I'm starting with Laravel. I have LinksController that handle my links table (CRUD). I want to use this table to store all the links from my app.
I have two tables:
- tutorials
- posts
LinksController.php
public function store(Request $request, Tutorial $tutorial) {
$link = new Link;
$link->user_id = auth()->user()->id;
$link->source_id = $tutorial->id;
$link->link = $request->link;
$link->save();
}
This works fine. Now I was trying to save posts links and I noticed my route model binding can use only one Model.
Routes:
tutorials/{tutorial}/links
posts/{post}/links
If I change Tutorial $tutorial for Post $post it will work for posts but not for tutorials.
I read about Polymorphic Relationships but I'm not sure how to pass different models to my LinksController.
Should I use something like this in my LinksController.php:
private $model;
public function __construct(Request $request) {
// if route a
// $this->model = Tutorial::class;
// else
// $this->model = Post::class;
}
I know that I can use hidden input to pass model, but I don't really want to do that.
Edit: Other solutions that come to my mind would be Explicit Binding:
RouteServiceProvider.php
Route::model('tutorial', \App\Tutorial::class);
Route::model('post', \App\Post::class);
And then in my LinksController store method:
public function store(Request $request, Model $model) {
Do you think this would be a good approach? In this case, the first parameter from the route should always be a variable that is present in my RouteServiceProvider.
Is there any better and more elegant approach to my problem?