Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
How can I search with belongsto laravel?

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');
    }
    ...
}
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Use whereHas():

Store::whereHas('user', function($q) use($username) {
        $q->where('name', 'like', '%'.$username.'%');
    })->paginate(5);
over 4 years ago · Santiago Trujillo Report

0

You can do it using Searchable package in order to search through the model fields and its relations fields

use Nicolaslopezj\Searchable\SearchableTrait;

class User extends \Eloquent
{
use SearchableTrait;

/**
 * Searchable rules.
 *
 * @var array
 */
protected $searchable = [
    /**
     * Columns and their priority in search results.
     * Columns with higher values are more important.
     * Columns with equal values have equal importance.
     *
     * @var array
     */
    'columns' => [
        'users.first_name' => 10,
        'users.last_name' => 10,
        'users.bio' => 2,
        'users.email' => 5,
        'posts.title' => 2,
        'posts.body' => 1,
    ],
    'joins' => [
        'posts' => ['users.id','posts.user_id'],
    ],
];

public function posts()
{
    return $this->hasMany('Post');
}

}

use :

$users = User::search($query)->get();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!