Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit route model binding in Lumen?

Tags:

php

laravel

lumen

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.

like image 935
Rob Avatar asked Feb 27 '16 13:02

Rob


People also ask

What is Route model binding?

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.

Which types of route model binding are supported in laravel?

Laravel currently supports two types of route model bindings. We have: Implicit model binding. explicit model binding.


1 Answers

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();
}
like image 65
Mohamed Gharib Avatar answered Oct 15 '22 09:10

Mohamed Gharib