Sling Academy
Home/PHP/Laravel: How to pass data to Blade templates

Laravel: How to pass data to Blade templates

Last updated: January 15, 2024

Introduction

Laravel Blade is a powerful templating engine that comes with the Laravel framework. It allows developers to generate dynamic HTML content with a clean and reusable syntax. One core concept in Blade templates is passing data from controllers to the views. In this tutorial, we’ll explore various methods of passing data to Blade templates, catered to different scenarios you might come across.

Passing Data from Controllers

The simplest way to pass data to a Blade template in Laravel is directly from a controller. We’ll start with the basics and gradually move to more complex scenarios. Here’s what a basic controller in Laravel might look like:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class WelcomeController extends Controller
{
    public function show()
    {
        $data = 'Welcome to Laravel!';
        return view('welcome', compact('data'));
    }
}

In the above example, we used the compact() function to pass the data to the view. Now let’s see how we would craft our welcome.blade.php template to display this data:

<html>
    <head><title>Laravel Blade</title></head>
    <body>
        <h1>{{ $data }}</h1>
    </body>
</html>

Now, when you hit the route associated with this controller method, you will see ‘Welcome to Laravel!’ displayed on your screen.

With Syntax

The with() method is another way to send data to the view, especially if you’re only passing a single piece of data. Here’s an example:

<?php

namespace App\Http\Controllers;

class GreetingController extends Controller
{
    public function show()
    {
        return view('greeting')->with('name', 'John Doe');
    }
}

The equivalent greeting.blade.php template would simply use the passed variable:

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

This method works great for a cleaner syntax when working with a limited number of variables.

Passing an Array of Data

Sometimes you need to pass more than one variable to the view. Laravel supports passing an associative array directly to the view() function. Here’s how:

<?php

namespace App\Http\Controllers;

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

In your profile.blade.php, you can manipulate both the $user and $posts variables:

<!-- User Profile Info -->
<h2>{{ $user->name }}'s Profile</h2>
<!-- User Posts -->
@foreach($posts as $post)
    <div>{{ $post->title }}</div>
@endforeach

Shared Data Using View Composers

Sometimes, you want to share data across all views or a set of views. Laravel allows you to do so using View Composers. A common use case for this feature is sharing the current authenticated user’s information or global settings. To pass data to all views you could use a service provider:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    public function boot()
    {
        \View::composer('*', function ($view) {
            $view->with('sharedData', 'This data is shared with all views.');
        });
    }
}

composer('*', ...) registers a composer that will execute for all views. The $sharedData variable will then be available across your application, which can be utilized in the following manner:

<footer>
    <p>{{ $sharedData }}</p>
</footer>

Advanced Data Sharing Using View Creators

A View Creator is similar to a Composer but is executed every time a view is instantiated, regardless of whether that view has already been compiled during the request. This can be particularly useful for setting certain data conditions based on unique logic for every sub-view rendered in your application. Here’s a brief example of setting a View Creator:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Support\Facades\View;

class ViewServiceProvider extends ServiceProvider
{
    public function boot()
    {
        View::creator('components.form.input', function ($view) {
            $view->with('currency', 'USD');
        });

        // Rest of the boot method.
    }
}

In your components/form/input.blade.php, you can use $currency now:

<!-- Form Input -->
<div>Currency: {{ $currency }}</div>

Passing Data with Route View

In certain cases, you may wish to bypass a controller and define a view directly in the routing file. Laravel allows you to associate views to routes. Here’s how you pass data to those views:

Route::view('/welcome', 'welcome', ['data' => 'Welcome to Laravel!']);

The data can be accessed as usual within your welcome.blade.php, like:

<h1>{{ $data }}</h1>

Conclusion

In this guide, we’ve explored various methods for passing data to Blade templates in Laravel. Whether you are working with a simple use case or need advanced data-sharing strategies across views, Laravel provides a clear and flexible way to handle data. As you build more complex features, you’ll find these techniques invaluable in keeping your codebase clean and maintainable.

Next Article: Laravel: How to render a PHP array with Blade

Previous Article: Using Livewire with Laravel: A Developer’s Guide

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array