'"Property [id] does not exist on the Eloquent builder instance.", laravel 8 Api Resource
IN CONTROLLER ;
public function index()
{
$conversations = Conversation::where('user_id',auth()->user()->id)->orWhere('second_user_id',auth()->user()->id);
$count = $conversations->get()->count();
//
for($i=0;$i<$count;$i++) {
for ($j = $i + 1; $j < $count; $j++) {
if ($conversations[$i]->messages->last()->id < $conversations[$j]->messages->last()->id) {
$temp = $conversations[$i];
$conversations[$i] = $conversations[$j];
$conversations[$j] = $temp;
}
}
}
// return ConversationResource::collection($conversations);
return new ConversationResource($conversations);
}
App\Http\Resources\ConversationResource;
public function toArray($request)
{
return [
'id'=> $this->id,
'created_at'=>$this->created_at,
'message'=>MessageResource::collection($this->messages),
];
}
USE App\Http\Resources\ConversationResource;
public function toArray($request)
{
return parent::toArray($request);``
}
Solution 1:[1]
Change this line:
$conversations = Conversation::where('user_id',auth()->user()->id)->orWhere('second_user_id',auth()->user()->id);
to this (add get() in the end):
$conversations = Conversation::where('user_id',auth()->user()->id)->orWhere('second_user_id',auth()->user()->id)->get();
and change the $count too:
$count = $conversations->count();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rouhollah Mazarei |
