IsmaElzem :
I have 2 table: User
& Demands
. Inside the table Demands
, I have the user_id
as a foreign key. The User log in with a name (which I have throught the Session). What I want to do is: - Have the name of the User (his log in)-> since I do not have the session implemented, I write the name directly inside the code. - Search his ID thanks to his name. - Search all of his demands with his id.
$name = "Jason";
$UserID = User::select('id')->where('name', '=', $name)->get();
$User= User::find($UserID);
$demands = Demand::where('user_id', '=', $UserID)->get();
echo $demands;
My array is then empty. But inside my database, I do have 3 demands of this user_id...
Do you guys have any clue please ?
Cordially.
jfadich :
Everyone else is right that the first query returns a collection. But you're doing an extra query that is not needed here. This can be simplified to query the users table only once.
$name = "Jason";
$User = User::where('name', '=', $name)->first();
//$User= User::find($UserID); remove this as it is not needed.
if(!$User) {
return "User not found";
}
$demands = Demand::where('user_id', '=', $User->id)->get();
echo $demands;