Look at this example:
use App\Http\Resources\UserResource;
use App\Models\User;
Route::get('/user/{id}', function ($id) {
return new UserResource(User::findOrFail($id));
});
How does this internally work? Because at first glance we just return an Object of the class UserResource. But Laravel is magically calling the toArray function and resolves it correctly.
I want the same for my Recommendation class to work.
use App\Http\Recommendations\RecentlyUpdatedRecommendation;
use ...
Route::get('/someurl', function () {
return ['collections' => [
new RecentlyUpdatedRecommendation(),
new WatchlistRecommendation(),
new LastWatchedRecommendation(),
...
]];
});
With
/**
* All Recommendations use this as output
*/
abstract class Recommendation
{
// No Idea what needs to be put here
}
The output array/json should resolve into this:
return [
'title' => $title,
'description' => $description,
'courses' => (collection) $courses
];
Any resource that you create is instance of
Illuminate\Contracts\Support\ResponsableInterface, This means that each of them must havetoResponsemethod implemented.If we look at
JsonResponse'stoResponsemethod we see this code:Internally it is calling
Resource'sresolvemethod.resolvemethod is where we seetoArraymethod to be calledBy creating new response you are just overriding
toArraymethod with your logic.In Your case, you don't need to write too much to get
toArraymethod "magically" calledNow watch will happen, When you return
['collecion' => new SomeRecomendation()], Laravel callsjson_encodeon it ( to return response as json ), Becausenew SomeRecomendation()is instance ofJsonSerializableit will calljsonSerializemethod and encodes an array returned from it.When you return only
return new SomeRecomendation();from controller, it will call, because it is instance ofArrayable, Laravel callstoArraymethod magically.Hope this answer helps you.