agyanadda@gmail.com

Laravel Examples

13 examples 13 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.