The Ultimate Laravel 11 Tutorial: A Step-by-Step Guide with Examples

Spread the love

1. Laravel 11 Tutorial: Introduction to Laravel 11

Overview of Laravel 11

In this Laravel 11 Tutorial the Laravel 11 is the latest version of the popular PHP framework designed for web application development. Known for its elegant syntax and robust features, Laravel 11 continues to simplify the development process while providing powerful tools for building modern web applications.

So, let’s begin with this comprehensive Laravel 11 tutorial.

Why Choose Laravel 11 for Your Projects?

Laravel 11 offers a range of benefits, including improved performance, enhanced security features, and an extensive ecosystem of tools and packages. Its comprehensive documentation and active community support make it an ideal choice for both beginners and experienced developers.

Key Features and Improvements in Laravel 11

  • Improved routing performance
  • Enhanced Eloquent ORM capabilities
  • New and improved Blade components
  • Streamlined authentication and authorization
  • Advanced task scheduling and queue management

2. Setting Up Your Development Environment

Now, next in this Laravel 11 tutorial is setting up development environment.

Prerequisites for Laravel 11

Before you begin, ensure you have the following installed:

  • PHP >= 8.0
  • Composer
  • A web server (Apache or Nginx)
  • A database (MySQL, PostgreSQL, SQLite, or SQL Server)

Installing Composer

Composer is a dependency management tool for PHP that allows you to manage your project’s dependencies easily. To install Composer, follow these steps:

  1. Download the Composer installer from the official website.
  2. Run the installer and follow the instructions.
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"

Creating a New Laravel 11 Project

Once Composer is installed, you can create a new Laravel 11 project using the following command:

composer create-project --prefer-dist laravel/laravel laravel11tutorial

Navigate to your project directory:

cd laravel11tutorial

Run the development server:

php artisan serve

Visit http://localhost:8000 in your web browser to see your new Laravel 11 project in action.

3. Laravel 11 Project Structure

Understanding the Directory Structure

The Laravel project structure is designed to be intuitive and easy to navigate. Here’s a brief overview of the key directories:

  • app/: Contains the core application code.
  • bootstrap/: Contains the application bootstrapping script.
  • config/: Contains configuration files.
  • database/: Contains database migrations, seeders, and factories.
  • public/: Contains publicly accessible files like index.php.
  • resources/: Contains view templates, raw assets, and language files.
  • routes/: Contains route definitions.
  • storage/: Contains compiled Blade templates, file-based sessions, caches, and other files generated by the framework.
  • tests/: Contains test files.
  • vendor/: Contains Composer dependencies.

Key Files and Their Roles

  • .env: Environment configuration file.
  • composer.json: Composer configuration file.
  • artisan: Command-line interface for Laravel.

4. Routing in Laravel 11

Basic Routing

Laravel routes are defined in the routes/web.php file. Here’s an example of a basic route:

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

Route Parameters and Constraints

You can define routes with parameters like this:

Route::get('/user/{id}', function ($id) {
    return 'User '.$id;
});

Add constraints to parameters:

Route::get('/user/{name}', function ($name) {
    // Only allows letters in the name parameter
})->where('name', '[A-Za-z]+');

Named Routes and Route Groups

Named routes allow you to reference routes easily:

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

Route groups allow you to group routes with common attributes:

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

5. Controllers in Laravel 11

Creating and Using Controllers

Create a new controller using Artisan:

php artisan make:controller UserController

Define methods within the controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function show($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

Define routes to use the controller:

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

Resource Controllers

Resource controllers simplify CRUD operations. Create a resource controller:

php artisan make:controller PhotoController --resource

Define resource routes:

Route::resource('photos', PhotoController::class);

Route Model Binding

Automatically inject model instances into routes:

Route::get('/user/{user}', function (User $user) {
    return $user;
});

6. Blade Templating in Laravel 11

Introduction to Blade Templates

Blade is Laravel’s templating engine. Blade files use the .blade.php extension and are stored in the resources/views directory.

Creating and Using Blade Templates

Create a new Blade template:

<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Tutorial</title>
</head>
<body>
    @yield('content')
</body>
</html>

Extend the layout in another view:

<!-- resources/views/welcome.blade.php -->
@extends('layouts.app')

@section('content')
    <h1>Welcome to Laravel 11!</h1>
@endsection

Blade Components and Layouts

Create a Blade component:

<!-- resources/views/components/alert.blade.php -->
<div class="alert alert-{{ $type }}">
    {{ $slot }}
</div>

Use the component in a view:

<x-alert type="success">
    Your operation was successful!
</x-alert>

7. Database and Eloquent ORM

Configuring the Database

Set up your database connection in the .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Running Migrations

Create a new migration:

php artisan make:migration create_users_table

Define the table structure in the migration file:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamps();
    });
}

