Code | Solutions

This laravel tutorial for beginners continues the Learn Laravel series by turning plain text responses into real pages with Blade views, layouts, and Blade components. If you have not read it yet, start with Part 2: Routes, Route Parameters & Controllers. Part 3 picks up the same Tasks app and the same TaskController.

I’m Usman Nadeem, an AI Full Stack Developer based in Lahore with 12+ years of delivery since February 2014. The Blade patterns below are the ones I use on production Laravel apps, trimmed to what a beginner needs to build clean, reusable pages.

Direct answer (for AI Overviews & scanners)

Blade is Laravel’s templating engine: a controller returns a view, and the view turns data into HTML. Blade files live in resources/views and end in .blade.php. Return one with view('tasks.index', ['tasks' => $tasks]) (the dot means a folder), print data safely with {{ $task }}, and loop with @foreach. Share one header and footer with a layout, either @extends('layouts.app') plus @section('content') filling an @yield('content'), or a component layout <x-layout> with {{ $slot }}. Build reusable pieces with php artisan make:component Alert and use them anywhere as <x-alert type="success" message="Task saved!" />. The examples work on Laravel 12 and the current Laravel 13 release.

Watch the video

Prefer to watch first? Part 3 is a short video (Urdu/Hindi voiceover, with the code on screen). This article writes out the same three concepts with copy-paste Laravel 12 examples. You can also open it on YouTube Shorts.

What you will learn in Part 3 of this Laravel tutorial for beginners

Each video in this series teaches three concepts. Part 3 covers:

  1. Laravel Blade views — where .blade.php files live, passing data from a controller with view(), safe output with {{ }}, and loops with @foreach.
  2. Laravel Blade layouts — one shared header and footer with @extends, @yield, and @section, or the modern <x-layout> component with {{ $slot }}.
  3. Laravel Blade components — php artisan make:component Alert, passing props such as type and message, and reusing one component everywhere.

You only need what Parts 1 and 2 covered: a Laravel project running with php artisan serve, and a TaskController connected to a route. Missed those? Read Part 1 and Part 2 first.


Laravel Blade views: return real HTML from a controller

In Part 2 the controller returned a string such as “Task #5”. Real apps return HTML, and in Laravel that HTML lives in Blade views: files inside resources/views whose names end in .blade.php. The .blade part tells Laravel to compile the file with Blade, so you can mix HTML with short directives like @foreach and @if.

Here is the controller from the video. The index method builds a list of tasks and hands it to a view:

