Developer Snippet Diary

routing

Routing - Laravel - The PHP Framework For Web Artisans

Basic Routing:

Route::get('/', function () {
    echo "working";
   // return 'Hello World';
  // return view('welcome');
});

Route::view('/welcome', 'welcome', ['name' => 'Taylor']); //also send array data

Controller method access

use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
//OR
Route::get('/user', 'UserController@index');

Without use ..... user controller

Route::get('message',[App\Http\Controllers\HomeController::class,'index']);

NAMED ROUTES:

Named routes allows you to refer to the routes when generating URLs or redirects to the specific routes.

Route::get('home',[App\Http\Controllers\HomeController::class,'index'])->name('rizwan');
//Generating URLs  
$url= route('student_details');  
//Generating Redirects...  
return redirect() -> route('student_details');  

___________________________

Available Methods

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

Route::match(['get', 'post'], '/', function () {  //code }); //multiple http verbs
 
Route::any('/', function () {    //code }); //all http verbs

Redirect 

Route::redirect('/here', '/there');
Route Parameters
Route::get('/user/{id}', function ($id) { echo $id; });
Route::get('/posts/{post}/comments/{comment}', function ($postId, $commentId) { //code });

If your route has dependencies that you would like the Laravel service container to automatically inject into your route's callback, you should list your route parameters after your dependencies:

use Illuminate\Http\Request;
Route::get('/user/{id}', function (Request $request, $id) {
    return 'User '.$id;
});

Optional parameters

Route::get('/user/{name?}', function ($name = null) {
    return $name;
});

Regular expressions

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

https://laravel.com/docs/9.x/routing#parameters-regular-expression-constraints

Route Groups:

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () { // });
    Route::get('/user/profile', function () { //  });
});
use App\Http\Controllers\OrderController;
Route::controller(OrderController::class)->group(function () {
    Route::get('/orders/{id}', 'show');
    Route::post('/orders', 'store');
});

 

Posted by: R GONDAL
Email: rizikmw@gmail.com