0

I have a Laravel 4 application with a resource Poll

// routes.php
Route::resource('polls', 'PollController');

I do not want anyone to be able to list all the polls, except if the user is authenticated and if (s)he is an admin. This was my solution:

// PollController.php
public function index() {

    if (Auth::check() && Auth::user()->admin) {
        return View::make('polls.index', Poll::all());
    }

    return View::make('polls.create', []);
}

This code works just fine, but it is not very clean code. For once, I make this the "admin check" in a few places. Also it does not feel like it follows the practice of "A function should be doing just 1 thing".

I was wondering if there is a cleaner way to handle cases where the response changes depending on whether the user is logged in and is an admin?

Enrique Moreno Tent
  • 24,127
  • 34
  • 104
  • 189

1 Answers1

2

Use Route Groups and Auth Filters.

http://laravel.com/docs/4.2/routing#route-groups

http://laravel.com/docs/4.2/security#protecting-routes

Example

Route::group(array('before' => 'auth'), function()
{
  // Route::resource('poll', 'PollController');
  // Additional routes
}

Here is a great tutorial series on Laravel in general (and your topic); http://culttt.com/2013/09/16/use-laravel-4-filters/

Community
  • 1
  • 1
dojs
  • 497
  • 2
  • 11
  • `Route::group(array('before' => 'auth'), function() { // add all your resources here });` – dojs Mar 10 '15 at 20:10
  • Why would you comment on your own answer? Just edit ;) – Kyslik Mar 10 '15 at 20:12
  • @Kyslik there was a question there previously... "How would I add a filter to a Route::resource" – dojs Mar 10 '15 at 20:13
  • Either way good practise is to edit your answer. Exactly for this reason. ###Example past it there and done. – Kyslik Mar 10 '15 at 20:14
  • That would add the filter to all the routes of the resource. I just wanted it for the "index" route. But this solved it: http://stackoverflow.com/questions/15823161/protecting-all-admin-routes-with-auth-in-laravel – Enrique Moreno Tent Mar 10 '15 at 20:24