0

I'm trying to build search functionality for a reality website. I want to be able to search by multiple parameters at a time, similar to what you would see on almost any retail website. I'm using Laravel on my project and I want to be able to make use of the Query Builder so I can use it's built in pagination.

If I try something like:

$listing = DB::select('select * from listings where city = 'Chicago');

I can't paginate the results.

The other approach would be to do this:

$listing = DB::table('listings')->where('city', 'Chicago')->get();

But the problem is that I don't know how many parameters a user might enter into the search. So how would I build a function call that could look like:

$listing = DB::table('listings')->where('city', 'Chicago')->where('askingPrice', '>', 50000)->where('bedrooms', '>', 3)->get();

1 Answer 1

1

Let's say you have this parameters:

<?php
$parameters = array(
    'one' => 'a',
    'two' => 'b',
    'three' => 'c'
);

Create object:

<?php
$listing = DB::table('listings');

And then, loop:

<?php
foreach ($parameters as $key => $value) {
    $listing = $listing->where($key, $value);
}

Of course you have to improve it to handle > and others. But I think you get it, right?

At last:

<?php
$listing = $listing->get();
Sign up to request clarification or add additional context in comments.

4 Comments

Does this query the database multiple times or only when you use get()?
Only when get() is used. where() returns \Illuminate\Database\Query\Builder not executing query.
When I do this I can't paginate. I thought I would be able to substitute $listing->get(); with $listing->paginate(20);
Not sure what I had done before but I am getting my pagination links now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.