CodeIgniter Laravel PHP Example HTML Javascript jQuery MORE Videos New
Need a Website Or Web Application.Contact : +91 9437911966 (Whatsapp) Note: Paid Service

Laravel Routing


All Laravel routes are defined in your route files(web.php/api.php), which are located in the routes directory.

The routes/web.php file defines routes that are for web interface. The routes defined in web.php, CSRF(Cross-site request forgery) token required for Post,Put and Delete method.

The routes in routes/api.php are stateless and CSRF token is not required here.We can use here JWT(JSON WEB TOKEN) or basic token to identify the user on each request.For JWT package is available https://packagist.org/packages/tymon/jwt-auth and how to use is https://blog.pusher.com/laravel-jwt/.

Available Route Method

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

Example

Route::get('/, function(){
return view('welcome');
})
Route::get('/home', 'HomeController@index')->name('home');

To get the list of routes run the following command in project folder terminal.

php artisan route : list

We can also create route resource for CRUD operation means single line represent all possible route get, post,put, delete.

Route::resource('/userData','UserDataController');

We may also create route for multiple methods(Verbs) like

Route::match(['get', 'post'], '/', function () {
// this will hit on get and post method
});
Route::any('/', function () {
//this will hit on any available method
});

Redirect Routes

Route::redirect('/current, '/destination,statusCode);
Route::redirect('/, '/dashboard,302);

Route Parameters

1)Required Parameter

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

Here {id} is required params and request url should be domain.com/user/1.

We may define multiple params like user/{id}/{anotherid}

2)Optional Parameter

Form making parameter optional put ? before } closing bracket like

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

3)Regular Expression constraints

We can format the route parameter using where() method. It accept the name of parameter and a regular express. Like:

Route::get('user/{name}', function ($name) {
    //
})->where('name', '[A-Za-z]+');

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

Route::get('user/{id}/{name}', function ($id, $name) {
    //
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

We can also put the constraint as global level.

It is very helpful because we know id will always number so put regular expression check on global basis.

For do this open app\Providers\RouteServiceProvider.php and write pattern method inside boot() method like : /**

 * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //
       Route::pattern('id', '[0-9]+');
        parent::boot();
    }

Named Routes

Named routes allow the convenient generation of URLs or redirects for specific routes.

This will be done by using name() method like

Route::get('user/profile', function () {
    //
})->name('profile');
For named routes
// Generating URLs...
$url = route('profile');

// Generating Redirects...
return redirect()->route('profile');

Route::get('user/{id}/profile',UserController@index)->name('profile');
$url = route('profile', ['id' => 1]);

Middleware

To assign middleware to all routes within a group, wemay use the middleware method before defining the group. Middleware are executed in the order they are listed in the array. For example:

Example:

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // Uses first & second Middleware
    });

    Route::get('user/profile', function () {
        // Uses first & second Middleware
    });
}); // the middleware close

OR

Route::get('/dashboard, function(){
    return view(dashboard);
})->middleware('auth');

Route Prefix

If we want to add prefix on URI then we can use prefix() method like

Route::prefix('admin')->group(function () {
    Route::get('users', function () {
        // Matches The "/admin/users" URL
    });
});

Query String

Handling query string in routes:

Route::get('test', function(){
return "<h1>" . Input::get("color") . "</h1>";
 });
Or 
Route::get('test', function(){ 
return "<pre>" . print_r(Input::all(), true) . "</pre>"; 
});

Input:all() return an associated array with name and value
domain.com/test?name=abc,age=27,id=1
Print method will print like
array(
[name]=>abc,
[age]=>27,
[id]=>1
)

In controller we can use request object and call query(). For example $query = $request->query(); It retrieves all of the query string values as an associative array

For particular query use $name = $request->query('name', 'defaultName')

Default name is optional parameter if name is not present then defaultName will return.