agyanadda@gmail.com

Laravel Examples

31 examples 31 topics

Learn by doing. Every example below can be opened in our online editor — change the code, press Run and see the result instantly.

Open the Try it Now editor »

Laravel Introduction

Laravel Basics · 1 example
Example — A complete Laravel page in one route PHP
<?php
// routes/web.php
use Illuminate\Support\Facades\Route;

Route::get('/hello', function () {
    return 'Hello from Laravel!';
});

Open http://127.0.0.1:8000/hello and the browser shows: Hello from Laravel! One line maps a URL to the code that answers it.

Laravel Installation

Laravel Basics · 1 example
Example — Create and run a new project Bash
# 1. Create the project
composer create-project laravel/laravel blog

# 2. Go into the folder
cd blog

# 3. Start the development server
php artisan serve
# INFO  Server running on [http://127.0.0.1:8000].

After php artisan serve, open http://127.0.0.1:8000 in your browser to see the Laravel welcome page. Press Ctrl+C to stop the server.

Laravel Folder Structure

Laravel Basics · 1 example
Example — Where each part of a page lives PHP
<?php
// routes/web.php            -> the URL
Route::get('/about', [PageController::class, 'about']);

// app/Http/Controllers/PageController.php -> the logic
public function about()
{
    return view('about');   // loads resources/views/about.blade.php
}

// resources/views/about.blade.php -> the HTML
// <h1>About us</h1>

view('about') looks for resources/views/about.blade.php. Dots are folders: view('pages.about') loads resources/views/pages/about.blade.php.

Laravel Routing

Laravel Basics · 1 example
Example — Parameters and named routes PHP
<?php
use Illuminate\Support\Facades\Route;

Route::get('/users/{id}', function (int $id) {
    return "User number $id";
})->name('users.show');

Route::get('/hello/{name?}', function (string $name = 'Guest') {
    return "Hello, $name";
});

// Building a URL from the name:
// route('users.show', 5)  =>  http://127.0.0.1:8000/users/5

/users/5 shows "User number 5". /hello shows "Hello, Guest" and /hello/Asha shows "Hello, Asha".

Laravel Controllers

Laravel Basics · 1 example
Example — A simple controller PHP
<?php
// app/Http/Controllers/PostController.php
namespace App\Http\Controllers;

class PostController extends Controller
{
    public function index()
    {
        $posts = ['Learn Routing', 'Learn Blade', 'Learn Eloquent'];

        return view('posts.index', ['posts' => $posts]);
    }
}

// routes/web.php
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'index']);

Visiting /posts runs index(), which sends the $posts array to resources/views/posts/index.blade.php.

Laravel Blade Templates

Laravel Basics · 1 example
Example — Layout and child page PHP
{{-- resources/views/layouts/app.blade.php --}}
<html>
<body>
  <h1>My Blog</h1>
  @yield('content')
</body>
</html>

{{-- resources/views/posts/index.blade.php --}}
@extends('layouts.app')

@section('content')
  <ul>
    @forelse ($posts as $post)
      <li>{{ $post }}</li>
    @empty
      <li>No posts yet.</li>
    @endforelse
  </ul>
@endsection

The page shows the "My Blog" heading from the layout, then a list of posts — or "No posts yet." if the array is empty.

Laravel Migrations

Database and Eloquent · 1 example
Example — Posts table migration PHP
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('title');
            $table->text('body');
            $table->boolean('is_published')->default(false);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

Run php artisan migrate and a posts table appears with id, user_id, title, body, is_published, created_at and updated_at columns.

Laravel Eloquent Models

Database and Eloquent · 1 example
Example — Model and queries PHP
<?php
// app/Models/Post.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['user_id', 'title', 'body', 'is_published'];
}

// Anywhere in a controller:
$post = Post::create([
    'user_id' => 1,
    'title'   => 'Hello Eloquent',
    'body'    => 'My first post.',
]);

$published = Post::where('is_published', true)->latest()->get();
echo $post->title;   // Hello Eloquent

create() inserts a row and returns a Post object. Columns are read as properties, e.g. $post->title.

Laravel CRUD Operations

Database and Eloquent · 1 example
Example — store, update and destroy PHP
<?php
public function store(Request $request)
{
    $data = $request->validate([
        'title' => 'required|max:255',
        'body'  => 'required',
    ]);
    $request->user()->posts()->create($data);

    return redirect()->route('posts.index')->with('success', 'Post created');
}

