Support the ongoing development of Laravel.io →
Requests Architecture

I want to reuse the logic of binding a {slug} to a model, in several resources.

Route::bind("slug", function($slug) {
	$item=Item::where('slug', $slug)->first();
	
	if($item)
	{
		return $item;	
	}
	else {
		App::abort(404);
	}
});

How can I reuse this code to use it for other resources like posts, ...

Should I define a function like this

function slug_model_binder($slug, $Model) {
	$model=$Model::where('slug', $slug)->first();
	
	if($model)
	{
		return $model;	
	}
	else {
		App::abort(404);
	}	
}

and use several calls to Route::bind() for different models like this:

Route::bind('item', function($slug) {
	return slug_model_binder($slug, 'Item');
});

Route::bind('post', function($slug) {
	return slug_model_binder($slug, 'Post');
});

Or can $route param of the binder callback help me to determine the current model?

what's the common practice for this functionality?

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

mtvs mtvs Joined 28 Jul 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.