Problem: You need to display data from your controller in a Blade view but aren't sure of the best way to pass variables.
Solution:
// Method 1: Using with()
public function index()
{
$users = User::all();
$title = 'User List';
return view('users.index')
->with('users', $users)
->with('title', $title);
}
// Method 2: Using array in view()
public function show($id)
{
$user = User::findOrFail($id);
$posts = $user->posts;
return view('users.show', [
'user' => $user,
'posts' => $posts,
'postCount' => $posts->count()
]);
}
// Method 3: Using compact() (recommended)
public function dashboard()
{
$stats = ['users' => 100, 'posts' => 500];
$recentPosts = Post::latest()->take(5)->get();
$notifications = auth()->user()->notifications;
return view('dashboard', compact('stats', 'recentPosts', 'notifications'));
}
// In your Blade view (users/index.blade.php)
<h1>{{ $title }}</h1>
@foreach ($users as $user)
<p>{{ $user->name }}</p>
@endforeach
// Method 4: Using View::share() for global variables
// In AppServiceProvider boot()
View::share('appName', config('app.name'));
Why it works: Laravel's view system accepts data as an associative array where keys become variable names in the view. compact()
creates an array from variable names, making it cleaner for multiple variables. with()
is chainable and good for conditional data.
Best practice: Use compact()
for multiple variables, array syntax for explicit key-value pairs, and with()
when chaining conditions or adding data dynamically.
Related Topics
- Building Admin Panels in Laravel: Beyond Nova and Filament - Build complex views with data
Share this article
Add Comment
No comments yet. Be the first to comment!