public function update(Request $request, Post $post)
{
    $post->update($request->validate(['title' => 'required|max:255', 'body' => 'required']));

    return redirect()->route('posts.show', $post)->with('success', 'Post updated');
}

public function destroy(Post $post)
{
    $post->delete();

    return back()->with('success', 'Post deleted');
}

/* Delete button in Blade:
<form method="POST" action="{{ route('posts.destroy', $post) }}">
    @csrf
    @method('DELETE')
    <button>Delete</button>
</form> */

Post $post is filled by route model binding. The delete form is a POST form that Laravel treats as DELETE because of @method('DELETE').

Laravel Eloquent Relationships

Database and Eloquent · 1 example
Example — User has many posts PHP
<?php
// app/Models/User.php
public function posts()
{
    return $this->hasMany(Post::class);
}

// app/Models/Post.php
public function user()
{
    return $this->belongsTo(User::class);
}

// Controller: load posts with their authors in 2 queries
$posts = Post::with('user')->latest()->get();

foreach ($posts as $post) {
    echo $post->title . ' by ' . $post->user->name . PHP_EOL;
}

Output is one line per post, e.g. "Hello Eloquent by Asha". with('user') prevents a separate query for every author.

Laravel Form Validation

Forms, Security and APIs · 1 example
Example — Register form validation PHP
<?php
public function store(Request $request)
{
    $data = $request->validate([
        'name'     => 'required|string|max:100',
        'email'    => 'required|email|unique:users,email',
        'password' => 'required|min:8|confirmed',
    ]);

    // only runs if every rule passed
    User::create($data);

    return redirect('/login')->with('success', 'Account created');
}

/* Blade:
<input name="email" value="{{ old('email') }}">
@error('email')
    <span class="text-danger">{{ $message }}</span>
@enderror */

If the email is already registered, the user is sent back to the form with "The email has already been taken." under the field and their other input still filled in.

Laravel Middleware and Authentication

Forms, Security and APIs · 1 example
Example — Protect routes and check for admins PHP
<?php
// routes/web.php
Route::middleware('auth')->group(function () {
    Route::get('/dashboard', fn () => view('dashboard'));
    Route::resource('posts', PostController::class);
});

// app/Http/Middleware/EnsureUserIsAdmin.php
public function handle(Request $request, Closure $next): Response
{
    if (! $request->user()?->is_admin) {
        abort(403, 'Admins only');
    }

    return $next($request);
}

// bootstrap/app.php (Laravel 11+)
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias(['admin' => EnsureUserIsAdmin::class]);
})

A guest who opens /dashboard is sent to /login. Routes with ->middleware('admin') show a 403 "Admins only" page to users who are not admins.

Laravel REST API

Forms, Security and APIs · 1 example
Example — A JSON API for posts PHP
<?php
// routes/api.php
Route::apiResource('posts', PostController::class)->only(['index', 'show']);
Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('posts', PostController::class)->except(['index', 'show']);
});

// app/Http/Controllers/PostController.php
public function index()
{
    return Post::latest()->paginate(10);
}

public function store(Request $request)
{
    $data = $request->validate(['title' => 'required|max:255', 'body' => 'required']);
    $post = $request->user()->posts()->create($data);

    return response()->json($post, 201);
}

public function destroy(Post $post)
{
    $post->delete();

    return response()->noContent();   // 204
}

GET /api/posts returns JSON like {"data":[{"id":1,"title":"Hello Eloquent",...}],"current_page":1,...}. Creating and deleting need a Sanctum token; invalid input returns status 422 with the errors as JSON.

Laravel Artisan Commands

Laravel Basics · 1 example
Example — Generate a full set of files and test in Tinker Bash
# Model + migration + resource controller
php artisan make:model Post -mcr
#  INFO  Model [app/Models/Post.php] created successfully.
#  INFO  Migration [database/migrations/..._create_posts_table.php] created successfully.
#  INFO  Controller [app/Http/Controllers/PostController.php] created successfully.

# Try Eloquent queries interactively
php artisan tinker
> App\Models\User::count()
= 3
> exit

# Something not updating? Clear all caches
php artisan optimize:clear

-mcr means -m (migration), -c (controller) and -r (resource methods). Tinker runs PHP code against your real database, so be careful with delete() there.

Laravel Configuration and .env

Laravel Basics · 1 example
Example — A custom config file PHP
<?php
// .env
// SITE_WHATSAPP=919876543210

// config/site.php
return [
    'whatsapp' => env('SITE_WHATSAPP', ''),
    'per_page' => 12,
];

