Home > Blockchain >  How to search relationship in laravel?
How to search relationship in laravel?

Time:07-24

I have two models which are related. I am trying to do a search in orders and only display the actual search results instead of ALL orders of the category and user in which the order was found.

public function up()
{
    Schema::create('orders', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->foreignId('category_id')->constrained()->cascadeOnDelete();
        $table->foreignId('report_id')->constrained()->cascadeOnDelete();
        $table->string('time');
        $table->string('date');
        $table->integer('issue_number');
        $table->boolean('status');
        $table->text('description')->nullable();
        $table->timestamps();
    });
}

So, what I WANT to achieve is the following. What I WANT to be displayed is:

OrderController.php

public function index()
{
    $keyword = request('search') ?? null;
    $orders = Order::query()->whereIn('user_id', $user->id)->whereIn('category_id', $category->id)
        ->orWhere(function ($query) use ($keyword) {
            $query->when($keyword, function ($query) use ($keyword) {
                $query->where('first_name' , 'LIKE' , "%{$keyword}%");
            });
        })->latest()->paginate(25);
    return view('Admin.orders.index', compact('orders'));
}

Order.php

public function user()
{
    return $this->belongsTo(User::class);
}

public function report()
{
    return $this->belongsTo(Report::class);
}

public function category()
{
    return $this->belongsTo(Category::class);
}

CodePudding user response:

If I got you right you want to apply filter to your related table. For that kind of operation you can use whereHas or whereRelation methods of eloquent.

$posts = Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'code%');
})->get();

or

$posts = Post::whereRelation(
    'comments', 'created_at', '>=', now()->subHour()
)->get();

comments is related column.

For more information check Querying Relationship Existence.

  • Related