Run the migration:

php artisan migrate

Eloquent ORM Basics

Eloquent provides an easy way to interact with the database. Define a model:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasFactory;
}

Retrieve data using Eloquent:

$users = User::all();

Relationships and Eager Loading

Define relationships in models:

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Use eager loading to optimize queries:

$posts = Post::with('user')->get();

8. Form Handling and Validation

Creating Forms in Laravel 11

Use Blade to create forms:

<form action="/user" method="POST">
    @csrf
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">
    <button type="submit">Submit</button>
</form>

Handling Form Submissions

Handle the form submission in a controller:

public function store(Request $request)
{
    $name = $request->input('name');
    // Process the form data
}

Validating Form Data

Validate form data in a controller:

public function store(Request $request)
{
    $validated = $request->validate([
        'name' => 'required|max:255',
        'email' => 'required|email',
    ]);

    // Process the validated data
}

9. Authentication and Authorization

Setting Up Authentication

Laravel provides built-in authentication. Run the following command to set it up:

composer require laravel/ui
php artisan ui vue --auth
npm install
npm run dev
php artisan migrate

User Registration and Login

The above commands will generate routes, controllers, and views for user authentication. You can customize these as needed.

Authorization with Gates and Policies

Define a gate in the AuthServiceProvider:

use Illuminate\Support\Facades\Gate;

Gate::define('update-post', function (User $user, Post $post) {
    return $user->id === $post->user_id;
});

Check the gate in a controller:

if (Gate::allows('update-post', $post)) {
    // The current user can update the post
}

10. API Development in Laravel 11

Setting Up API Routes

Define API routes in the routes/api.php file:

Route::get('/users', [UserController::class, 'index']);
Route::get('/users/{user}', [UserController::class, 'show']);

Creating API Controllers

Create a new API controller:

php artisan make:controller Api/UserController

Define methods in the controller:

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        return User::all();
    }

    public function show(User $user)
    {
        return $user;
    }
}

API Resource and Transformers

Use API resources for structured responses:

php artisan make:resource UserResource

Define the resource:

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }
}

Use the resource in a controller:

public function show(User $user)
{
    return new UserResource($user);
}

11. Testing in Laravel 11

Introduction to Testing

Laravel provides robust testing tools out of the box. Tests are stored in the tests directory.

Writing Unit Tests

Create a unit test:

php artisan make:test UserTest --unit

Define test methods:

public function test_user_creation()
{
    $user = User::factory()->create();
    $this->assertInstanceOf(User::class, $user);
}

Run the tests:

php artisan test

Writing Feature Tests

Create a feature test:

php artisan make:test UserFeatureTest

Define test methods:

public function test_user_can_view_profile()
{
    $response = $this->get('/user/1');
    $response->assertStatus(200);
}

Run the tests:

php artisan test

12. Deploying Laravel 11 Applications

Preparing Your Application for Deployment

Ensure your .env file is configured for production:

APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.com

Deploying to a Web Server

  • Upload your project files to the web server.
  • Set the correct permissions for storage and cache directories.
  • Configure the web server to point to the public directory.

Managing Environment Configuration

Use environment-specific configuration files for production, staging, and development environments.

13. Middleware in Laravel 11

Creating and Using Middleware

Create a new middleware:

php artisan make:middleware EnsureUserIsAdmin

Define the middleware logic:

public function handle($request, Closure $next)
{
    if (! $request->user()->isAdmin()) {
        return redirect('home');
    }

    return $next($request);
}

Register the middleware:

protected $routeMiddleware = [
    'admin' => \App\Http\Middleware\EnsureUserIsAdmin::class,
];

Middleware Parameters

Pass parameters to middleware:

Route::get('profile', function () {
    // 
})->middleware('auth:api');

