Laravel Routing

Routing is one of the important part in web application development. A route is basically and endpoint which works as a pointer in laravel application. A route simply points to a controller method or itself returns a response.

Basic Routing

In laravel all the requests are processes with the help of routes. The application routes are defined in the routes directory routes/web.php file. The routes in the web.php file are contained in the middleware group which provides features like session state , authentication and CSRF protection.

Lest see the Route in practical.

The Default Route in Laravel

Route::get('/', function () {
    return view('welcome');
});

The default route in laravel returns welcome view. Welcome view is the welcome.blade.php stored in the resources/views directory.

In this example, Route is the class that defines the static method get(). we have passed parameters to get() method ‘/’ and function() closure. The ‘/’ defines the root directory and function() defines the functionality of the get() method.

This route points to the root folder so if we enter url http://127.0.0.1:8000/ it will execute the above get method which returns welcome view.


Custom Route in Laravel

Lets configure a custom route in the laravel application.

 
Route::get('/firstpage',function(){
     return "This is the first custom route.";
 });


In this example, we have defined a custom route which returns a string.
The url will be http://127.0.0.1:8000/firstpage. Here we have passed two arguments to the get() method ‘/firstpage’ and function closure. ‘/firstpage’ will appear in the url and the route will execute the functionality we have defined in the function closure.


CSRF Protection


Laravel provides protection against CSRF attacks. Cross-site request forgeries are malicious exploit where in unauthorized commands are executed by an unauthorized user.

Laravel generates a CSRF token for each logged in user. This token is used to verify that all the requests are being passed by an authenticated user.

When we create an HTML form we need to include CSRF token field in the form so that CSRF protection middleware can validate the request. To include CSRF token in the form we can use @csrf blade directive to generate the token . If we do not include CSRF token in the form the request will be rejected.

<form method="POST" action="/usersave">  
    @csrf  
    ...  
</form> 


There can be a scenario when we need to register a route that will respond for multiple http methods then we can use match() method. The match method requires one additional argument i.e array of http methods. We need to define methods in the array that we want the route to respond to.

We can also define a route that will respond to all the http methods using any() method. See below example-

 // Match Method Demo
 Route::match(['get','post'],'/testmatchmethod',function(){
     return "This route will respond to GET and POST method.";
 });

 
 // Any Method Demo
 Route::any('/testanymethod',function(){
     return "This route will respond to any HTTP method.";
 });


Redirect using route


We can define redirection using routes. Redirect() method is used to navigate from one url to another. This method allows to move from one url to another url in a simple way.

The redirect method can be used inside a route or we can directly call the redirect() method without defining a regular route.

   //Redirecting using a route.
   Route ::get('navigateme',function(){
       return redirect('/firstpage');
   });

   //Directly calling redirect method without a route.
   Route::redirect('navigateme','firstpage');


Returning a view from a route.


We can return a view from a route using view() method.

   //Returning a view using route .
   Route::get('/returnview',function(){
       return view('welcome');
   });

   //Directly returning a view  without a route.
   Route::view('/returnview','welcome');

Passing Parameters in Routes

In web development we need to pass parameters to URL. Laravel provides a convenient way to pass parameters to routes.

There are two types of parameters we can pass.

  • Required Parameters
  • Optional Parameters.


Required Parameters

When we define a route with required parameters we must pass values to the route in URL. In a scenario when our loading page is dependent on the url parameter we should make it required.

  Route ::get('user/{id}', function($id){
      return 'The user id is '.$id;
  });

If we do not pass parameters in the url when defined required parameters in the route the application will throw 404 (Page Not Found ) error.


Optional Parameters

If we want to have url parameters optional then we can define route parameter as optional. To achieve this we use ? operator after the parameter name. when we define a parameter as optional then we also need to define default value to the variable.

Route::get('user/{email?}', function($email=null){
    return 'User Email is'.$email;
});

When route parameter is optional and we do not pass value in URL the page will still work and the function will use default value.

Regular expressions with route

We can use regular expressions with routes. Using regular expressions we can define how the url parameter should be constrained.

   //Regular expression with routes
   Route ::get('user/{name?}',function($name=null){
       return 'User Name is '.$name; 
   })->where('name','[a-zA-Z]+');

When we define a route with regular expression it will accept parameters only in the format specified in the regular expression. We can define regular expressions for route to accept only numeric values by defining a route with expression like this ‘[0-9]+’.

Global Constraint

If we want all the route parameters to be constrained by a regular expression we can use pattern method. We can define patterns in the RouteServiceProvider’s boot() method.

In Global constraints we do not have to apply constraints specifically to each route using where clause like we did above we just need to define pattern in the boot() method and it will be applied to all the routes.

   public function boot()  
   {  
     Route::pattern('id', '[0-9]+');  
     parent::boot();  
   }

   Route ::get('user/{id}', function($id){
       return 'The user id is '.$id;
   });

Named Routes in Laravel

Named routes is a useful feature of laravel which we can use to provide nicknames to the routes. Named routes allows to refer to the routes when generating URLs and redirecting to the specific routes.

We can define the named routes using name() method when defining the route.

   Route::get('user/details',function(){

   })->name('user_details');

We can also create named routes for Controller methods.

   Route::get('user/details',usercontroller@details)->name('user_details');

We can use named routes to generate URLs and redirecting to other urls.

   //Generate full URL of the route.
   $url = route('user_details');

   //Redirecting
     Route::get('/', function () {
           return redirect()->route('user_details');
     });

Parameters in named routes

We can also define the url parameters using named routes. To do so we need to pass parameter as a second argument to the route function and these parameters are included to the specified position in the URL.

     Route::get('user/{id}/profile',function($id){

       $url = route('userprofile',['id'=>500]);
       return "URL= ".$url;

      })->name('userprofile');

In this way we have seen different ways and methods to defined routes and redirecting from one url to another. Laravel routing provides flexible options to define SEO friendly urls in the application.

About the Author: allcodebuzz

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *