Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I search with belongsto laravel?

Tags:

My query to search for a username in a store listing is as follows:

$data = Store::join('users AS b', 'b.id', '=', 'stores.user_id')
             ->where('b.name', 'like', '%hazard%')
             ->paginate();

It works. But I use join to do it.

How can I do it using belongto?

My store model is like this :

class Store extends Model
{   
    protected $fillable = ['name', 'user_id', ...];
    public function user()
    {
        return $this->belongsTo(User::class,'user_id', 'id');
    }
    ...
}
like image 587
samuel toh Avatar asked Apr 23 '17 06:04

samuel toh


People also ask

What is belongsTo in Laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.

What does get () do in Laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.

How do you belong to a relationship?

Belongs To relation defines that an entity is owned by a related entity on the exclusive matter. Example: a post belongs to an author, a comment belongs a post. Most belongsTo relations can be created using the inverse option of the declared hasOne or hasMany relation.


1 Answers

Use whereHas():

Store::whereHas('user', function($q) use($username) {
        $q->where('name', 'like', '%'.$username.'%');
    })->paginate(5);
like image 138
Alexey Mezenin Avatar answered Sep 21 '22 10:09

Alexey Mezenin