I'm using laravel resources to get data for api:
return [
'id' => $this->id,
'unread' => $this->unread,
'contact' => UserResource::collection($this->users),
];
And this is working fine. The problem is when 'users' is empty. I mean - not every time my controller is loading users from my relations:
$offers = Offer::where('user_id', $user_id)->orderBy('created_at','desc')->get();
foreach ($offers as $offer)
{
$offer->setRelation('users', $offer->users->unique());
}
return OfferShortResource::collection($offers);
sometimes - this relation does not exists. But not the relation is problem, because - my resource is not loading the relation - the relatin is loaded inside controller.
So how can I add some kind of logic to resources? - to tell basically - users property may not exists - then do not load data here, or even - do not check $this->users
relation
edit: I tried to make it like this:
use Illuminate\Support\Arr;
...
'contact' => $this->when(Arr::exists($this, 'users'), function () {
return UserResource::collection($this->users);
}),
but this is giving always false
edit 2: relation in the Offer model
public function users(){
return $this->belongsToMany(User::class, 'messages', 'offer_id', 'from')
->where('users.id', '!=', auth()->user()->id);
Try using whereHas
:
Offer::whereHas('users', function ($query) use ($user_id) {
$query->where('user_id', $user_id);
})->orderByDesc('created_at')->get();
The optional helper is useful for accessing properties that may not be defined:
optional($this->user)->name
The when
method should work for you, try the following:
'contact' => $this->when(property_exists($this, 'users'), function () {
return UserResource::collection($this->users);
}),
Also try:
isset($this->users)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With