PHP code example of soyhuce / laravel-model-injection

1. Go to this page and download the library: Download soyhuce/laravel-model-injection library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

soyhuce / laravel-model-injection example snippets


use Soyhuce\ModelInjection\ValidatesImplicitBinding;

class Post extends Model 
{
    use ValidatesImplicitBinding;
    
    /**
     * @return array<string, mixed>
     */
    public function routeBindingRules(): array
    {
        return [
            'id' => 'integer',
            'slug' => ['string', 'min:5']
        ];
    }
}

Route::get('posts/{post}', function(Post $post) {
    //...
});

Route::get('posts-by-slug/{post:slug}', function(Post $post) {
    //...
});

InvalidRouteBinding::handleUsing(function (string $class, string $field): never {
    Log::error("Invalid binding for $class on $field.");

    abort(422);
});

use Soyhuce\ModelInjection\BindModels;

class RouteServiceProvider extends ServiceProvider {

    use BindModels;

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot() {
        parent::boot();

        $this->bindModel('user', User::class, 'integer'); // Validates that the parameter is an integer
        
        // You can bind a model explicitly on a given column
        $this->bindModelOn('post', Post::class, ['string', 'min:5'], 'slug');
    }
}