Laravel - Route with variable

Asked

Viewed 2,110 times

5

Good morning Sirs. I have a question about the route in the Laravel, I carried through researches trying to find the result but I did not find what I wanted.

I need that from the id that is redirected (for example: /discipline/3) it sends the number "3" to the parameter of my method return_discipline($id) so I can work with it. I tried to do as below but nothing worked so far. What should I do?

Thank you

Code in web.php file

Route::get('/disciplina/{id}', "select@retorna_disciplina(id)")->middleware('login');

Code in the controller

 public function retorna_disciplina($id)
    {
        $prontuario = session('prontuario');
        $cargo = session('cargo');

        if($cargo == "P")
        {
            $disciplina = DB::table('oferecimento_disciplina')
                ->where('id_professor','=', $prontuario)
                ->where('dsa', '=', $id)
                ->first();

            if(count($disciplina)>0)
            {
                $postagens = DB::table('postagens')
                    ->where('dsa', '=', $id)
                    ->get();
                return view('disciplinas.disciplina')->with([
                        'disciplina' => $disciplina,
                        'postagens' => $postagens
                    ]);
            }
            else{
                Redirect::to('/perfil')->withErros("A disciplina não existe ou você não tem permissão de acesso");
            }
        }
}
  • What is the version of your Laravel?

2 answers

3


Your Route has a small error, it should be like this (I assume the controller name and the file name are right and is "select"):

Route::get('/disciplina/{id}', "select@retorna_disciplina")->middleware('login');

In the controller must have:

use Illuminate\Http\Request; // caso não tenha já isto, deve estar no topo ao lado dos outros "use" que deve ter
...
public function retorna_disciplina(Request $request) {
    $id = $request->id;
    ....
}

The variable $request, stores the information about the request, in which part of it are the parameters sent via GET, in this case the id.

  • Are you sure? $request->id works? Usually, pass the value $id as a parameter, and it is captured...

  • That’s how I’ve always done @Wallacemaxters, at least it works too

  • Look at my answer. Since version 4 of Laravel, I have always used the parameter in the method. I think maybe it’s because the tutorials of the documentation only taught to do so. It’s the first time I see it there.

  • I think that it turns out to be better, because you have access to more information about the request, ex: $request->ip, $request->url() etc... And it’s more at hand, at least I’ve always done so @Wallacemaxters

  • Perfect, I did as you mentioned and helped me a lot! Thanks again Miguel.

  • Hi, you’re welcome @Renankaiclopes, I’m glad you decided

Show 1 more comment

2

You only need to specify in your route expression which parameter will be variable in the url. Then, in your controller, you set the desired parameter to capture the url parameter in your specific method.

See the example below.

Controller:

class SiteController extends Controller
{
      public function getArticle($id)
      {
         dd($id);
      }
}

Route:

Route::get('site/article/{id}', 'SiteController@getArticle');

In the case above, when you call the route site/article/5, the parameter $id of the method getArticle will have the value 5.

Note that to indicate which passage of the url will have the variable parameter, you need to use a keyed word {}.

If necessary to use Request in your method, you can do so:

class SiteController extends Controller
{
      public function getArticle(Request $request, $id)
      {
         dd($id);
      }
}
  • This way I never did, but also instantiated the Request has access to all information in the same, but does not need to put another argument

  • @Miguel generally, to access $request->id, only when I pass /article/?id=5 url. That way there was different, I hadn’t seen it yet. I didn’t know that Laravel "mixed" requests with the route parameter.

  • The route parameter is also part of the request (GET), it makes sense that you have access to it from it

  • @Miguel actually, no. The path url has nothing to do with the query string. That’s why I thought it was weird that Laravel did it. I’m not saying the answer is wrong, I’m just saying I didn’t know it worked.

  • Wallace I really have the idea that he does, I imagine that when he 'sees' a route with /user/{id} starts from the beginning that the id will be a parameter sent via GET and dynamic. That raw would be user?id=1

Browser other questions tagged

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