What approach should be used in Resource type controllers to list and search for items?

Asked

Viewed 13 times

2

I created the controller Artigocontroller of the kind Resource, then I have the verbs and default routes. I use the method index from my controller to list all articles (paged):

$artigos = Artigo::orderBy('edicao', 'desc')->paginate(25);
return view('painel.artigos.listar', compact('artigos'));

The point is that in my view listar.blade.php, in addition to listing everything, I also have a search input, which in theory does the search and populates that same view, so I know the method index does not accept input parameters, in this case the best is in case the search calls another controller and this points back to the view?

I’m using Laravel 5.6

1 answer

1

One approach that can be used is to accept query strings to filter in the index.

public function index(Request $request) 
{
    $query = $request->query('campo1', 'campo2');
    // Ou todos os campos.. é interessante uma validação aqui
    $query = $request->query();

    $artigos = Artigo::where($query)->orderBy('edicao', 'desc')->paginate(25);

    return view('painel.artigos.listar', compact('artigos'));
}

Your url might be something like this:

/artigos?campo1=123&campo2=234

  • But in this case as we are talking about Resource, if I pass some parameter I would not be falling into another method like show?

  • Not because it only goes to another Source if you use url tracking type /article/field

  • In this case it is not a parameter in the url, it is simply an extra argument for the method. Note that a ? to send the fields.

Browser other questions tagged

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