Laravel WhereHas Eloquent Example

Apr 28, 2021 . Admin

Hello Friends,

Now let's see example of how to use whereHas condition in laravel. This is a short guide on laravel if whereHas condition. We will use how to use whereHas condition in laravel. Here you will learn how to use whereHas condition in laravel. We will use how to use if whereHas condition in laravel. Let's get started with how to whereHas condition use in laravel.

Here i will give you many example how you can check whereHas condition in laravel.

Example WhereHas Eloquent:

Now this example, If you need even more power, you may use the whereHas methods to put "where" conditions on your has queries.

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models\Service;
use App\Models\User;
use App\Http\Controllers\Controller;


class ServiceController extends Controller
{
     /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {

        $services = Service::whereHas('user', function($q){
            $q->where('is_active', '=', 1);
        })->get()->toArray(); 

        dd($services);
    }
}
?>
Output:
array:3 [▼
  0 => array:7 [▼
    "id" => 1
    "name" => "E-Commerce"
    "description" => "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit."
    "icon" => "1617280462-agency.jpeg"
    "created_at" => "2021-04-01T12:34:22.000000Z"
    "updated_at" => "2021-04-23T13:15:28.000000Z"
    "user_id" => 1
  ]
  1 => array:7 [▼
    "id" => 2
    "name" => "Responsive Design"
    "description" => "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit."
    "icon" => "1617280510-agency2.jpeg"
    "created_at" => "2021-04-01T12:35:10.000000Z"
    "updated_at" => "2021-04-19T12:24:33.000000Z"
    "user_id" => 13
  ]
  2 => array:7 [▼
    "id" => 3
    "name" => "Web Security"
    "description" => "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit."
    "icon" => "1617280535-key.jpg"
    "created_at" => "2021-04-01T12:35:35.000000Z"
    "updated_at" => "2021-04-19T12:24:40.000000Z"
    "user_id" => 1
  ]
]

It will help you....

#Laravel 8 #Laravel