CoderTn
CoderTn

Reputation: 997

Query database table using LIKE in Laravel

I am trying to query a table using where like :

Auth::user()
    ->friends
    ->where('friend.first_name','LIKE','%'.$firstName.'%')
    ->all()

The query does work properly without using the LIKE statement only when i add the LIKE keyword it doesn't return any results.

Upvotes: 0

Views: 277

Answers (3)

Cheng Shi
Cheng Shi

Reputation: 220

I think you are confused between a laravel relation and a eloquent collection. First let me go straight to answer, you would have to do

Auth::user()
    ->friends()
    ->where('friend.first_name','LIKE','%'.$firstName.'%')
    ->get()

To explain what's wrong with your code, ->where('name', 'Like', '%something%') This is a query builder method. You have to use it on the query builder, or Before you actually retrieve the model / model collection.

Auth::user()->friends()

This would give you a relation Illuminate\Database\Eloquent\Relations\HasMany that you can apply where like on.


Auth::user()->friends

This will return you a Illuminate\Database\Eloquent\Collection. And yes, it is a collection, so you will have to use collection method. Take a look at the where method for collection. You can see it only support key => value pair. It does not support "LIKE"

The where method filters the collection by a given key / value pair:

If you want to use achieve a "Like" on collection, you can probably use the filter method, which support custom callback.

The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:

To conclude, when you define a friends "HasMany" relation on User, you have two way to retrieve it.

If you want to apply additional query builder method, you need to use user->friends() which do not return you data, it return you a relation that you can use query builder method. Once you do user->friends, it get you a collection. You cannot apply query builder on that anymore. So basically, user->friends is act the same way as user->friends()->get()

Upvotes: 0

Smit Desai
Smit Desai

Reputation: 1

Don't Use all() and use get().

Auth::user()->friends()->where('something','LIKE','%'.$something.'%')->get()

Upvotes: 0

Watercayman
Watercayman

Reputation: 8178

Using all() will work without the builder where() statement.

When grabbing data using the query, use get() instead:

Auth::user()->friends->where('something','LIKE','%'.$something.'%')->get()

Upvotes: 1

Related Questions