// Anywhere in your app (controller, Blade, job):
$number  = config('site.whatsapp');   // 919876543210
$perPage = config('site.per_page');   // 12

// Blade: <a href="https://wa.me/{{ config('site.whatsapp') }}">Chat</a>

env() is used only in the config file; the rest of the app calls config(), which keeps working after php artisan config:cache.

Laravel Request and Response

Laravel Basics · 1 example
Example — Search page with query string PHP
<?php
use Illuminate\Http\Request;

// GET /search?q=laravel&page=2
public function search(Request $request)
{
    $q = trim($request->query('q', ''));

    if ($q === '') {
        return redirect()->route('home')->with('error', 'Type something to search');
    }

    if ($request->wantsJson()) {
        return response()->json(['query' => $q, 'results' => []]);
    }

    return view('search', ['q' => $q]);
}

/search?q=laravel shows the search view. An empty search redirects home with a one-time error message. A request that asks for JSON gets {"query":"laravel","results":[]}.

Laravel Blade Components

Laravel Basics · 1 example
Example — A reusable alert component PHP
{{-- resources/views/components/alert.blade.php --}}
@props(['type' => 'info'])

<div {{ $attributes->merge(['class' => 'alert alert-' . $type]) }}>
    {{ $slot }}
</div>

{{-- Using it in any view --}}
<x-alert type="success">Post saved successfully!</x-alert>

<x-alert type="danger" class="mt-3">Something went wrong.</x-alert>

{{-- Output HTML --}}
{{-- <div class="alert alert-success">Post saved successfully!</div> --}}
{{-- <div class="alert alert-danger mt-3">Something went wrong.</div> --}}

type becomes a prop, the text between the tags becomes $slot, and the extra class="mt-3" is merged into the class list.

Laravel Seeders and Factories

Database and Eloquent · 1 example
Example — Factory and seeder PHP
<?php
// database/factories/PostFactory.php
public function definition(): array
{
    return [
        'user_id'      => \App\Models\User::factory(),
        'title'        => fake()->sentence(6),
        'body'         => fake()->paragraphs(3, true),
        'is_published' => fake()->boolean(80),
    ];
}

// database/seeders/DatabaseSeeder.php
public function run(): void
{
    \App\Models\User::factory()->create([
        'name'  => 'Admin',
        'email' => 'admin@example.com',
    ]);

    \App\Models\User::factory(5)
        ->has(\App\Models\Post::factory(3))
        ->create();
}

php artisan db:seed creates 1 admin and 5 users with 3 posts each — 15 posts with random titles, about 80% of them published.

Laravel Query Builder

Database and Eloquent · 1 example
Example — Posts per author report PHP
<?php
use Illuminate\Support\Facades\DB;

$report = DB::table('posts')
    ->join('users', 'users.id', '=', 'posts.user_id')
    ->select('users.name', DB::raw('COUNT(posts.id) as total'))
    ->where('posts.is_published', true)
    ->groupBy('users.id', 'users.name')
    ->orderByDesc('total')
    ->get();

foreach ($report as $row) {
    echo "$row->name: $row->total posts" . PHP_EOL;
}

// Bulk update in one query
DB::table('posts')->where('user_id', 7)->update(['is_published' => false]);

Output, e.g.: "Asha: 12 posts", "Ravi: 8 posts". The join and GROUP BY run as one SQL query.

Laravel Scopes, Accessors and Casts

Database and Eloquent · 1 example
Example — A cleaner Post model PHP
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Post extends Model
{
    use SoftDeletes;

    protected function casts(): array
    {
        return ['is_published' => 'boolean', 'published_at' => 'datetime'];
    }

    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    protected function title(): Attribute
    {
        return Attribute::make(set: fn (string $value) => Str::title($value));
    }
}

// Usage
$posts = Post::published()->latest()->get();
echo $posts->first()?->published_at?->format('d M Y');   // 01 Dec 2026

Saving the title "learn laravel scopes" stores "Learn Laravel Scopes". published_at is a Carbon date, so ->format() works directly.

Laravel Collections

Database and Eloquent · 1 example
Example — Order summary with collections PHP
<?php
$orders = collect([
    ['customer' => 'Asha', 'city' => 'Patna',  'amount' => 499, 'status' => 'paid'],
    ['customer' => 'Ravi', 'city' => 'Delhi',  'amount' => 999, 'status' => 'paid'],
    ['customer' => 'Neha', 'city' => 'Patna',  'amount' => 299, 'status' => 'failed'],
    ['customer' => 'Amit', 'city' => 'Patna',  'amount' => 799, 'status' => 'paid'],
]);

