DEV Community

0xAirdropfarmer
0xAirdropfarmer

Posted on • Originally published at Medium on

All you need to know about Route in Laravel 5

All you need to know about Route in Laravel 5

Route explanation

In a Laravel , 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 style

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

WHAT’S A 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 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 , but rather service location using Laravel’s facades

but if you don’t like facade this alternative way

$router->get('/', function () {
    return 'Hello, World!';
 });
Enter fullscreen mode Exit fullscreen mode

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 () {});
Enter fullscreen mode Exit fullscreen mode

HTTP METHODS

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

Route Handling

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

Route::get('/user/list', 'UserController@list');
Enter fullscreen mode Exit fullscreen mode

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 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 closure

Route::get('users/{id}/list', function ($id) { 
// 
});
Enter fullscreen mode Exit fullscreen mode

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

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

Route::get('users/{id?}/list', function ($id = 'fallbackId') { 
//
 });
Enter fullscreen mode Exit fullscreen mode

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]+');
Enter fullscreen mode Exit fullscreen mode

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 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 . The helper will prefix your route with the full domain of your site.

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

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 .

// 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'); ?>">
Enter fullscreen mode Exit fullscreen mode

This example show a few new concepts. First, we’re using fluent route definition to add the name, by chaining the name() method . 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 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 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 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
Enter fullscreen mode Exit fullscreen mode

Route Groups

if you have a routes share a certain authentication , 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 group

Route::group([], function () {          
   Route::get('Hi', function () {            
      return 'taq';         
   });        
   Route::get('world', function () {         
         return 'World';
  });
});
Enter fullscreen mode Exit fullscreen mode

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 profile

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

Route group and path 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 that

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

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');
});
Enter fullscreen mode Exit fullscreen mode

Name Prefixes

you can also set prefix to name() function with ‘as’ 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'); });
 });
Enter fullscreen mode Exit fullscreen mode

Route and Views

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

first way use closure

Route::get('/', function () { 
return view('home'); 
});
Enter fullscreen mode Exit fullscreen mode

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());
});
Enter fullscreen mode Exit fullscreen mode

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 site.

view()->share('user','somevalue');
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

now file PostController appear in /HTTP/Controllers

in this file

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

Example 3–20. Simple controller example

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

next create route

// routes/web.php 
Route::get('/post', 'PostController@index');
Enter fullscreen mode Exit fullscreen mode

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

Controller namespacing

if we need to group relate controller and keep in some folder . 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 again

and update route add admin

try refresh

Getting input with post 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 action

// routes/web.php 
Route::post('post', 'PostController@store');
Enter fullscreen mode Exit fullscreen mode

now we bridge post url to store 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'); 
}
Enter fullscreen mode Exit fullscreen mode

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 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 once.

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

php artisan make:controller PostController --resource
Enter fullscreen mode Exit fullscreen mode

Now open app/Http/Controllers/PostController.php. You’ll see it comes .

<?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)
    {
        //
    }
}
Enter fullscreen mode Exit fullscreen mode

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

Route::resource('post','PostController');
Enter fullscreen mode Exit fullscreen mode

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

now we have multiple route for handle multiple situation

Route Model 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 example

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

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 .

Implicit Route Model 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 example

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

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 function

Custom Route Model 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); 
}
Enter fullscreen mode Exit fullscreen mode

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 ,resource route

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

Originally published at Krissanawat Blog.


Top comments (0)