How to fix Laravel resource is not working properly in blade view?

394 views Asked by At

I'm confused why casted props are inaccessible in the blade file. When I try to check it in the controller its showing properly.

Here's the JSON shown in the browser: return $users; (here status is string) enter image description here

But when I tried to show it in the view, the status goes back to int which is the original value. enter image description here

@foreach ($users as $user)
  <h1>{{ $user->status }}</h1>
@endforeach

And when I tried to dd in the blade view it shows the original model values.


Here's my resource file (shortened version):

public function toArray($request)
{
    return [
        'status' => StatusEnum::value($this->status),
        ...
    ];
}

Here's my controller look like:

public function index()
{
    $record = User::all();
    $users = UserResource::collection($record);

    return view('pages.user.index', compact('users'));
}

I already tried solutions from other related QA e.g. ->resolve() but not working properly.

2

There are 2 answers

1
Omar Alkattan On

Make sure user model doesn't has getStatusAttribute() function nor status() if it returns a related model.

Keep in mind that this may be due to inherited or imported classes and traits in User model

0
Azade On

I had the same problem as you, and could fix it, now I share my solution with you:

In your controller, convert the collection of resources to JSON using the toJson method:

$items = ProductResource::collection($yourCollection)->toJson();
return view('view.show', compact('items'));

In your Blade view decode the collection:

@php
 $items=json_decode($items) 
 @endphp
...
  @foreach ($items as $item)
     ...
  @endforeach