1: Create a Controller Method: In your controller, define a method where you want to pass data to the view.
public function showData() {
$data = ['name' => 'Zia', 'age' => 25];
return view('profile', $data);
}
In this example, $data
contains key-value pairs that you want to pass to the view.
2: Passing Data to View Using view()
Helper: The view()
helper is used to load views and pass data to them. Here, we are passing $data
to the profile
view.
3: Access Data in the View: In your Blade template (e.g., profile.blade.php
), you can access the data using the keys from the array:
<h1>Hello, {{ $name }}!</h1>
<p>Age: {{ $age }}</p>
The values of $name
and $age
will be displayed in the view.
4: Alternative - Using with()
Method: You can also pass data using the with()
method:
public function showData() {
return view('profile')->with('name', 'Zia')->with('age', 25);
}
In this case, name
and age
will be passed directly to the view.
5: Passing Multiple Data Sets: You can pass multiple data sets by chaining with()
methods or passing an array:
return view('profile', ['name' => 'Zia', 'age' => 25]);
6: Compiling Data into One Array: For cleaner code, you can compile your data into one array:
public function showData() {
$data = ['name' => 'Zia', 'age' => 25];
return view('profile', compact('data'));
}
Passing data to views in Laravel is simple and versatile. You can use array-based passing, with()
method, or the compact()
function for cleaner code. This flexibility ensures your views are dynamically rendered based on the data passed from the controller.