I'm trying to use implicit route model binding in Lumen but seems it's not working.
Is there anyway to enable this?
$app->get('/users/{user}', 'UsersController@get');
It's just returning the value in user
but it's not type hinting it and returning the model.
Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user's ID, you can inject the entire User model instance that matches the given ID.
Laravel currently supports two types of route model bindings. We have: Implicit model binding. explicit model binding.
I created a package to add support for route-model-binding
in Lumen, Check it out here :
Lumen Route Binding
It requires :
php >= 7.1
Lumen 5.* || 6.*
It supports Explicit binding :
$binder->bind('user', 'App\User');
Implicit binding :
$binder->implicitBind('App\Models');
And Composite binding : (bind more than one wildcard together, In situations like posts\{post}\comments\{comment}
you will be able to bind it to a callable that will resolve the Post
and the Comment
related to the post)
$binder->compositeBind(['post', 'comment'], function($postKey, $commentKey) {
$post = \App\Post::findOrFail($postKey);
$comment = $post->comments()->findOrFail($commentKey);
return [$post, $comment];
});
Also can work with other classes like Repositories
:
// Add a suffix to the class name
$binder->implicitBind('App\Repositories', '', 'Repository');
Can use a custom method on the repository :
// Use a custom method on the class
$binder->implicitBind('App\Repositories', '', 'Repository', 'findForRoute');
Where in the repository class you can do :
public function findForRoute($val)
{
return $this->model->where('slug', $val)->firstOrFail();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With