analnassorog
analnassorog

Reputation: 23

Laravel - Customize the key in the route model binding with json field

I want to customize the key in the route model binding and i do something like this -

use App\Models\Post;

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

But my slug is a json multilingual field and holds data like this -

{
  'en': 'hello'
  'ru': 'привет',
  'de': 'hallo',
}

I already have a mechanism to retrieve the subdomain and assign the corresponding prefix to some $subdomain variable, so i already know which language i should grab from the DB, but how do i embed this $subdomain inside the route itself? Something like -

Route::get('/posts/{post:slug->$subdomain}', function (Post $post) {
    return $post;
});

I even tried to put the whole route into a pre-defined string with something like this -

$post_url = '/posts/{post:slug->'.$subdomain.'}';
Route::get($post_url, function (Post $post) {
    return $post;
});

And it also resulted in constant 404 errors. What am I doing wrong?

Upvotes: 0

Views: 1142

Answers (1)

analnassorog
analnassorog

Reputation: 23

My solution was to explicitly bind this route inside the RouteServiceProvide.php like this -

Route::bind('post', function ($value) {
            $slug = "slug->".$subdomain;
                return Post::where($slug, $value)->firstOrFail();
        });

Then I could easily access any language version of the post.

Upvotes: 2

Related Questions