ryanborum's avatar

When to use a Controller vs Route file

Hey all, I currently have a single-page Laravel application, super simple. It displays data from a database and allows for the data to be sorted and searched through. I currently handle all my searching and sorting in the routing file, but it's getting lengthy and I was wondering if it would be best practice to move it to its own controller. Is there a standard for when a controller should be used vs when it would be a waste?

My "searching" route currently looks like:

Route::get('/search', function () {
    $orderParam = Input::get('order');
    $searchTitle = Input::get('searchtitle');
    $archived = Input::get('archive_flag');
    //Might no longer need series of if checks, but good to work with manual URL parameters I guess
    $query = DB::table('proposals');
    if(Input::has('archive_flag')){
      $query->where('archive_flag', '=', $archived);
    }
    if(Input::has('searchtitle')){
      $query->where('title', 'LIKE', '% ' . $searchTitle . '%');
    }
    if(Input::has('order')){
      $query->orderBy($orderParam);
    }
    $proposals = $query->get();
    $numResults = $query->count();
    $documents = DB::table('prop_documents')->get();
    $comments = DB::table('prop_status')->get();
    return view('index', ['proposals' => $proposals, 'documents' => $documents, 'comments' => $comments, 'numResults'=>$numResults]);
});

Thanks to anyone who can provide some insight

0 likes
4 replies
topvillas's avatar
Level 46

The simple answer is use controllers every time.

The routes file is for handling routes and controllers are for handling route actions.

But, a lot of people would also tell you skinny controllers are better and that you should also consider moving that search functionality into a service class and injecting that into the controller.

1 like
ryanborum's avatar

So I should move all my logic to a controller and my route file should become just a GET route to the controller?

topvillas's avatar

Yep. That's the core of the MVC pattern.

1 like
Cronix's avatar

Additionally, routes with closures can't be cached. Eventually you'll probably want to cache them, especially on your production server, as it does speed things up.

https://laravel.com/docs/5.6/controllers#route-caching

Closures are great for quickly mocking something up, or testing something, but once it's working you should really always move it to a controller.

Please or to participate in this conversation.