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

Tuesday, February 1, 2022

[FIXED] Get hidden attribute of a model specified using Model::with()

 February 01, 2022     eloquent, laravel, laravel-5     No comments   

Issue

In a controller, I use this code to get all Text objects and their associated authors

return Text::with('authors')->get();

This is part of a backend only available to admins, and I need them to be able to access the authors name fields. But in the Author model, I set protected $hidden = ['name']; when I programmed another part of my app that's for standard users.

There's a hasMany relationship: Each text has many authors. Is there a way to use with, but get some hidden attribute? Or the other way round, to declare some attribute as hidden temporarily when using with?

Please note this is question is about the use of with in combination with hidden attributes. I'm not looking for something like $authors = $authors->makeVisible(['name']); (which is explained here).


Solution

I could find two approaches to solve my problem:

1) Using each as seen in this question

$texts = Text::with('authors')
             ->get()
             ->each(function ($text) {
    $text->authors->makeVisible(['name']);
});

2) Using transform() as recommended in an answer to the same question. This seems to be way faster.

$texts = Text::with('authors')
             ->get()
             ->transform(function ($text) {
    $text->authors->makeVisible(['name']);
    return $text;
});


Answered By - Pida
  • 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