Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tjkalinowski's avatar

How to do it in Laravel way?

Hello!

How to build query in Laravel way?

We have 3 tables : [events] + [types] + [users]

[events] belongsTo [types] + [types] manyToMany [users]  or 
[users] manyTomay [types]  + [types] haveMany [events]

How to build this: SELECT * FROM TABLE events WHERE belongs to type of current user

In other words:

I want to display all events from table events, which have type_id attached to user currently logged.

I am able to check current users ID:

$currentUser = Auth::id();         // it is 10

I am able to check which types belongs to a user

$user = User::find(10);
$types = $user->types->pluck('id')->all();   // returns 1,6

I want to display all record from events which have 1 or 6 type_id.

How to build that query?

I do not want to build that, this is very bad idea. Because I do not know how many of Users has the same Type, so next query is a bad idea. I know it

$events1 = Event::where(type_id, 1)->get();
$events2 = Event::where(type_id,6)->get();

Please Help :)

0 likes
4 replies
NKHO's avatar

I'm not sure what you're asking. Do you want to chain multiple ->where() clauses together?

$events_one = Event::where('type_id', '=', 1)->where('user_id', '=', Auth::user()->id);
Snapey's avatar

hasManyThrough should do it but I don't have any data suitable for testing it.

User.php

public function events()
{
    return $this->hasManyThrough(App\Event::class, App\Type::class);

}

Then you can $user->load('events');

tjkalinowski's avatar

@nkho it is wrong replay. This code will not work, Event table do not have user_id. This is not display 1 and 6 type_id.

I will look at @snapey replay and think about, to understand. This is possible solution I am looking for.

tjkalinowski's avatar

I have found whereIn!

This is example, which works:

$user = App\User::find(10) // id=10
$types = $user->types->pluck('id')->all() // array [1,6]
App\Event::whereIn('type_id', $types)->get() // works!

Please or to participate in this conversation.