PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 6, 2022

[FIXED] Separate a relationship from the collection on Laravel 8 - Eloquent

 February 06, 2022     eloquent, laravel, laravel-8, laravel-blade     No comments   

Issue

I am generating a query that collects an invoice, and the related invoice customer.

$invoice = Invoice::with(['lines', 'fullClient'])->findOrFail($idInvoice);     
return view('invoiceView', ['invoice'=>$invoice]);

It works correctly, through $invoice->clients, I can access the client. But I would like to be able to separate the client from the collection invoice. To send it through another variable. So that it looks something like this:

$invoice = Invoice::with(['lines', 'fullClient'])->findOrFail($idInvoice); 
//Some magic here
return view('invoiceView', ['invoice'=>$invoice,'client'=>$client]);

It is to take advantage of an invoice creation view (to be able to edit), which is expected by the $clients collection.
I have searched, to do this in the view, but it is not possible or it is not recommended.

I guess I could do something like thisbefore sending it to view:

$client = $invoice->customer

But then I would be sending it twice on view.


Solution

To unset the relationship from a model you can use unsetRelation($relation) method

$invoice = Invoice::with(['lines', 'fullClient'])->findOrFail($idInvoice); 
$client = $invoice->fullClient;

$invoice->unsetRelation('fullClient');

return view('invoiceView', ['invoice'=>$invoice,'client'=>$client]);



Answered By - Clément Baconnier
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing