Razvan George
Razvan George

Reputation: 117

Laravel create a route with slug and id

At this time i have

Route::get('properties/{id}', 'InfoController@show');

And the link looks like mydoamin.com/properties/1

Is there any posibility to create a route to have properties/id/slug(from title) ?

Upvotes: 1

Views: 8181

Answers (4)

Keith Turkowski
Keith Turkowski

Reputation: 811

Add this to your ModelController (with a slug field and regular CRUD show function)

public function slug($slug) { return $this->show(Model::where('slug', $slug)->firstOrFail()); }

Add this route to web.php (to match all non-all-numeric slugs not containing '/'

Route::get ('model/{slug}', 'ModelController@slug')->where(['slug' => '^(?!((.*/)|(create$))).*\D+.*$']);

Make sure it comes before

Route::resource('model', 'ModelController');

You'll match any non-all-numeric slugs, but pass through integers to the regular route.

Upvotes: 0

H H
H H

Reputation: 2123

Yes, you can achieve this by doing the following:

Update your route:

Route::get('properties/{id}/{slug}', 'InfoController@show');

Then accept the route in your controller and check there is a valid model with the given id and slug.

public function show($id, $slug) {
    $model = Model::where('id', $id)
                  ->where('slug', $slug)
                  ->first();

    if(! $model) {
        // handle error here
    }

    return view('show', compact('model'));
}    

(Note that validation can also be done by creating a custom Form Request: https://laravel.com/docs/5.6/validation#form-request-validation)

Upvotes: 6

webcodecs
webcodecs

Reputation: 217

You can edit the route to Route::get('properties/{id}/{slug}', 'InfoController@show');

The check if the slug can be matched with the title have to placed in the controller.

Upvotes: 0

webdevtr
webdevtr

Reputation: 480

yes, you can do like this,

Route::get('properties/{id}/{title}', 'InfoController@show');

on show function

public function show ($id, $title) {

I hope this will help you

Upvotes: 2

Related Questions