To demonstrate the power of middleware, we'll create a simple Laravel application that allows users to create and view blog posts. We'll use middleware to restrict access to certain parts of the application based on the user's authentication status.
Before we begin, you should have a basic understanding of Laravel and how to create and run Laravel projects. If you're new to Laravel, you can get started by reading the official Laravel documentation.
To get started, we'll create a new Laravel project by running the following command in our terminal:
composer create-project --prefer-dist laravel/laravel blog
This will create a new Laravel project in a directory called blog
.
Next, we'll set up the database for our application. Open the .env
file in your project's root directory and modify the DB_
variables to match your database configuration.
Once you've configured the database, run the following command to create the necessary tables:
php artisan migrate
Next, we'll create a BlogPost
model and a BlogPostController
to handle requests related to blog posts. Run the following commands in your terminal to create these files:
php artisan make:model BlogPost -mc
This will create a BlogPost
model and a BlogPostController
.
Next, we'll create the views for our blog post pages. Run the following command in your terminal to create a directory for our blog post views:
mkdir resources/views/posts
Then, create the following three Blade templates in the resources/views/posts
directory:
index.blade.php
@extends('layouts.app')
@section('content')
<h1>Blog Posts</h1>
<ul>
@foreach($posts as $post)
<li><a href="{{ route('posts.show', $post->id) }}">{{ $post->title }}</a></li>
@endforeach
</ul>
<a href="{{ route('posts.create') }}">Create Post</a>
@endsection
create.blade.php
@extends('layouts.app')
@section('content')
<h1>Create Post</h1>
<form method="POST" action="{{ route('posts.store') }}">
@csrf
<label for="title">Title:</label>
<input type="text" name="title" id="title">
<br>
<label for="body">Body:</label>
<textarea name="body" id="body"></textarea>
<br>
<input type="submit" value="Submit">
</form>
@endsection
show.blade.php
@extends('layouts.app')
@section('content')
<h1>{{ $post->title }}</h1>
<p>{{ $post->body }}</p>
<a href="{{ route('posts.index') }}">Back to Posts</a>
@endsection
Next, we'll create the routes for our blog post pages. Open the `routes/web.php file and add the following routes:
Route::get('/', function () {
return view('welcome');
});
Route::resource('posts', 'BlogPostController')->middleware('auth');
The first route is the default route for our application and displays the welcome page. The second route is a resource route for our BlogPostController
, which handles all requests related to blog posts. We've also added the auth
middleware to this route, which means that users must be authenticated in order to access the blog post pages.
Now we'll create the middleware that will check if the user is authenticated before allowing them to access the blog post pages. Run the following command in your terminal to create a new middleware:
php artisan make:middleware Authenticate
This will create a new Authenticate
middleware in the app/Http/Middleware
directory. Open the app/Http/Middleware/Authenticate.php
file and modify it to look like this:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Authenticate
{
public function handle(Request $request, Closure $next)
{
if (!auth()->check()) {
return redirect('login');
}
return $next($request);
}
}
In this middleware, we're checking if the user is authenticated using the auth()
function provided by Laravel. If the user is not authenticated, we're redirecting them to the login page. If the user is authenticated, we're allowing them to access the requested page by calling the $next
closure.
Next, we need to register our middleware with Laravel. Open the app/Http/Kernel.php
file and add the following line to the $routeMiddleware
array:
'auth' => \App\Http\Middleware\Authenticate::class,
This registers our Authenticate
middleware with the auth
alias, which we used in our BlogPostController
route.
Finally, we'll test our middleware to make sure it's working correctly. Run the following command to start the Laravel development server:
php artisan serve
Then, visit http://localhost:8000/posts
in your web browser. You should be redirected to the login page if you're not already authenticated. Once you've logged in, you should be able to access the blog post pages.
In this tutorial, we've explored how middleware works in Laravel and how you can use it to add additional functionality to your applications. We've created a simple Laravel application that allows users to create and view blog posts, and we've used middleware to restrict access to certain parts of the application based on the user's authentication status.
Middleware is a powerful feature of Laravel, and it's worth spending some time getting to know how it works. With middleware, you can add all sorts of functionality to your applications, from authentication and authorization to logging and debugging.