Laravel Routing Basic Routing

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Routing defines a map between HTTP methods and URIs on one side, and actions on the other. Routes are normally written in the app/Http/routes.php file.

In its simplest form, a route is defined by calling the corresponding HTTP method on the Route facade, passing as parameters a string that matches the URI (relative to the application root), and a callback.

For instance: a route to the root URI of the site that returns a view home looks like this:

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

A route for a post request which simply echoes the post variables:

Route::post('submit', function() {
   return Input::all();
});

//or

Route::post('submit', function(\Illuminate\Http\Request $request) {
   return $request->all();
});

Routes pointing to a Controller method

Instead of defining the callback inline, the route can refer to a controller method in [ControllerClassName@Method] syntax:

Route::get('login', 'LoginController@index');

A route for multiple verbs

The match method can be used to match an array of HTTP methods for a given route:

Route::match(['GET', 'POST'], '/', 'LoginController@index');

Also you can use all to match any HTTP method for a given route:

Route::all('login', 'LoginController@index');

Route Groups

Routes can be grouped to avoid code repetition.

Let's say all URIs with a prefix of /admin use a certain middleware called admin and they all live in the App\Http\Controllers\Admin namespace.

A clean way of representing this using Route Groups is as follows:

Route::group([
    'namespace' => 'Admin',
    'middleware' => 'admin',
    'prefix' => 'admin'
    ], function () {
        
        // something.dev/admin
        // 'App\Http\Controllers\Admin\IndexController'
        // Uses admin middleware
        Route::get('/', ['uses' => 'IndexController@index']);    
        
        // something.dev/admin/logs
        // 'App\Http\Controllers\Admin\LogsController'
        // Uses admin middleware
        Route::get('/logs', ['uses' => 'LogsController@index']);    
});


Got any Laravel Question?