$paid = $orders->where('status', 'paid');

echo $paid->sum('amount');                          // 2297
echo $paid->pluck('customer')->implode(', ');        // Asha, Ravi, Amit
print_r($paid->groupBy('city')->map->count()->all()); // [Patna => 2, Delhi => 1]

where() keeps paid orders, sum() totals them, pluck() takes the names, and groupBy()->map->count() counts paid orders per city.

Laravel File Upload

Forms, Security and APIs · 1 example
Example — Upload a profile photo PHP
<?php
use Illuminate\Support\Facades\Storage;

public function updatePhoto(Request $request)
{
    $request->validate([
        'photo' => 'required|image|mimes:jpg,jpeg,png,webp|max:2048',
    ]);

    $user = $request->user();

    if ($user->photo) {
        Storage::disk('public')->delete($user->photo);   // remove the old photo
    }

    $user->update([
        'photo' => $request->file('photo')->store('photos', 'public'),
    ]);

    return back()->with('success', 'Photo updated');
}

/* Blade form:
<form method="POST" action="{{ route('profile.photo') }}" enctype="multipart/form-data">
    @csrf
    <input type="file" name="photo" accept="image/*">
    <button>Upload</button>
</form> */

The file is saved as storage/app/public/photos/<random-name>.jpg and shown with asset('storage/' . $user->photo). The old photo is deleted first.

Laravel Authorization: Gates and Policies

Forms, Security and APIs · 1 example
Example — Only the author can edit PHP
<?php
// app/Policies/PostPolicy.php
public function update(User $user, Post $post): bool
{
    return $user->id === $post->user_id || $user->is_admin;
}

public function delete(User $user, Post $post): bool
{
    return $this->update($user, $post);
}

// app/Http/Controllers/PostController.php
use Illuminate\Support\Facades\Gate;

public function edit(Post $post)
{
    Gate::authorize('update', $post);   // 403 for other users

    return view('posts.edit', compact('post'));
}

/* Blade:
@can('update', $post)
    <a href="{{ route('posts.edit', $post) }}">Edit</a>
@endcan */

The author and admins see the Edit link and can open the page. Another user does not see the link, and opening the URL directly shows a 403 Forbidden page.

Laravel API Authentication with Sanctum

Forms, Security and APIs · 1 example
Example — Login, protected route and logout PHP
<?php
// routes/api.php
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

Route::post('/login', function (Request $request) {
    $request->validate(['email' => 'required|email', 'password' => 'required']);

    $user = User::where('email', $request->email)->first();

    if (! $user || ! Hash::check($request->password, $user->password)) {
        throw ValidationException::withMessages(['email' => 'Wrong email or password.']);
    }

    return ['token' => $user->createToken('mobile-app')->plainTextToken];
});

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/me', fn (Request $request) => $request->user());
    Route::post('/logout', function (Request $request) {
        $request->user()->currentAccessToken()->delete();
        return response()->noContent();
    });
});

POST /api/login returns {"token":"1|abc..."}. GET /api/me with the header Authorization: Bearer 1|abc... returns the user as JSON; without it, the response is 401 Unauthenticated.

Laravel Sending Email

Advanced Laravel · 1 example
Example — Welcome email PHP
<?php
// app/Mail/WelcomeMail.php
namespace App\Mail;

use App\Models\User;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;

class WelcomeMail extends Mailable
{
    public function __construct(public User $user) {}

    public function envelope(): Envelope
    {
        return new Envelope(subject: 'Welcome to AgyanAdda!');
    }

    public function content(): Content
    {
        return new Content(view: 'emails.welcome');
    }
}

// resources/views/emails/welcome.blade.php
// <h2>Hi {{ $user->name }},</h2>
// <p>Thanks for joining. Start learning today!</p>

// Controller
use Illuminate\Support\Facades\Mail;
Mail::to($user)->send(new WelcomeMail($user));

The user receives an email with the subject "Welcome to AgyanAdda!" and the body "Hi Asha, Thanks for joining...". With MAIL_MAILER=log it appears in storage/logs/laravel.log instead.

Laravel Queues and Jobs

Advanced Laravel · 1 example
Example — Send the welcome email in the background PHP
<?php
// app/Jobs/SendWelcomeEmail.php
namespace App\Jobs;

use App\Mail\WelcomeMail;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Mail;

class SendWelcomeEmail implements ShouldQueue
{
    use Queueable;

    public $tries = 3;

    public function __construct(public User $user) {}

