Support the ongoing development of Laravel.io →
posted 3 years ago
Eloquent
Last updated 2 years ago.
0

Hey!

In your Event model you can add a method like this:

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

and in your User model add a method like this:

public function events()
{
    return $this->hasMany(\App\Models\Event::class);
}

To get the events of type created from a User you can use something like this:

// Get the current logged in user
$user = auth()->user();

// Get the Events of type "created"
$events = $user->events()->where('event_name', '=', 'created')->get();

For eager loading you'd have to use Constraining eager loading like this:

$events = $user->with(['events' => function($query) {
    $query->where('event_name', '=', 'created');
}])->get();

Have a great day!

Tom

Last updated by @tomhatzer 2 years ago.
0

Hello @tomhatzer

Thanks for the answer but in the example, you do not include the 3rd table which is activity_log

0

You can use MorphTo and MorphOne relation in your models

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Yannik yannik-slym Joined 17 Feb 2020

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.