Sakibul Alam
Sakibul Alam

Reputation: 1823

Laravel 4 Eloquent Dynamic Where Clause

I recently learned about dynamic where clauses (I think that's what is called) in Laravel 4 Eloquent which makes where clauses like User::where('first_name', 'Jon')->get() becomes nicer User::whereFirstName('Jon')->get(). How flexible is this??

Can i for example do the following

Upvotes: 0

Views: 4726

Answers (1)

JofryHS
JofryHS

Reputation: 5874

You can use Query Scope to achieve what you needed.

A simple illustration:

public function scopeFirstOrLastName($query, $first, $last)
{
    return $query->where('first_name', 'LIKE', '%' . $first . '%')
                 ->where('last_name', 'LIKE', '%' . $last . '%');
}

Using it:

$user->firstOrLastName('John', 'Doe')->get();

You can name it as you see fit, and you can use any operator (or any query builder operation) inside.

Upvotes: 5

Related Questions