Partial reloads with Eloquent API Resource
Hello,
I have this code.
use App\Http\Resources\StudentResource;
use App\Http\Resources\SessionResource;
...
return Inertia::render('Students/Show', [
'students' => fn () => StudentResource($student->fresh()),
'sessions' => fn () => SessionResource(Session::
with('student')
->with('funding')
->with('path')
->with('project')
->with('level')
->with('type')
->with('state')
->where('student_id', $student->id)
->orderByDesc('date')
->get()
)
]);
I have this error : Call to undefined function App\Http\Controllers\StudentResource().
How is it possible to use a resource to partial reload the page ?
Thanks for your help.
Vincent
It's says undefined function in App\Http\Controllers\StudentResource, make sure you import it from the right place App\Http\Resources\StudentResource
Notice, it's Resources NOT Controllers.
@MohamedTammam Yes but it's the right place. I don't have this error if I use the resource outside the InertiaJS render method.
Laravel tries to identify the resource in the Controllers folder whereas it is imported (use) from the right place.
@vincent15000 What if you use
return Inertia::render('Students/Show', [
'students' => fn () => \App\Http\Resources\StudentResource($student->fresh()),
// ...
@vincent15000 And actually, you should have new keyword
return Inertia::render('Students/Show', [
'students' => fn () => new \App\Http\Resources\StudentResource($student->fresh()),
@MohamedTammam Adding the new keyword solves perhaps the problem for the resource, but I have now the same error message for the Session model.
@vincent15000 Then use new, To be honest I don't know how it's working without creating a new instance and just calling the class out.
@Sinnbeck , can you please assist for my question?
@MohamedTammam But I can't add the new keyword before the Session model.
@MohamedTammam I don't know but it doesn't work. But for the model, it was an error from me, I forgot to import (use) the model.
Now I don't have the same error, but another : I can't access to the properties of the model while constructing the resource.
@vincent15000 Yeah, you need to use the static method collection
'sessions' => fn () => SessionResource::collection(Session::
with('student')
->with('funding')
->with('path')
->with('project')
->with('level')
->with('type')
->with('state')
->where('student_id', $student->id)
->orderByDesc('date')
->get()
)
@MohamedTammam That's it ... thank you.
Here is the right code.
return Inertia::render('Students/Show', [
'students' => fn () => new StudentResource($student->fresh()),
'sessions' => fn () => SessionResource::collection(Session::
with('student')
->with('funding')
->with('path')
->with('project')
->with('level')
->with('type')
->with('state')
->where('student_id', $student->id)
->orderByDesc('date')
->get()
)
]);
The new keyword is only needed if I don't generate a collection of resources but only one resource.
Please or to participate in this conversation.