Search code examples
laravel-8php-8.1

Laravel Route Model Binding, shows 404 when i passed encrypted Id for Editing


When i used to edit Language table i have used route model binding method which is more easier. but my client have a requirement that all the id's passing through URL should be encrypted. here my attempt failed with 404

edit.blade.blade

   <a href="{{ route('admin.languages.edit', ['language' => encrypt($language->id)]) }}">
     <i class="icon-note icons"></i>
   </a>

LanguageController

 public function edit(Language $language)
 {
   return view('admin.language.edit',compact('language'));
 }

enter image description here


Solution

  • If the model id in the url is encrypted you cannot use route model binding.

    However you can customize the way Route Model Binding is resolved for a specific model. In the file app\Providers\RouteServiceProvider.php you may use the Route::bind method. The closure you pass to the bind method will receive the value of the URI segment and should return the instance of the class that should be injected into the route. Again, this customization should take place in the boot method of your application's RouteServiceProvider:

    use App\Models\Language;
    use Illuminate\Support\Facades\Route;
    use Illuminate\Support\Facades\Crypt;
     
    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        Route::bind('language', function ($value) {
            $id = Crypt::decryptString($value);
        
            return Language::where('id', $value)->firstOrFail();
        });
     
        // ...
    }