    public function handle(): void
    {
        Mail::to($this->user)->send(new WelcomeMail($this->user));
    }
}

// After registration (controller):
SendWelcomeEmail::dispatch($user);

// Terminal: start a worker
// php artisan queue:work

Registration finishes instantly. The worker sends the email a moment later and retries up to 3 times if the mail server fails.

Laravel Task Scheduling

Advanced Laravel · 1 example
Example — Daily cleanup and a morning report PHP
<?php
// routes/console.php  (Laravel 11+)
use App\Models\Otp;
use Illuminate\Support\Facades\Schedule;

// Delete expired OTPs every hour
Schedule::call(function () {
    Otp::where('created_at', '<', now()->subHour())->delete();
})->hourly();

// Send a sales report at 9 AM India time, Monday to Friday
Schedule::command('report:send')
    ->weekdays()
    ->dailyAt('09:00')
    ->timezone('Asia/Kolkata')
    ->withoutOverlapping();

// Prune old login logs every Sunday
Schedule::command('model:prune')->weekly();

php artisan schedule:list shows three tasks with their next run times. On the server, the single cron line runs them all at the right times.

Laravel Caching

Advanced Laravel · 1 example
Example — Cache the homepage posts PHP
<?php
use Illuminate\Support\Facades\Cache;

// HomeController
public function index()
{
    $posts = Cache::remember('home.latest-posts', now()->addMinutes(30), function () {
        return Post::published()->with('user')->latest()->take(10)->get();
    });

    return view('home', compact('posts'));
}

// PostController@store / update / destroy — clear it when posts change
Cache::forget('home.latest-posts');

The first visitor runs the query; for the next 30 minutes every visitor gets the cached list with no database query. Saving a post clears the cache, so the change appears immediately.

Laravel Testing

Advanced Laravel · 1 example
Example — Testing post creation PHP
<?php
namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PostTest extends TestCase
{
    use RefreshDatabase;

    public function test_guests_are_redirected_to_login(): void
    {
        $this->get('/posts/create')->assertRedirect('/login');
    }

    public function test_user_can_create_a_post(): void
    {
        $user = User::factory()->create();

        $this->actingAs($user)
            ->post('/posts', ['title' => 'My test post', 'body' => 'Hello'])
            ->assertRedirect('/posts');

        $this->assertDatabaseHas('posts', ['title' => 'My test post', 'user_id' => $user->id]);
    }

    public function test_title_is_required(): void
    {
        $this->actingAs(User::factory()->create())
            ->post('/posts', ['title' => '', 'body' => 'Hello'])
            ->assertSessionHasErrors('title');
    }
}

php artisan test runs the three tests and prints PASS for each, e.g. "✓ user can create a post". If someone breaks the validation later, test_title_is_required fails.

Laravel Deployment

Advanced Laravel · 1 example
Example — Typical deployment on a VPS Bash
cd /var/www/myapp

# 1. Get the latest code
git pull origin main

# 2. PHP packages without dev tools
composer install --no-dev --optimize-autoloader

# 3. Database changes (--force is required in production)
php artisan migrate --force

# 4. Front-end assets (if you use Vite)
npm ci && npm run build

# 5. Public storage link (first deploy only)
php artisan storage:link

# 6. Cache config, routes, views and events
php artisan optimize

# 7. Reload queue workers
php artisan queue:restart

# Permissions (first deploy)
sudo chown -R www-data:www-data storage bootstrap/cache

After these steps, the site runs the new code with cached config and routes. If something looks wrong, check storage/logs/laravel.log.

Laravel Best Practices

Advanced Laravel · 1 example
Example — Before and after: a cleaner controller PHP
<?php
// ❌ Before: everything in the controller, N+1 queries, no validation
public function index()
{
    $posts = Post::where('is_published', 1)->orderBy('id', 'desc')->get();
    foreach ($posts as $p) { $p->author = User::find($p->user_id)->name; }
    return view('posts.index', ['posts' => $posts]);
}

// ✅ After: scope, eager loading, pagination
public function index()
{
    $posts = Post::published()->with('user')->latest()->paginate(12);

    return view('posts.index', compact('posts'));
}

// ✅ Validation in a Form Request, save in a transaction
public function store(StorePostRequest $request)
{
    $post = DB::transaction(fn () => $request->user()->posts()->create($request->validated()));

    return redirect()->route('posts.show', $post)->with('success', 'Post created');
}

The "after" version runs 2 queries instead of 1 + one per post, shows 12 posts per page, and keeps validation out of the controller.