Laravel Classroom image

osdyui
 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|1 | 2 | 3 | 4|Last
Lessons:-Routes With Closures

4.3 Filters
Ok ok… I said I was going to be explaining Routes in this one, but I honestly can’t think of a
better place to cover Filters, and they are related, so here we go.
Filters are exactly as they sound, they are code or tests that can be performed ‘before’ or ‘after’
a route, and other key events within the framework. Laravel has four special route filters that
are defined by default in application/routes.php. Let’s take a look at them.
1 <?php
2
3 Route::filter('before', f4 {
5 // Do stuff before every request to your application...
6 });
7
8 Route::filter('after', function($response)
9 {
10 // Do stuff after every request to your application...
11 });
12
13 Route::filter('csrf', function()
14 {
15 if (Request::forged()) return Response::error('500');
16 });
17
18 Route::filter('auth', function()
19 {
20 if (Auth::guest()) return Redirect::to('login');
21 });
The first two routes execute the encapsulated closure before and after every request (or route
/ action) to your application. What you do within the enclosure is entirely up to you. Start
libraries, provide data to ‘something’, your own creativity is your only limitation. They are
special filters in that they do not need to be assigned to individual routes.
The ‘csrf’ filter is used to prevent ‘cross-site-request-forgery²’ and can be applied to routes which
are the result of an AJAX call for extra security.
The ‘auth’ filter can be applied to any route to prevent access unless a user is currently ‘logged
in’ using Laravel’s authentication system.
To apply ‘csrf’ or ‘auth’ filters to your Routes, simply add a new array entry to the second
parameter like so:
1 <?php
2
3 Route::get('/', array('as' => 'profile', 'before' => 'auth', 'do' => functi\
4 on()
5 {
6 return View::make('account/profile');
7 }));
The key for the array can be either ‘before’ to run the filter before your route, or ‘after’ to run
it after. Multiple filters can be applied by separating their names with a | (pipe) for example
auth|csrf.
As of Laravel 3.1, if you would like to add a filter to a number of requests whose URIs match a
specific pattern, use the following line :unction()1 <?php
2
3 Route::filter('pattern: admin/*', 'auth');
This will apply the ‘auth’ filter to all route URIs that start with admin/.

 

 
 
 

osdyui

Skills    Laravel

Qualifications :-
Location :-,,,
Description:-
Explore
 

  Students (0)