Global and Route Middleware

Apply middleware globally in app/Http/Kernel.php:

protected $middleware = [
    \App\Http\Middleware\CheckForMaintenanceMode::class,
];

14. File Storage and Uploads

Configuring File Storage

Set up the filesystem configuration in config/filesystems.php and the .env file:

FILESYSTEM_DRIVER=public

Handling File Uploads

Create a form for file uploads:

<form action="/upload" method="POST" enctype="multipart/form-data">
    @csrf
    <input type="file" name="file">
    <button type="submit">Upload</button>
</form>

Handle the file upload in a controller:

public function upload(Request $request)
{
    $path = $request->file('file')->store('uploads');
    return $path;
}

Accessing Uploaded Files

Access uploaded files using the storage facade:

$files = Storage::files('uploads');

15. Event Handling in Laravel 11

Creating and Listening to Events

Create a new event and listener:

php artisan make:event UserRegistered
php artisan make:listener SendWelcomeEmail

Define the event and listener:

class UserRegistered
{
    public $user;
    
    public function __construct(User $user)
    {
        $this->user = $user;
    }
}

class SendWelcomeEmail
{
    public function handle(UserRegistered $event)
    {
        // Send email to $event->user
    }
}

Register the event and listener in EventServiceProvider:

protected $listen = [
    UserRegistered::class => [
        SendWelcomeEmail::class,
    ],
];

Event Broadcasting

Set up broadcasting configuration in .env:

BROADCAST_DRIVER=pusher

Queued Event Listeners

Define a listener as queued:

class SendWelcomeEmail implements ShouldQueue
{
    // ...
}

16. Queueing in Laravel 11

Setting Up Queues

Configure the queue driver in .env:

QUEUE_CONNECTION=database

Creating and Dispatching Jobs

Create a new job:

php artisan make:job ProcessPodcast

Dispatch the job:

ProcessPodcast::dispatch($podcast);

Monitoring and Managing Queues

Run the queue worker:

php artisan queue:work

Monitor the queue:

php artisan queue:failed

17. Task Scheduling in Laravel 11

Setting Up Task Scheduling

Define scheduled tasks in app/Console/Kernel.php:

protected function schedule(Schedule $schedule)
{
    $schedule->command('report:generate')->daily();
}

Defining Scheduled Tasks

Create a custom command for the scheduled task:

php artisan make:command GenerateReport

Running Scheduled Tasks

Set up the Laravel scheduler to run every minute:

* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

18. Advanced Eloquent Techniques

Query Scopes

Define query scopes in a model:

class User extends Model
{
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }
}

Use the query scope:

$activeUsers = User::active()->get();

Mutators and Accessors

Define mutators and accessors in a model:

class User extends Model
{
    public function getNameAttribute($value)
    {
        return ucfirst($value);
    }

    public function setNameAttribute($value)
    {
        $this->attributes['name'] = strtolower($value);
    }
}

Eloquent Collections

Use Eloquent collections for advanced data manipulation:

$users = User::all()->filter(function ($user) {
    return $user->active;
});

19. Advanced Blade Techniques

Blade Directives

Create custom Blade directives:

Blade::directive('datetime', function ($expression) {
    return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
});

Custom Blade Components

Create a custom Blade component:

php artisan make:component Alert

Use the custom component in a view:

<x-alert type="danger">
    This is an error message.
</x-alert>

Blade Macros

Define Blade macros:

Blade::macro('bold', function ($text) {
    return "<strong>{$text}</strong>";
});

Use the macro in a view:

{!! Blade::bold('This text is bold') !!}

Conclusion

Recap of Laravel 11 Tutorial

Laravel 11 offers a wide range of features and improvements that make web development faster, easier, and more enjoyable. From enhanced routing and Blade templating to advanced Eloquent ORM capabilities, Laravel 11 is designed to meet the needs of modern web applications.

Additional Resources for Learning Laravel 11

Final Thoughts on Laravel 11 Tutorial

With its elegant syntax, comprehensive documentation, and active community, Laravel 11 is an excellent choice for developers looking to build robust, scalable web applications. Whether you’re a beginner or an experienced developer, Laravel 11 has the tools and resources to help you succeed.

Also, read: How to use Laravel cookies – Get, Set, Delete with example

Leave a Comment