All you need to know about Route in Laravel 5
Tags: laravel
Published: 2017-11-26 13:00:42

---
title: "All you need to know about Route in Laravel 5"
published: true
tags: laravel
canonical_url: https://medium.com/lordofdev/all-you-need-to-know-about-route-in-laravel-5-ea7b6aebbcaa
---

### All you need to know about Route in Laravel&nbsp;5

![](https://cdn-images-1.medium.com/max/1024/0*EvImwRFRWs-JR-BX.png)

#### Route explanation

In a Laravel&nbsp;, provide handle multiple route type we have “web” routes in _routes/web.php_ and “API” routes in _routes/api.php_ and artisan command route in console.php. Web routes are those that will be visited by users; API routes are those for your API. For this post, we’ll focus on the routes in _routes/web.php_.

#### Basic route definition

all class in laravel declare by static way and we pass parameter in key-value format; value can use in multiple type in example we use closure&nbsp;style

```
// routes/web.php 
Route::get('/', function () {       
        return 'Hello, World!';
});
```

#### WHAT’S A&nbsp;CLOSURE?

closure is an object representation of an anonymous function. We can see that the anonymous function in the above code actually returns an object of closure which is assigned to and called using the variable $string. You can say closure is an object oriented way to use anonymous functions.

#### why use static&nbsp;class

If you have much experience developing PHP, you might be surprised to see static calls on the Route class. This is not actually a static method&nbsp;, but rather service location using Laravel’s facades

but if you don’t like facade this alternative way

```
$router->get('/', function () {
    return 'Hello, World!';
 });
```

#### Route Verbs

You might’ve noticed that we’ve been using Route::get in our route definitions. This means we’re telling Laravel to only match for these routes when the HTTP request uses the GET action. But what if it’s a form POST, or maybe some JavaScript sending PUT or DELETE requests? There are a few other options for methods to call on a route definition,

```
Route::get('/', function () { 
return 'Hello, World!'; 
});
Route::post('/', function () {});
Route::put('/', function () {});
Route::delete('/', function () {});
Route::any('/', function () {})
Route::match(['get', 'post'], '/', function () {});
```

#### HTTP METHODS

If you’re not familiar with the idea of HTTP methods, read on in&nbsp;this

#### Route Handling

closure doesn’t only way for resolve route action, We can bridge to controller with this&nbsp;example

```
Route::get('/user/list', 'UserController@list');
```

This is telling Laravel to pass requests to that path to the list() method of the App\Http\Controllers\UserController controller. This method will be passed the same parameters and treated the same way as a&nbsp;closure.

#### Route Parameters

If the route has parameters segments in the URL structure that are variable it’s simple to define them in your route and pass them to your&nbsp;closure

```
Route::get('users/{id}/list', function ($id) { 
// 
});
```

we use {id} for accept parameter and $id use to pass parameter to closure but if we didn’t pass parameter we get&nbsp;error

We can also make your route parameters optional by including a question mark (?) after the parameter name, like&nbsp;this

```
Route::get('users/{id?}/list', function ($id = 'fallbackId') { 
//
 });
```

And you can use regular expressions to define that a route should only match if a parameter meets particular requirements

```
Route::get('users/{id}', function ($id) { 
//
 })->where('id', '[0-9]+');
```

if you visit a path that matches a route string, but the regex doesn’t match the parameter, it won’t be matched, so it would return a 404 Not Found&nbsp;error.

#### Route Names

if we need to use route in elsewhere your can refer by url path and put in parameter to url() helper to simplify that linking in your views, in below example&nbsp;. The helper will prefix your route with the full domain of your&nbsp;site.

```
<a href="<?php echo url('/'); ?>"> // outputs <a href="http://yoursite.com/">
```

in previous version laravel give name to route with alias method but now this change to name method but give same feature you can call route without use full path and when change url you doesn’t change all place&nbsp;.

```
// in routes/web.php: 
Route::get('user/{id}', 'UsersController@show')->name('user.show');
// Link the route in a view with route() helper
 <a href="<?php echo route('user.show'); ?>">
```

This example show a few new concepts. First, we’re using fluent route definition to add the name, by chaining the name() method&nbsp;. This method allows us to name the route, make it a short alias to use it dynamically and can reference elsewhere.

#### Passing route parameters to&nbsp;helper

When your route has parameters (e.g., posts/{id}), you need to define those parameters when you’re using the route() helper to generate a link to the&nbsp;route.

There are a few different ways to pass these parameters. Let’s imagine a route defined as posts/{postId}/comments/{commentId}. If the user ID is 3 and the comment ID is 7, let’s look at a few options we have available to&nbsp;us:

**Option 1:**

```
route('posts.comments.show', [3, 7]) 
// http://yoursite.com/posts/3/comments/7
route('posts.comments.show', ['postId' => 3, 'commentId' => 7]) 
// http://yoursite.com/posts/3/comments/7
// tips to pass query string
route('users.comments.show', ['postId' => 3, 'commentId' => 7, 'opt' => 'a']) 
// http://myapp.com/posts/1/comments/2?opt=a
```

#### Route Groups

if you have a routes share a certain authentication&nbsp;, a path prefix, or a controller namespace. if we defined shared characteristics again and again on each route not only seems boring task and make you application not organize.

But route groups allow you to group several routes together, and apply any shared configuration settings once, to reduce this duplication.

this example show how to group route with route&nbsp;group

```
Route::group([], function () {          
   Route::get('Hi', function () {            
      return 'taq';         
   });        
   Route::get('world', function () {         
         return 'World';
  });
});
```

By default, a route group doesn’t actually do anything. Besides we will pass some configuration to first parameter (eg. middleware,prefix,namespace)

#### Route group and Middleware

middleware is some configuration that we want to do before or after visitor access to route (eg.authentication,checkage) in this case we apply middleware name auth for check visitor access this group has authenticate user if you doesn’t authenticate can’t access dashboard or user&nbsp;profile

```
Route::group(['middleware' => 'auth'], function () { 
     Route::get('dashboard', function () {
       return view('dashboard');     
     });      
     Route::get('profile', function () {   
       return view('profile');    
     }); 
});
```

#### Route group and path&nbsp;prefixes

If you have a group of routes that share a segment of their path for example, if your site’s admin area is prefixed with /adminyou can use route groups to do&nbsp;that

```
Route::group(['prefix' => 'admin'], function () { 
        Route::get('/', function () {
           // Handles the path /admin 
         }); 
         Route::get('users', function () {
           // Handles the path /admin/users 
          }); 
});
```

#### Route group and namespace Prefixes

If you’re grouping routes by path prefix, it’s similar their controllers have a similar PHP namespace. In the Admin example, all of the Admin routes’ controllers might be under an Admin namespace. By using the route group namespace prefix, as in example, help we avoid long controller references

```
// not use route group
 Route::get('/report', 'Admin/ReportControllerB@index');      
 Route::get('/setting', 'Admin/SettingControllerB@index');
Route::group(['namespace' => 'Admin'], function () {
    
    Route::get('/report', 'ReportControllerB@index');      
    Route::get('/setting', 'SettingControllerB@index');
});
```

#### Name Prefixes

you can also set prefix to name() function with ‘as’&nbsp;example

```
Route::group(['as' => 'posts.', 'prefix' => 'posts'], function () {     
  Route::group(['as' => 'comments.', 'prefix' => 'comments'], function () {     
  // you can use by in helper like route('posts.comments.list')               
  Route::get('{id}', function () { // })->name('list'); });
 });
```

#### Route and&nbsp;Views

You can render view directly in controller in three different ways&nbsp;. For now, just concern yourself with view(), it’s helper function.

first way use&nbsp;closure

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

this closure loads the _resources/views/home.blade.php_

second way pass parameter

```
Route::get('users', function () {     
    return view('users.index')->with('users', User::all());
});
```

This closure loads the _resources/views/users/index.blade.php_ and passes it a single variable named tasks, which contains the result of the User::all() method.

third way using View Composers to Share Variables with Every View Sometimes it can become a duplicate to pass the same variables over and over. There may be a variable that you want accessible to every view in the&nbsp;site.

```
view()->share('user','somevalue');
```

#### Route and Controllers

Route is gate between controllers and views, in this section we talk about how many way to use route with controller

So, let’s create a controller. we use Artisan command for generate controller template

```
php artisan make:controller PostController
```

now file PostController appear in /HTTP/Controllers

![](https://cdn-images-1.medium.com/max/958/1*Uvu0BPVMStMDRQGa85Eu7w.png)

in this&nbsp;file

![](https://cdn-images-1.medium.com/max/470/1*zP1JpTnNcj9kfxwlOhqQ_w.png)

Modify this file as shown&nbsp;, creating a new public method called index. We’ll just return some text&nbsp;there.

Example 3–20. Simple controller example

```
<?php
use App\Http\Controllers\Controller;
class PostController extends Controller {    
     public function index() {
      return 'Hello, World!';   
     }
 }
```

next create&nbsp;route

```
// routes/web.php 
Route::get('/post', 'PostController@index');
```

That’s it. Visit the / route and you’ll see the words “Hello,&nbsp;World!”

![](https://cdn-images-1.medium.com/max/471/1*slVQtHW4PlIu4n3GumUU4Q.png)

#### Controller namespacing

if we need to group relate controller and keep in some folder&nbsp;. we need to know use namespace concept name space is concept for prevent class name conflict when we have two class with same name and keep in different folder

we need to update namespace with add admin after controller and include Controller class&nbsp;again

![](https://cdn-images-1.medium.com/max/755/1*wzS1f3UC9bvQZlLxOblopw.png)

and update route add&nbsp;admin

![](https://cdn-images-1.medium.com/max/549/1*YEa48bCJI1V7gIi7wzXj9A.png)

try refresh

![](https://cdn-images-1.medium.com/max/435/1*dwlWXuzK-r5m-Puv9qEC8A.png)

#### Getting input with post&nbsp;route

The second most common action to perform in a controller method is to take input from the user and act on it. we have route post for responsible this&nbsp;action

```
// routes/web.php 
Route::post('post', 'PostController@store');
```

now we bridge post url to store&nbsp;method

```
// PostController.php
 public function store(Request $request) {
      $task = new App\Post; 
      $task->title = $request->get('title'); 
      $task->body = $request->get('body'); 
      $task->save();
      return redirect('post.index'); 
}
```

This example makes use of Post models and the redirect() helper, and we’ll talk about them more later, but you can see what we’re doing here: we create a new&nbsp;Post,

#### Resource controller

Many time naming the methods in your controllers can be the hardest part of writing a controller. but, Laravel has some conventions for all of the routes of a traditional REST controller called a “resource controller” additionally, it comes with a generator out of the box and a convenience route definition that allows you to bind an entire resource controller at&nbsp;once.

To see the methods that Laravel expects for a resource controller, let’s generate a new controller from the command&nbsp;line:

```
php artisan make:controller PostController --resource
```

Now open _app/Http/Controllers/PostController.php_. You’ll see it comes&nbsp;.

```
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
```

now we can bind all method in post controller to one&nbsp;route

```
Route::resource('post','PostController');
```

If you ever find yourself in a situation where you’re wondering what resource routes has available, run php artisan route:list and you’ll get a listing of all of the available routes

![](https://cdn-images-1.medium.com/max/888/1*jJAh_oWC-TaU4C1_afDlVA.png)

now we have multiple route for handle multiple situation

#### Route Model&nbsp;Binding

One of the most common routing patterns is that the first line of any controller method tries to find the resource with the given ID, like in&nbsp;example

```
Route::get('user/{id}', function ($id) {    
 $user = App\User::findOrFail($id); 
});
```

Laravel provides a feature that simplifies this pattern called “route model binding.” This allows you to define that a particular parameter name (e.g., {id}) will indicate to the route resolver that it should look up an Eloquent record with that ID and then pass it in as the parameter _instead_ of just passing the ID. There are two type of model binding: implicit and custom&nbsp;.

#### Implicit Route Model&nbsp;Binding

The simplest way to use route model binding is to name your route parameter something unique to that model (e.g., name it $user instead of $id), then typehint that parameter in the closure or controller method and use the same variable name there. It’s easier to show than to describe, so take a look at&nbsp;example

```
Route::get('users/{user}', function (User $user) {
 return view('user.show')->with('user', $user);
 });
```

Every time this route is visited, the application will assume that whatever is passed into {user} is an ID that should be used to look up a User, and then that resulting model instance will be passed in to your second&nbsp;function

#### Custom Route Model&nbsp;Binding

To manually configure route model bindings, copy example below to the boot() method in App\Providers\RouteServiceProvider.

```
public function boot(Router $router) { 
// run parent's boot() method  
parent::boot($router);
// init the binding 
$router->model('user', User::class); 
}
```

You’ve now defined that whenever a route has a parameter in its definition named {user}, as in before, the route resolver will return an instance of the User class with the ID of that URL parameter.

#### Conclusion

Laravel’s routes is provide way to handle every moment in application access like a gate for our application it’s provide a lot out of the box feature like model binding&nbsp;,resource route

in this post cover all this basic topic for route hope you enjoy much more than&nbsp;document

_Originally published at_ [_Krissanawat Blog_](http://krissanawat.com/2017/11/06/need-know-route-laravel-5/)_._

* * *