Laravel Starter - PHP User Group (Myanmar)
Laravel Starter - PHP User Group (Myanmar)
Laravel Starter - PHP User Group (Myanmar)
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
<strong>Laravel</strong> <strong>Starter</strong><br />
Let's take a look:<br />
Route::filter('auth', function()<br />
{<br />
if (Auth::guest()) return Redirect::to('login');<br />
});<br />
You can see that a filter is registered with the Route::filter() method. The typical location<br />
to store filter registrations is within your application/routes.php file.<br />
The Route::filter() method takes two parameters. The first is a string containing the name<br />
of the filter. The second is the anonymous function that will be run when the filter is activated.<br />
In this example, the anonymous function will check if a user is logged in using the<br />
Auth::guest() method. If the user is not logged in, the filter returns a response object that<br />
tells <strong>Laravel</strong> to redirect the user to the login page.<br />
It's important to note that while you can return response objects from before filters, it's not<br />
possible to redirect from after filters as at this point it's too late.<br />
Now that we have the auth filter, how do we tell <strong>Laravel</strong> when to run it? The correct algorithm<br />
is situational.<br />
The following is an example of applying a filter to a routed function:<br />
Route::get('admin', array('before' => 'auth', function()<br />
{<br />
return View::make('admin.dashboard');<br />
}));<br />
In this example, we want to provide an admin dashboard for users who have successfully<br />
authenticated. You may notice that our Route::get() declaration has changed. Our first<br />
argument is still the route's URI. However, our second argument is no longer an anonymous<br />
function, it's now an array. This array provides a method for configuring our route registration.<br />
<strong>Laravel</strong> knows that when you pass a key/value pair, it should be used as configuration and that<br />
when you pass an anonymous function, it should be used as the target function for the route.<br />
39