0

Consider the main category subcategory mentality. I want to have the following when a link is clicked.

I can do : www.localhost.com/category/

i want to do: www.localhost.com/category/vehicle

derivatives: www.localhost.com/category/vehicle/bmw www.localhost.com/category/vehicle/bmw/bmm-x7-series

Route::get('/category/{id}', 'CategoryController@index')->name('category.index'); ` 

my route below:

Route::get('/category/{slug}', 'CategoryController@index')->where('slug' , '[\w\d\-\_]+'); 

I created a control named CategoryController

class CategoryController extends Controller { public function index($slug) { $category = Category::where('slug' , $slug)->first(); return view('category.show' , compact('category')); } 

my view content(category.show.blade.php)

{{$category->slug}} <a href="{{ url('/category/' . $category->slug) }}" class="uhover">life is good. {{url($category->slug)}}</a> 
1
  • first glance, I think your issue is that you are using the {id} token, which IIRC laravel thinks should be an integer, so maybe try using a different variable name. Also, this question may provide some context for your conundrum. Commented Jan 9, 2018 at 16:40

1 Answer 1

1

If you want to have the category / brand of the vehicles in the URL and not the ID, then you will need to remove /{id} from your route and replace it with a /{slug}.

So you route would probably look like this:

Route::get('/category/{slug}', 'CategoryController@index')->name('category.index'); 

You will have to change your method to something like:

// Show Method public function show($slug){ $category = Category::where('slug', $slug)->first(); return view('game.show', compact('category')); } 

Ideally, to make sure that the slug is unique, you would store it in the database. You can take advantage of Laravel's slug helper to do so and if the slug already exists, just append a suffix to make it unique.

You can use generate the slug model:

class Item extends Model { public static function boot() { parent::boot(); static::saving(function ($model) { $model->slug = str_slug($model->name); }); } } 

If you want to use route–model binding, then you’ll need to tell Eloquent the column to use should be your slug column instead

public function getRouteKeyName() { return 'slug'; } 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks bro, but do not apply. :(
how come? Did I misunderstand your question? Give us more details so we can help.
Unfortunately I do not really know English. Thank you for your interest.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.