In this tutorial, we will learn how to pass data from a controller to a view in the Laravel framework and how to share variables across multiple views.
You'll learn:
Before we begin, make sure you have a basic understanding of MVC (Model-View-Controller) architecture, PHP, and the Laravel framework.
In Laravel, you can pass data from a controller to a view using the with
function. This function accepts two arguments: the name of the variable you want to use in your view and the value of this variable.
public function show()
{
return view('welcome')->with('name', 'John Doe');
}
In this example, 'name' is the variable we are passing to the view, and 'John Doe' is its value. You can access this variable in your view using Blade syntax:
Hello, {{ $name }}
You can share variables across multiple views using the share
method in the AppServiceProvider
:
public function boot()
{
View::share('key', 'value');
}
In this case, 'key' is the name of the variable, and 'value' is its value. You can access this shared variable in any view:
The shared value is: {{ $key }}
Here are some practical examples of how to pass data from controllers to views and share variables across views.
Controller:
public function show()
{
$name = 'John Doe';
$age = 30;
return view('welcome', compact('name', 'age'));
}
In this example, we are passing two variables to the view: 'name' and 'age'. We use the compact
function to pass multiple variables.
View:
<p>Hello, {{ $name }}. You are {{ $age }} years old.</p>
AppServiceProvider:
public function boot()
{
View::share('siteName', 'My Awesome Site');
}
In any view, you can access the shared variable:
<h1>Welcome to {{ $siteName }}</h1>
In this tutorial, we've learned how to pass data from controllers to views and how to share variables across multiple views in Laravel. We've also learned how to use Blade syntax to display these data in our views.
For further learning, you can explore other features of the Laravel framework. Here are some additional resources:
public function show()
{
$items = ['Apple', 'Banana', 'Cherry'];
return view('items', compact('items'));
}
View:
<ul>
@foreach ($items as $item)
<li>{{ $item }}</li>
@endforeach
</ul>
public function boot()
{
View::share('siteName', 'My Awesome Site');
}
In any view, you can access the shared variable:
<h1>Welcome to {{ $siteName }}</h1>
Remember to continue practicing and exploring the Laravel documentation to gain more knowledge and experience.