// app/Http/Controllers/TaskController.php
public function index()
{
    $tasks = ['Learn Routes', 'Learn Controllers', 'Learn Blade'];

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

Two details matter. view('tasks.index') uses a dot instead of a slash, so Laravel loads resources/views/tasks/index.blade.php. And each array key becomes a variable in the view, so 'tasks' turns into $tasks. The shorthand view('tasks.index', compact('tasks')) does exactly the same thing.

Now the view itself:

{{-- resources/views/tasks/index.blade.php --}}
<h1>My Tasks ({{ count($tasks) }})</h1>

<ul>
    @foreach ($tasks as $task)
        <li>{{ $task }}</li>
    @endforeach
</ul>

Open /tasks and you see “My Tasks (3)” with three items. A route must point at the method, either the Route::resource('tasks', TaskController::class) line from Part 2 or a single route:

// routes/web.php
use App\Http\Controllers\TaskController;

Route::get('/tasks', [TaskController::class, 'index'])->name('tasks.index');

Why {{ }} is safe by default

Double curly braces escape the value with PHP’s htmlspecialchars, so a task titled <script>alert(1)</script> prints as harmless text instead of running. That blocks a whole class of XSS attacks. {!! $html !!} prints raw HTML; only use it for content you fully trust, never user input.

Blade control structures you will use every day

@forelse is a loop with a built-in “nothing here” case, and @if works like a normal PHP if:

@forelse ($tasks as $task)
    <li>{{ $loop->iteration }}. {{ $task }}</li>
@empty
    <li>No tasks yet. Add your first one!</li>
@endforelse

{{-- Blade comments like this one never reach the browser --}}

Inside any loop, $loop->iteration and $loop->last save you from counting by hand. The full list of directives is in the official Laravel Blade documentation.


Laravel Blade layouts: write the header and footer once

With three or four pages, every view repeats the same <head>, navigation, and footer, and one footer change means editing every file. A layout puts the shared shell in one file and leaves a hole for each page’s content.

Option 1: @extends, @yield and @section

Create the layout file:

{{-- resources/views/layouts/app.blade.php --}}
<!DOCTYPE html>
<html>
<head>
    <title>@yield('title', 'Tasks App')</title>
</head>
<body>
    <nav>Tasks App</nav>
    <main>@yield('content')</main>
    <footer>usmannadeem.com</footer>
</body>
</html>

@yield('content') is the hole. @yield('title', 'Tasks App') is a smaller hole with a default value, used when a page does not set its own title. Now the tasks page only contains what is unique to it:

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

@section('title', 'My Tasks')

@section('content')
    <h1>My Tasks ({{ count($tasks) }})</h1>
    <ul>
        @foreach ($tasks as $task)
            <li>{{ $task }}</li>
        @endforeach
    </ul>
@endsection

@extends('layouts.app') points at resources/views/layouts/app.blade.php (the same dot-means-folder rule). Everything between @section('content') and @endsection is dropped into the layout’s @yield('content'). Edit the footer in the layout once and every page that extends it updates. That is the “ek file badlo, poori website update” moment from the video.

Option 2: the modern x-layout component

Newer Laravel projects and the official starter kits often build the layout as a component instead. It is the same idea with HTML-like syntax:

{{-- resources/views/components/layout.blade.php --}}
<html>
<head>
    <title>{{ $title ?? 'Tasks App' }}</title>
</head>
<body>
    <nav>Tasks App</nav>
    <main>{{ $slot }}</main>
</body>
</html>
{{-- resources/views/tasks/index.blade.php --}}
<x-layout>
    <x-slot:title>My Tasks</x-slot>

    <h1>My Tasks</h1>
</x-layout>

Any file in resources/views/components works as an <x-...> tag, so layout.blade.php becomes <x-layout>. Whatever sits between its tags arrives as {{ $slot }}. The <x-slot:title> line fills a second, named slot called $title. Pick one approach per project; you do not need both. I lean toward the component version on new builds.


Laravel Blade components: write once, use everywhere

Layouts handle the page shell. Blade components handle the small repeated pieces inside pages: alerts, buttons, task cards, form inputs. Write it once and pass in what changes, instead of copying HTML that slowly drifts apart.

Generate one with Artisan:

php artisan make:component Alert

Typical output:

   INFO  Component [app/View/Components/Alert.php] created successfully.

That single command creates two files: a PHP class in app/View/Components/Alert.php and its view in resources/views/components/alert.blade.php. Give the class the props you want to accept:

// app/View/Components/Alert.php
namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    public function __construct(
        public string $type = 'info',
        public string $message = '',
    ) {}

    public function render()
    {
        return view('components.alert');
    }
}

Public constructor properties are automatically available in the component’s view, so the template stays tiny:

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

Now use it anywhere, in any view or layout:

<x-alert type="success" message="Task saved!" />
<x-alert type="error" message="Something went wrong." />

Same component, two alerts. Change alert.blade.php once and every alert updates. A plain attribute like type="success" passes a string. To pass a PHP value, prefix the attribute with a colon:

@if (session('status'))
    <x-alert type="success" :message="session('status')" />
@endif

Anonymous components (no PHP class)

When a component only displays data, you can skip the class. Run php artisan make:component Alert --view (or just create the file in resources/views/components) and declare the props at the top with @props:

{{-- resources/views/components/alert.blade.php --}}
@props(['type' => 'info', 'message' => ''])

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

$attributes->merge() lets the caller add extra classes without editing the component. The <x-layout> above is an anonymous component too.


Recap: Laravel tutorial for beginners, Part 3

  1. Blade views show data. Files live in resources/views as .blade.php. Return them with view('tasks.index', [...]), print with {{ }} (auto-escaped), and loop with @foreach or @forelse.
  2. Layouts keep the design in one place. Use @extends plus @section to fill an @yield, or wrap pages in <x-layout> and print {{ $slot }}.
  3. Components make code reusable. php artisan make:component Alert, then <x-alert type="success" message="Task saved!" /> anywhere in the app.

If /tasks shows your list inside a shared layout, with an <x-alert> at the top, you have finished Part 3.


What’s next: Part 4 — Database, Migrations, and Eloquent

Right now the task list is a hard-coded PHP array. In Part 4 of this Laravel tutorial for beginners, the same view reads real rows from a database:

  • Database setup and migrations — the .env connection settings, php artisan make:migration create_tasks_table, and php artisan migrate
  • Eloquent models — php artisan make:model Task and $fillable for mass assignment protection
  • Eloquent queries — Task::all(), Task::create(), Task::find(), and Task::where() feeding the same Blade view

Part 4 is coming next, so follow Coding Solutions by Usman on YouTube, Instagram, or TikTok so you do not miss it. Missed a step? Read Part 2 or start from Part 1.


Need help building a Laravel application?

If this laravel tutorial for beginners has you planning a production Laravel app — a new build, a feature, or a clean-up of messy Blade templates — I take on selected Laravel development projects. Still choosing a stack? Read Laravel vs Node.js for SaaS, then send a short brief through the contact form and I will tell you whether I am a fit.


