October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Laravel Blade: Passing Data from a Controller to a View and Rendering It Dynamically

A controller passes data to a Blade view as an array in the view() call. Each key becomes a template variable, output is escaped by default, and @if and @forelse handle conditional and looped markup.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Laravel controller sends data to a Blade template by passing an associative array as the second argument to view(). Each array key becomes a variable inside the template, so ['name' => $name] makes $name available to the view, and {{ $name }} prints it with escaping applied. The examples below follow the Laravel 12.x documentation. Before copying them, confirm your version with php artisan --version, because the 12.x pages note that a newer 13.x documentation set exists.

Wire the route to a controller action

A Blade view is only ever rendered by code that runs first. In a typical request, a route points to a controller method, and that method prepares data and returns a view. Laravel’s controller documentation covers the action pattern in full. A minimal setup looks like this:

As an Amazon Associate I earn from qualifying purchases.

In routes/web.php:

use AppHttpControllersGreetingController;

Route::get('/greeting', [GreetingController::class, 'show']);

Generate the controller with php artisan make:controller GreetingController, then add the action:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
namespace AppHttpControllers;

use IlluminateViewView;

class GreetingController extends Controller
{
    public function show(): View
    {
        $name = 'Samantha';

        return view('greeting', ['name' => $name]);
    }
}

Create resources/views/greeting.blade.php with this content:

<h1>Hello, {{ $name }}</h1>

Visiting /greeting returns <h1>Hello, Samantha</h1>. The controller decided the value; the template only decided where it appears.

Pass data from the controller to the view

The Laravel Views documentation describes three ways to supply values. They produce the same result, but they suit different situations.

One value or several values in an array

For a group of related values, pass one associative array. This is the form most controller actions use:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
return view('profile', [
    'user' => $user,
    'posts' => $posts,
]);

Inside profile.blade.php, the template reads $user and $posts. A common model example is a UserController method that returns view('user.profile', ['user' => User::findOrFail($id)]). The findOrFail() call returns a 404 response when no matching record exists, so the template never receives a missing model.

Passing an existing array

If the data is already assembled, pass the variable directly as the second argument, for example view('admin.profile', $data). The keys of $data become the template variables.

Chaining with()

Chained with() calls add values one at a time and are equivalent to the array form:

return view('greeting')
    ->with('name', 'Victoria')
    ->with('occupation', 'Astronaut');
Approach Syntax Best used when
Array as second argument view('profile', ['user' => $user]) Passing a group of related values in one action
Pre-built variable view('profile', $data) The array is assembled elsewhere before rendering
Chained with() view('profile')->with('user', $user) Adding a few values conditionally, one at a time

Match the array keys to the template variables

The template receives data by key, not by the name of the PHP variable that held it. If the controller passes ['profile' => $user], the template must use $profile. Writing $user in that template produces an undefined variable error, which is the most common mismatch when copying examples.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

View names map to folders with dot notation. resources/views/admin/profile.blade.php is referenced as view('admin.profile'). Avoid dots inside folder names, because the dot is reserved as the separator.

Render values safely

Laravel’s Blade documentation describes two output forms:

Syntax Output behaviour Use for
{{ $name }} Escaped through PHP’s htmlspecialchars function Ordinary text, including anything a user may have typed
{!! $html !!} Printed without escaping Trusted HTML that you have already sanitized or generated yourself

Use the escaped form by default. Raw output is the usual source of cross-site scripting bugs when a template prints comments, profile fields, or search terms. Use {!! !!} only when the content is known to be safe, and sanitize it before it reaches the view if it might contain user input.

Render conditional and repeated markup

Blade directives let the template decide which HTML to produce from the data it receives. Two patterns cover most cases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Show content or an empty state with @if

@if ($posts->isEmpty())
    <p>No posts yet.</p>
@else
    <ul>
        @foreach ($posts as $post)
            <li>{{ $post->title }}</li>
        @endforeach
    </ul>
@endif

This works when the controller passes an Eloquent collection or any collection with an isEmpty() method.

Loop and fall back with @forelse

@forelse combines the loop and the fallback in one block, which is shorter and harder to get wrong:

<ul>
    @forelse ($posts as $post)
        <li>{{ $post->title }}</li>
    @empty
        <li>No posts found.</li>
    @endforelse
</ul>

Both forms render plain HTML on the server, so the output is ready before it reaches the browser.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the right scope for data

Explicit controller data is the default. Laravel also offers two ways to make a value available to more than one view, and each widens its scope.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Mechanism Scope Where it is set up
Controller array or with() One response The controller action that returns the view
View::share() Every rendered view Usually the boot() method of a service provider
View composer A specific view, whichever route or controller renders it A service provider, binding logic for that view in one place

Use explicit data for anything a page needs for its own response, because the controller shows where each value comes from. Use a view composer when the same view is returned from several places and needs the same extra value. Reserve View::share() for values that truly apply to every page, such as an application name. Sharing page-specific values globally makes templates depend on invisible setup code.

Understand what “dynamic” means in Blade

In this context, dynamic means the server evaluates PHP values, conditions, and loops while it builds the HTML response. The user sees the result of each request. Laravel’s frontend documentation describes this model as the default: interactions normally request a new HTML document, and the browser re-renders the page. That is sufficient for many applications.

If you need interactions that update part of the page without a full reload, that is a separate decision. The same frontend guide points to Livewire and Alpine.js for Laravel-centric interactivity, and to JavaScript frameworks such as Vue, React, and Svelte for applications built around a client-side interface. Passing data from a controller to a Blade view does not require any of them.

Optional: precompile views for deployment

Laravel compiles Blade templates the first time they are needed and caches the compiled result. For production deployments, php artisan view:cache precompiles every view in the application. php artisan view:clear removes the compiled cache, which is useful after template changes on a server that has cached views. These commands are optional for local development, where the framework recompiles as needed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.