Skip to content
Advertisement

Laravel filter relationship data

Code

public function getCauserDetails(){
   return $this->belongsTo(Users::class, 'causer_id', 'id');
}

$name = testtt; //data to find

ActivityLog::where('causer_id', $userid)
    ->orWhere('subject_id', $userid)
    ->with('getCauserDetails')
    ->whereHas('getCauserDetails', function ($q) use ($name) {
        $q->where('name', "=", 'testtt');
    })
    ->get()
    ->toArray();

Data return

Array
(
    [0] => Array
        (
            [id] => 22
            [log_name] => login
            [subject_type] => AppModelsUsers
            [subject_id] => 0
            [causer_id] => 2
            [created_at] => 2021-05-18 21:27:07
            [updated_at] => 2021-05-18 21:27:07
            [get_causer_details] => Array
                (
                    [id] => 2
                    [name] => lim
                )
        )

    [1] => Array
        (
            [id] => 21
            [log_name] => logout
            [subject_type] => AppModelsUsers
            [subject_id] => 0
            [causer_id] => 2
            [created_at] => 2021-05-18 21:26:57
            [updated_at] => 2021-05-18 21:26:57
            [get_causer_details] => Array
                (
                    [id] => 2
                    [name] => Senior
                )

        )

    [2] => Array
        (
            [id] => 22
            [log_name] => logout
            [subject_type] => AppModelsUsers
            [subject_id] => 0
            [causer_id] => 2
            [created_at] => 2021-05-18 21:26:57
            [updated_at] => 2021-05-18 21:26:57
            [get_causer_details] => Array
                (
                    [id] => 2
                    [name] => testtt
                )

        )
)

Question: I tried to filtering data that if a relationship “getCauserDetails”, How can I not show the data if the relationship name is only found “test” or should I say null? So on the example output, it displays all the data, but I want to only the data that I filter just retrieve.

Advertisement

Answer

Because of your orWhere() you need to nest it:

$name = 'testtt'; //data to find

ActivityLog::with('getCauserDetails')
    ->where(function($q) {
        $q->where('causer_id', $userid)
        ->orWhere('subject_id', $userid)
    })
    ->whereHas('getCauserDetails', function ($q) use ($name) {
        $q->where('name', "=", $name);
    })
    ->get()
    ->toArray();

You can filter the relation, too:

$name = 'testtt'; //data to find
ActivityLog::where('causer_id', $userid)
    ->orWhere('subject_id', $userid)
    ->with(['getCauserDetails' => function ($q) use ($name) {
        $q->where('name', "=", $name);
    }])
    ->whereHas('getCauserDetails', function ($q) use ($name) {
        $q->where('name', "=", $name);
    })
    ->get()
    ->toArray();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement