Routing

To navigate through your Laravel application, you define routes in the routes/web.php file. Routes can either point directly to Views
or pass through Controllers to handle logic before returning a response.

Basic Routing

Laravel routes are defined using the Route facade and can respond to different methods:

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

View Routing

If you only need to return a view without additional logic, you can use the Route::view method:

Route::view('/about', 'about');

Additionally, you can pass data to the view:

Route::view('/about', 'about', ['employees' => Employee::all()]);

Controller Routing

Instead of defining logic inside routes, you can delegate it to controllers:

Route::get('/dashboard', [DashboardController::class, 'index']);

HTTP methods in Laravel

Method Description
Route::get() Fetches a resource
Route::post() Creates a new resource
Route::put() Updates a resource
Route::delete() Deletes a resource

Examples:

Route::post('/user', [UserController::class, 'store']);

Route::put('/user/{id}', [UserController::class, 'update']);

Route::delete('/user/{id}', [UserController::class, 'destroy']);

Named Routes

You can give routes unique names by using name():

Route::get('/profile', [ProfileController::class, 'show'])->name('profile.show');

In the Blade, the route can be accessed via route('profile.show') inside the href attribute of an <a> tag. Dont forget to add curly
brackets in the href attribute before accessing the route!


Resource Routes

To generate CRUD routes for a controller, use Route::resource :

Route::resource('products', ProductController::class);

This automatically creates routes for index, create, store, show, edit, update and destroy actions.
If you dont intend on using all of them you can add limits:

Route::resource('products', ProductController::class)->only(['index', 'show']);

Route::resource('products', ProductController::class)->except(['create', 'edit']);

Grouped Routes & Middleware Authentication

Grouping routes helps apply shared attributes like middleware:

Route::middleware('auth')->group(function () {
* define routes here
});

API Routing

API routes are defined in routes/api.php. These routes are stateless and automatically prefixed with /api:

Route::get('/products', [ProductController::class, 'getProducts']);
public function getProducts(){
return Product::all();
}

The API can be accessed with the link /api/products. Your output should resemble the following:

[
{
"name": "Product 1",
"description": "Description of the first product.",
"price": 10.99
},
{
"name": "Product 2",
"description": "Description of the second product.",
"price": 15.99
}
]