Route Model Binding - nevadskiy/laravel-translatable GitHub Wiki
You can use Route Model Binding feature to resolve models by a translatable attribute.
For example, let's set up the Book
model to work with Route Model Binding by a translatable slug
attribute.
The Extra Table strategy is best for this case.
First we need to define 2 tables: books
and book_translations
.
The simplest books
table migration might look like this:
Schema::create('books', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
Define the unique slug
field in the extra translations table:
Schema::create('book_translations', function (Blueprint $table) {
$table->id();
$table->foreignId('book_id')->references('id')->on('books');
$table->string('locale', 2);
$table->string('slug')->unique();
$table->timestamps();
$table->unique(['book_id', 'locale']);
});
The Book
model will look like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Nevadskiy\Translatable\Strategies\ExtraTable\HasTranslations;
class Book extends Model
{
use HasTranslations;
protected $translatable = [
'slug',
];
}
Now that all the settings are complete, we can use the model with the Route Model Binding.
For example, you can add the following route to the routes/web.php
file:
Route::get('books/{book:slug}', function (Book $book) {
return view('books.show', ['book' => $book]);
});
The book model will be resolved from a route using the slug
attribute.