Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Pixelairport's avatar

Route binding in Spatie Package Tools

I have a problem and tested a lot right now, but nothing works. It seems that the timing of loading my routes is wrong, but I dont know how to solve it.

I have a package which uses spatie package tools:

$package
            ->name('ez-posts')
            ->hasRoutes(['web']);

But the route binding is not working. If the following code is in my main web.php file of laravel it works, but not in the package web.php file. The model will not be found:

Route::get('bla/{post}', function (Post $post) {
    dd($post);
});

I also tried to load web.php in boot(), packageBooted() or bootingPackage() methods. Noting works.

0 likes
1 reply
LaryAI's avatar
Level 58

Certainly! The issue you're facing is a common one when developing Laravel packages with spatie/laravel-package-tools. The problem is that route model binding (e.g., {post} resolving to a Post model) only works if Laravel knows how to resolve the binding. By default, Laravel looks for bindings registered in the main app's RouteServiceProvider. When your routes are loaded from a package, you need to ensure the binding is registered before your package routes are loaded.

Solution

1. Register Route Model Bindings in Your Package

You should register your route model bindings in your package's service provider, specifically in the boot method before the routes are loaded. With spatie/laravel-package-tools, you can use the bootingPackage() method for this purpose.

Example:

use Illuminate\Support\Facades\Route;
use Vendor\Package\Models\Post;

class EzPostsServiceProvider extends PackageServiceProvider
{
    public function bootingPackage()
    {
        // Register the binding before routes are loaded
        Route::model('post', Post::class);
    }

    public function configurePackage(Package $package): void
    {
        $package
            ->name('ez-posts')
            ->hasRoutes(['web']);
    }
}

2. Why bootingPackage()?

  • bootingPackage() is called before the package's routes are registered.
  • This ensures that when Laravel parses your package's web.php routes, it already knows how to resolve {post} to your Post model.

3. Double-check Model Namespace

Make sure the Post model's namespace matches what you use in Route::model().

4. Clear Cached Routes

If you have previously cached your routes (php artisan route:cache), clear them:

php artisan route:clear

Summary

  • Register your route model bindings in bootingPackage().
  • Use Route::model('post', Post::class); before routes are loaded.
  • Clear cached routes if necessary.

This will ensure your route model binding works in your package routes just like it does in your main app.

Please or to participate in this conversation.