Laravel models acts like array?
I know about PHP Array Objects but I have never seen laravel models working like this…Its kinda strange. Heres the actual code..
public function getUserChats()
{
$users = [];
$chats1 = Chat::where('sender_id','=',auth()->user()->id)->get();
$chats2 = Chat::where('reciever_id','=',auth()->user()->id)->get();
foreach ($chats2->toArray() as $chat2) {
$user = new UserResource(User::where('id','=',$chat2['sender_id'])->first());
array_push($users, $user);
}
foreach ($chats1->toArray() as $chat1) {
$user = new UserResource(User::where('id','=',$chat1['reciever_id'])->first());
array_push($users, $user);
}
return $users;
}
//The above method works but this one doesn't works
public function getUserChats()
{
$users = [];
$chats1 = Chat::where('sender_id','=',auth()->user()->id)->get();
$chats2 = Chat::where('reciever_id','=',auth()->user()->id)->get();
foreach ($chats2->toArray() as $chat2) {
$user = new UserResource(User::where('id','=',$chat2->sender_id)->first());
array_push($users, $user);
}
foreach ($chats1->toArray() as $chat1) {
$user = new UserResource(User::where('id','=',$chat1->reciever_id)->first());
array_push($users, $user);
}
return $users;
}
Notice inside the for each loop how I have to access the sender_id from $chat1 and $chat2 . I want to know whats actually going on .. Its more of a theoretical
question…Thanks for the response
from Laravel Questions and Answers https://laravelquestions.com/php/laravel-models-acts-like-array/
via Lzo Media
No comments:
Post a Comment