Difference between with and compact in Laravel
Doesnāt it do the same at the end of the day?
September 06, 2024 ā¢ Code
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
returnĀ view('caios-bill-users.edit')
->with('data',Ā $user)
->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
returnĀ view('caios-bill-users.edit',Ā compact('user',Ā 'contract_attachments'));
Differences:
- Syntax and Readability
- :
- Usage
- :
- Chaining
- :
Updated Code Using Both Methods:
UsingĀ with:
<?php
$userĀ =Ā User::findOrFail($id);
$contract_attachmentsĀ =Ā ContractAttachments::where('user_id',Ā $id)->get();
returnĀ view('caios-bill-users.edit')
->with('data',Ā $user)
->with('contract_attachments',Ā $contract_attachments);
UsingĀ compact:
<?php
$userĀ =Ā User::findOrFail($id);
$contract_attachmentsĀ =Ā ContractAttachments::where('user_id',Ā $id)->get();
returnĀ 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.