sharrpenized's avatar

Route model binding VS repository. Can they live together?

I have a controller. It has some methods with quite complex queries (like pagination) and also some very simple methods with trivilar queries (like destroy). It feels correct to put pagination logic in repository, however, I'm not sure what to do with the rest of controller methods which are trivial.

I could use Route Model Bindings:

public function destroy( Item $item )
{
    $item->delete();
    return redirect()->back()->withSuccess( 'Item deleted' );
}

However, the code above creates a hard dependency between Controller and Model. This could be solved with a repo like this:

public function destroy( $id )
{
    $this->repository->deleteById($id);
    return redirect()->back()->withSuccess( 'Item deleted' );
}

It kinda feels bad to mix route model binding together with repositories and I should probably stop using route model binding in favour of repos. Is that right?

0 likes
3 replies
bobbybouwmann's avatar
Level 88

Yea, stop with model binding and use the repository ;) Model binding is cool if you need to be quick but it doesn't make any sence in some cases!

bestmomo's avatar

Also possible is a mix :

public function destroy( Item $item )
{
    $this->repository->delete($item);
    return redirect()->back()->withSuccess( 'Item deleted' );
}

But as says @bobbybouwmann model binding, although it appears elegant, if often inopportune.

pmall's avatar

Dont use route model binding.

Mixing routing logic with model selection can be useful only to quickly prototype a project.

Please or to participate in this conversation.