Difference between with and compact in Laravel
Doesn’t it do the same at the end of the day?
September 6, 2024
The with
and compact
methods in Laravel are used to pass data to views, but they do so in different ways. Here's a detailed comparison:
with
Method
The with method is used to pass individual pieces of data to the view. You can chain multiple with calls to pass multiple pieces of data.
Example:
php
1<?php2return view('caios-bill-users.edit')3 ->with('data', $user)4 ->with('contract_attachments', $contract_attachments);
compact
Function
The compact
function is a PHP function that creates an array from variables and their values. It is useful when you want to pass multiple variables to the view in a more concise way.
Example:
php
1<?php2return view('caios-bill-users.edit', compact('user', 'contract_attachments'));
Differences:
- Syntax and Readability
- Usage
- Chaining
Updated Code Using Both Methods:
Using with
:
php
1<?php2$user = User::findOrFail($id);3$contract_attachments = ContractAttachments::where('user_id', $id)->get();4return view('caios-bill-users.edit')5 ->with('data', $user)6 ->with('contract_attachments', $contract_attachments);
Using compact:
php
1<?php2$user = User::findOrFail($id);3$contract_attachments = ContractAttachments::where('user_id', $id)->get();4return view('caios-bill-users.edit', compact('user', 'contract_attachments'));
Both approaches will pass the $user
and $contract_attachments
data to the view. Choose the one that best fits your coding style and project conventions.