Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shadrix's avatar
Level 12

How to resolve a class from a router / controller? (Similar to Eloquent API Resources)

I'm looking for a way that works similar to Eloquent API Resources. Unfortunately, my brain doesn't comprehend the magic behind it.

Similar like here:

use App\Http\Resources\UserResource;
use App\Models\User;

Route::get('/user/{id}', function ($id) {
    return new UserResource(User::findOrFail($id));
});

I want to use

use App\Http\Recommendations\RecentlyUpdatedRecommendation;
use ...

Route::get('/someurl', function () {
    return ['collections' => [
       new RecentlyUpdatedRecommendation(),
       new WatchlistRecommendation(),
       new LastWatchedRecommendation(),
       ...
    ]];
});

What can I do to get that syntax?

0 likes
1 reply
shadrix's avatar
Level 12

Ok I found some help! I leave this post be, maybe it's helpfull as well:

 abstract class Recommendation implements Arrayable, JsonSerializable {
  
 }

...

class SomeRecomendation extends Recommendation {

 public function jsonSerialize()
  {
    return $this->toArray();
  }

  public function toArray(){
    return [
      'title' => $title,
      'description' => $description,
      'courses' => (collection) $courses
    ];
  }
}

Now watch will happen, When you return ['collecion' => new SomeRecomendation()], Laravel calls json_encode on it ( to return response as json ), Because new SomeRecomendation() is instance of JsonSerializable it will call jsonSerialize method and encodes an array returned from it.

Please or to participate in this conversation.