How to use Inject View in Laravel

AuthorSumit Dey Sarkar

Pubish Date26 Jan 2024

categoryLaravel

In this tutorial, we will learn how to use inject view in Laravel.

How to use Inject View in Laravel

Inject functionality in blade

In Laravel, you can pass data to views in several ways. Here's one common method using the view() function:

Using the view() Function:

In your controller or route closure, you can use the view() function to load a view and pass data to it.

public function index()
{
    $data = [
        'key' => 'value',
        'another_key' => 'another_value',
    ];

    return view('your.view.name', $data);
}

Here, 'your.view.name' is the name of your view file, and $data is an associative array containing the data you want to pass to the view.

Using Compact:

You can use the compact() function to compact variables and pass them to the view:

public function index()
{
    $variable1 = 'value1';
    $variable2 = 'value2';

    return view('your.view.name', compact('variable1', 'variable2'));
}

This is a shorthand way of passing variables to the view.

Using with Method:

You can also use the with method on the view instance:

public function index()
{
    $variable = 'value';

    return view('your.view.name')->with('key', $variable);
}

This will pass the variable to the view with the specified key.

In your view file, you can then access these variables using standard Blade syntax:

<p>{{ $key }}</p>
<p>{{ $another_key }}</p>

Make sure to replace your.view.name, key, value, etc., with your actual view name and data.

Comments 0

Leave a comment