May 26, 2022
0
Level 3
API Resource Conditional and Inertia
I'm working with my first API Resource and having having trouble with using a conditional statement and can't figure out what I'm missing.
Here is the resource:
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
$this->when(Auth::user()->type === 'sos', [
'code' => $this->name,
'ctds' => $this->ctds,
'address' => $this->address,
'city' => $this->city,
'state' => $this->state,
'zip' => $this->zip,
'name' => $this->name,
'phone' => $this->phone,
'url' => $this->url,
'deleted_at' => $this->deleted_at,
]),
];
}
}
When I call the resource into a function below the condition works and I see the JSON file as expected:
class SfasController extends Controller
{
public function index() {
return SfaResource::collection(Sfa::query());
}
But when I try to pass it through an Inertia Route (below), the the property user.type returns null so the condition is never true.
class SfasController extends Controller
{
public function index() {
return Inertia::render('Sfas/Index', [
'sfas' => SfaResource::collection(Sfa::query()
->orderBy('name')
->paginate(10)
->withQueryString()),
'filters' => Request::all('search', 'trashed'),
]);
Here's the route:
Route::get('sfas', [SfasController::class, 'index'])
->name('sfas')
->middleware('auth');
I'm very new to this and sure it's some basic concept I've missed. Please let me know if more info would be helpful.
Please or to participate in this conversation.