0
Route::get('/blog', 'BlogController@index')->name('blog');
Route::get('/blog/tag/{tag}', 'BlogController@index')->name('blog');
Route::get('/blog/category/{category}', 'BlogController@index')->name('blog');

I want to redirect different urls to same controller.

If the user filter for tag, send me link like : blog/tag/sample-tag

Or category : blog/category/sample-category

Or if user wants to see all blog : blog

I want to check in BlogController's index method like :

if ($request->has('tag') // return tag's blog content
else if ($request->has('category') // return category's blog content
else // return all blog content.

Laravel 5.6.*

Error:

Missing required parameters for [Route: blog] [URI: blog/category/{category}]

I call like this : <li><a href="{{ route('blog') }}">BLOG</a></li>

6
  • While you could use the same controller, I wouldn't recommend using the same route name or the same controller method. Why do the second two need to use the index method? Commented Feb 17, 2019 at 0:49
  • sorry my bad, i update with the error Commented Feb 17, 2019 at 0:49
  • should i create another controller for tag and category? @Devon Commented Feb 17, 2019 at 0:50
  • If you want to filter a resource index its better to use the query string, i.e: /blog?tag=laravel&category=programming Commented Feb 17, 2019 at 0:56
  • @dparoli is it good for seo? Commented Feb 17, 2019 at 0:59

3 Answers 3

3

It is better to sperate your routes into different controller method

// Define routes
Route::get('/blog', 'BlogController@index')->name('blog');
Route::get('/blog/tag/{tag}', 'BlogController@tag')->name('blog.tag');
Route::get('/blog/category/{category}', 'BlogController@category')->name('blog.category');

// Generate url
route('blog');
route('blog.tag', ['tag' => $tag]);
route('blog.category', ['category' => $category]);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Route::get('/blog/{second?}/{third?}','BlogController@index')->where(['second'=>'tag|category']);

Comments

0

It is better to separate your routes but you can do this by injecting the model into your method like this code:

public function index (?Tag $tag, ?Category $category)
{
    if($tag->exists){
       ....
    }
    if($category->exists){
       ....
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.