Optional parameters on the Laravel Route

Asked

Viewed 1,766 times

2

I’m passing parameters on a Route using Laravel 5.8 like this:

Route::get('/cursos/{id_categoria_curso}/{id_atuacao_area}', 'SiteController@cursosFiltro')->name('cursos');

I want to make the Controller execute whether the values are passed or not. For example: A link that will pass the Two parameters, another link that will pass only One and a third link that will not pass any?

You can do this in Rota and Controller or I’ll have to make 3 controllers one for each situation?

You will always load the same View. Having or not parameters.

1 answer

2


Just place a question mark at the end of the parameter to make it optional:

Route::get('/cursos/{id_categoria_curso?}/{id_atuacao_area?}', 'SiteController@cursosFiltro')->name('cursos');

Still, in your controller you need to declare these parameters:

public function cursosFiltro($id_categoria_curso = null, $id_atuacao_area = null)
{
    // faz alguma lógica com os parâmetros 
}
  • So now it looks like this: If you pass the two parameters it works. If you pass 1 or none does not load the courses. the filter ta thus: $courses = Course::Where('id_categoria_course', $id_categoria_course) ->Where('id_actuaca_area', $id_actuacao_area) ->get(); Return view view('site.cursos.courses', Compact('courses', 'categories', 'areas'));

  • you need to work the logic of your controller.

  • i answered my question with a question on IF. You can help me?

  • in this case would be a new question @Junioaraujo

  • related: https://pt.meta.stackoverflow.com/questions/1682/o-que-fazer-quando-o-o-p-muda-sua-question/1684#1684

Browser other questions tagged

You are not signed in. Login or sign up in order to post.