How to send data from controller to view in Laravel?


 

Here's an example of how you can send data from a controller to a view in Laravel, along with the corresponding route in your web.php file:

Controller:

<?php
namespace
App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
   
public function showProfile()
    {
       
$user = Auth::user();
       
return view('profile')->with('user', $user);
    }
}

 

web.php:

 

<?php
use
Illuminate\Support\Facades\Route;
Route::
get('/profile', 'UserController@showProfile')->name('profile');

 

To access the $user variable in the view template, you can use Blade syntax like this:

<h1>Welcome, {{ $user->name }}</h1>

 

You can also pass multiple variables to the view by using the compact function like this:

return view('profile', compact('user', 'posts')); 

 

Then, in the view template, you can access the variables like this:

<h1>Welcome, {{ $user->name }}</h1> @foreach ($posts as $post) <div>{{ $post->title }}</div> @endforeach

 

Post a Comment

Previous Post Next Post