To pass data to a Blade view in Laravel, you can use the with
function or the compact
function in your controller. Here's how to pass data to a view and display it:
with
function or the compact
function. Here's an example using the with
function:public function index()
{
$data = ['name' => 'John', 'age' => 30];
return view('myView')->with('data', $data);
}
Or using the compact
function:
public function index()
{
$name = 'John';
$age = 30;
return view('myView', compact('name', 'age'));
}
<h1>{{ $data['name'] }}</h1>
<p>{{ $data['age'] }}</p>
Or:
<h1>{{ $name }}</h1>
<p>{{ $age }}</p>
The data passed from the controller will be accessible in the view using the provided variable name ($data
, $name
, $age
in the above examples) and you can display it or use it as needed.