FAQ

Q1. What is Blade in Laravel? A. Blade is Laravel’s built-in templating engine. Blade files live in resources/views and end in .blade.php. They mix normal HTML with directives such as @foreach and @if, and Laravel compiles them into plain PHP and caches the result, so they stay fast.

Q2. How do I pass data from a controller to a Blade view? A. Return view(‘tasks.index’, [‘tasks’ => $tasks]) from the controller. Each array key becomes a variable in the view, so ‘tasks’ is available as $tasks. The shorthand compact(‘tasks’) does the same thing.

Q3. What is the difference between {{ }} and {!! !!} in Blade? A. Double curly braces print a value escaped with htmlspecialchars, which protects against XSS attacks. {!! !!} prints raw, unescaped HTML, so only use it for content you fully trust, never for user input.

Q4. How do I loop through data in a Blade view? A. Use @foreach ($tasks as $task) … @endforeach. Use @forelse with @empty when you also want a message for an empty list. Inside the loop, the $loop variable gives helpers such as $loop->iteration and $loop->last.

Q5. What do @extends, @yield and @section do in Laravel? A. A layout file marks holes with @yield(‘content’). A page starts with @extends(‘layouts.app’) and fills the hole with @section(‘content’) … @endsection. The header and footer live only in the layout, so one edit updates every page.

Q6. Should I use @extends or an x-layout component? A. Both work in Laravel 12. @extends with @yield is the classic approach. An x-layout component in resources/views/components with {{ $slot }} is the modern approach used by the official starter kits. Pick one per project and use it consistently.

Q7. How do I create a Blade component in Laravel 12? A. Run php artisan make:component Alert. Laravel creates app/View/Components/Alert.php and resources/views/components/alert.blade.php. Add public constructor properties such as $type and $message, then use the component as x-alert with type and message attributes in any view.

Q8. What will Part 4 of this Laravel series cover? A. Part 4 covers the database: connecting Laravel in the .env file, creating a tasks table with migrations and php artisan migrate, building a Task model with $fillable, and reading and saving tasks with Eloquent queries such as Task::all(), Task::create(), Task::find() and Task::where().


Tags

2026 ai tools aiagent Angular 21 Angular Developer for Hire Angular Performance Angular Signals Angular TypeScript Best Practices API Authentication API Development API Integration API Security API Versioning B2B SaaS Backend Development Backend Framework Comparison Best PHP Framework 2026 Best Practices Box Model CakePHP CakePHP 2026 CakePHP Laravel PHP Developer CakePHP Tutorial 2026 CakePHP vs Laravel Case Study Client Management cost to hire freelance developer crewai CRM Integration css css animation CSS Tips CSS Tutorial Database Optimization Developer Tools Enterprise Angular Development Express.js FastAPI Tutorial 2026 framework comparison Freelance Angular Developer Freelance Developer freelance developer guide freelance developer tips Freelance Development freelance full-stack developer Freelance Laravel Developer Freelance PHP Developer Freelance Web Developer freelance web developer process Freelance Web Development Freelancer vs Agency Freelancing Tips Front-End Development frontend Frontend Development Full Stack Developer Full Stack Developer Pakistan Full Stack Development Full-Stack Case Study Full-Stack Development Grid Hire a Developer Hire Angular Developer hire freelance developer hire freelance full-stack developer Hire Laravel Developer how to work with a freelance dev how to write a project brief individual software engineer freelance individual software engineer hire Inertia.js javascript JavaScript Frameworks JWT Authentication laravel Laravel 13 Laravel 2026 Laravel API 2026 Laravel Application Laravel Development Laravel Optimization Scale Laravel Performance Laravel REST API Laravel REST API Tutorial Laravel Sanctum Laravel Tutorial Laravel vs CakePHP Laravel Vue Tutorial multi-agent Next.js Node.js Node.js API Node.js developer Node.js Developer Portfolio Node.js Express Node.js Tutorial Nuxt PERN Stack PHP PHP Developer PHP Developer for Hire PHP Development PHP Framework PHP Framework Comparison PHP Performance PHP Web Development PostgreSQL Prisma Production Deployment project brief template Project Management Python Backend Developer Python FastAPI react React developer for hire React Node.js Developer Portfolio React SPA React Tutorial React vs Vue Real-Time Chat App Redis Caching Responsive Design REST API SaaS Development Sanctum SMB Web Development Socket.io React Real-Time App Socket.io Tutorial Software Development software development process Software Integration software project brief SSG SSR Standalone Components System Integration TypeScript Strict Mode Vite vue Vue 4 Composition API Vue Laravel Developer Vue.js Development web app development process Web Design Web Design Fundamentals web development Web Development 2026 Web Development Cost Web Layout Web Projects WebSocket

Recent News