A middleware in Laravel is a filter that processes HTTP requests before they reach controllers. It’s used for tasks like authentication, logging, and modifying requests or responses.
To protect a route from unauthorized access, middleware method is called on the instance of the Route
class;
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth']);
To access user related information in Blade template, code corresponding to it should be wrapped with @auth [CODE] @endauth
@auth
auth()->user()->name
@endauth
Controllers - Laravel 12.x - The PHP Framework For Web Artisans
A controller in Laravel is a class that handles HTTP requests and returns responses. It groups related request-handling logic, making code more organized and reusable. Controllers usually correspond to a model.
<aside> 💡
Creating a Controller
php artisan make:controller [NAME]
[MODEL-NAME]Controller
in PascalCase
: php artisan make:controller BookController
app/Http/Controllers
</aside><?php
namespace App\\Http\\Controllers;
use Illuminate\\Http\\Request;
use App\\Models\\Book;
class BookController extends Controller
{
public function index(){
$books = Book::all();
return view('books.index', ['books'=>$books]);
}
}
After a controller is created it needs to be referenced in web.php
<?php
use Illuminate\\Support\\Facades\\Route;
use App\\Http\\Controllers\\BookController
Route::get('/books', [BookController::class, 'index'])-middleware('auth');