How to define route in laravel ?


Laravel provides more method to define routes. In the Laravel we can define routes to many way like Closure Method ,

By default all routes methods define inside the routes folder

1.Closure Method

Route::get('home', function () {
    //write code here
    //we can load view file also
    return 'Hello World';
});

1.By controller method

We can define routes in Laravel by using controller method. In this method we have to define a method in controller file. We have to pass that method with controller. lets see by an example.

If we have to open a url like this https://jswebsolutions.in/ajax. Then what should we have to do for that url.

//routes/web.php
Route::get('/ajax', 'UserController@ajax');
//app/Http/Controllers/UserController

public function ajax(){
    //write code here

    view('site/home')->with($data);
}

We can also define required and optional URI in routes.

//routes/web.php

// routes with required URI
Route::get('/ajax/{p1}', 'UserController@ajax');
//Define required URI method in controller
public function ajax($p1){
//write code here
view('site/home')->with($data);
}

// routes with optional URI
Route::get('/ajax/{p1?}', 'UserController@ajax');

//Define optional URI method in controller
public function ajax($p1 = NULL){
//write code here
view('site/home')->with($data);
}

We can define a single url which perform mutiple request at the same url like below.

//routes/web.php

//we can manage get and post type of request from the same url

Route::match(['get', 'post'], '/ajax', function () {
//
});

//we can manage any type of request from the single url
Route::any('/ajax', function () {
//
});