Laravel: Retrieve polymorphic attributes efficiently

My actual Question is: How to return attributes to the client which I actually need, throw the rest away and be as efficient as possible?

So, I have a construction where I basically have media objects, which can be of different types, like video, picture, link and so on. This is constructed in a polymorphic manner. In this example, users can have an avatar, which is in fact a media Object, but the only thing that I'm interested in on client side is actually the image url.

Our applicaiton is RESTful and if I want to list all users, I want the users JSON to basically return a property with only the url of the avatar and not the complete polymorphic model, which I then would have to traverse on client side, not to mention the huge overhead to send from the server to the client.

From User Model:

/** * A user can have an avatar * * @return \Illuminate\Database\Eloquent\Relations\MorphOne */ public function avatar() { return $this->morphOne('Fanlete\Media', 'appendable'); }

From Media Model:

/** * A media element can be extended in different ways (kind of inheritance), this function morphs to the specific implementation * * @return \Illuminate\Database\Eloquent\Relations\MorphTo */ public function mediable() { return $this->morphTo(); } /** * A media element can be appended by various models, i.e. a user to save its avatar * * @return \Illuminate\Database\Eloquent\Relations\MorphTo */ public function appendable() { return $this->morphTo(); }

From Picture Model, a concrete Media implementation:

public function media() { return $this->morphMany('Fanlete\Media', 'mediable'); }

So, let's say I have a function to list all users in my controller:

public function index() { return User::all(); }

Where I want an output like this:

{ "id": 1, "email": "[email protected]", "name": "Example", "surname": "User", "created_at": "2015-06-17 07:05:26", "updated_at": "2015-06-17 07:05:26", "avatar": "" }

At the moment I solve it like this, which feels actually not that elegant and somehow very wrong and bottlenecked:

User Model again:

protected $appends = ['avatar']; public function getAvatarAttribute() { return $this->avatar()->get()->first()->mediable()->get()->first()->url; }

Of course I could also do something like this in my controller:

$users = Users::with("avatar.mediable")->get()->all(); // Now sort out attributes I don't need and return array

and without sortin the output would look like this (very messy and huge overhead):

{ "id": 1, "email": "[email protected]", "name": "Example", "surname": "User", "created_at": "2015-06-17 07:05:26", "updated_at": "2015-06-17 07:05:26", "avatar": { "id": 6, "appendable_id": 1, "appendable_type": "Fanlete\\User", "mediable_id": 6, "mediable_type": "Fanlete\\Picture", "created_at": "2015-06-17 07:05:26", "updated_at": "2015-06-17 07:05:26", "mediable": { "id": 6, "url": "", "title": null, "created_at": "2015-06-17 07:05:26", "updated_at": "2015-06-17 07:05:26" } } }

But this would also feel like a workaround and is exactly that overhead I do not need and want.



You might be almost there.

Your getAvatarAttribute() is way too complicated, indeed. You could try to do something like:

/** we hide the relation from the json */
protected $hidden = ['avatar'];

/** we append the url of the avatar to the json */
protected $appends = ['avatar_url'];

* To not be confused with the avatar() method, I used avatar_url.
public function getAvatarUrlAttribute()
return $this->avatar->mediable->url;

And then, you should be able to do $users = User::with('avatar.mediable')->get(); without the bottleneck, and have a nice JSON response.

Category:rest Time:2019-01-11 Views:0

Related post

  • Retrieve empty attributes of LDAP DN 2009-10-28

    I am currently programming a tool (in ANSI C) for my company which reads from an LDAP Directory and outputs all the data in a specific format (that is: the name format of our old proprietary directory db). This is then handled by another tool which r

  • How do I retrieve the attribute of an element using Swing's HTMLEditorKit.ParserCallback? 2009-11-19

    I am extending HTMLEditorKit.ParserCallback to parse HTML. I am matching on a certain element type in an overridden method like this: @Override public void handleStartTag(Tag t, MutableAttributeSet a, int pos) { if (Tag.DIV.equals(t)) { String id = (

  • rspec validates_presence_of polymorphic attributes ruby on rails 2010-10-20

    I am writing an rspec for an address model that has a polymorphic attribute called :addressable. I am using factory girl for testing. This model has no controller because I do not wish to create a standalone address but that doesnt stop the rspec fro

  • Best way to retrieve data attributes in Python? 2011-09-17

    I have a question that is puzzling me recently about which is the best way to retrieve attributes from outside. Let say I have a class: class Thing: def __init__(self, whatever): self.whatever = whatever x = Thing('foo') Now I know that if I want to

  • CFLDAP failing to retrieve Integer8 attributes, ColdFusion 2011-12-19

    I am trying to retrieve accountExpires attribute value from Active Directory using CFLDAP. However, when I cfdrump the recordset, I get blank values for its value. I've tried retrieving other Integer8 attribute values and they are all blank. From thi

  • Creating a new entity with polymorphic attribute 2012-01-02

    I'm creating a tagging system across three different entity types. I'm running into trouble implementing it as an associated, polymorphic attribute. Editing an existing contact seems to work (it creates the associated record), but when creating a new

  • Unable to retrieve validation attributes (from my model) in my custom html helper 2012-03-05

    I developed my own custom htmlhelper for managing my radio buttons. No problems for generating basic html tag from my custom helper. But I have problems for injecting validation attributes in my html tag (client side unobtrusive validation). I used t

  • How to retrieve user attributes through SAML in WSO2 Identity Server 2012-04-26

    I'm doing a sample webapp that authenticates against WSO2 Identity Server through SAML. It works fine but now I wanted to retrieve user attributes and roles for authorization and I'm completely lost. Reading some SAML docs I know that I must send an

  • How do I retrieve specific attributes of a relationship/collection? 2009-07-05

    Is there a good way to retrieve all of a specific attribute from a relationship/collection? For instance, I want a list of all the names of a person's cars. Obviously I can't do the following: Person.Cars.Name(s) ...but does something of that nature

  • OOP: retrieve 'fathers' attributes from the 'child' object 2009-07-28

    here i am again ;) My problem atm is with nested php classes, i have, for example, a class like this one: class Father{ public $father_id; public $name; public $job; public $sons; public function __construct($id, $name, $job){ $this->father_id = $

  • C# LINQ - Retrieve multiple attributes from single element, convert to structured (non-xml) text 2009-12-11

    I have an XML file with property groups and properties. I want to retrieve the property groups, print the Name attribute from that element, and then print the child properties of said property group below that entry. Example XML file: <?xml versio

  • How to retrieve XML attribute for custom control 2010-03-17

    I've created a combo box control with a edittext and spinner. I'm trying to let the android:prompt attribute be passed onto the spinner, which means I need to catch it in the constructor which passes my the AttributeSet and set it on the spinner. I c

  • Retrieve custom attribute parameter values? 2010-10-13

    if i have created an attribute: public class TableAttribute : Attribute { public string HeaderText { get; set; } } which i apply to a few of my properties in a class public class Person { [Table(HeaderText="F. Name")] public string FirstName { get; s

  • jQuery not able to retrieve placeholder attribute value? 2010-11-21

    Is there a jQuery way for me to retrieve the placeholder attribute of a form input element? I've tried the obvious: alert($('form_input_element').attr('placeholder')); but it returns undefined in both firefox and chrome for some reason! All other att

  • Retrieving HTML attribute values "the DOM 0 way" 2010-12-15

    jQuery has an attr() method which retrieves the value of a given HTML attribute. For instance: var foo = document.getElementById("foo"); $(foo).attr("id"); But, performance-wise this is not optimal since an jQuery object has to be created just to cal

  • Most efficient way to handle variably sized UITableView Cells, and retrieve associated data efficiently 2011-06-06

    Hey all, would really appreciate some help with this - I am aiming at high efficiency w.r.t data fetches and memory usage. I have a core data store, storing table of content items (tocEntity): article title, page number. A page can have multiple arti

  • jQuery .attr retrieving custom attribute returns undefined 2011-06-10

    i have the following problem using jquery. I have sth like this <div id="yxz" value="1"> <span class="delete"></span> </div> now I have this fn but it only returns "undefined", it does however return the id, or class if I ask

  • Retrieving ETag attribute with Feedparser 2011-06-24

    I know that Feedparser supports retrieval of the ETag header (, but the feed I'm retrieving includes 'etag' as an attribute in the content node, for each entry item retrieved: <content type="applicatio

  • The best way to retrieve the attributes from xml elements using C#/.net 3.5 2011-07-26

    If we have a XML like: <Data> <Cars> <Details> <Dataset se-datafilter="cars" dv-datamanipulationrequired="false" dv-filtercondition="" dv-sortcolumn="" dv-gettopNrows="" /> <XmlData></XmlData> </Details> <

  • Is finding Elements by a custom attribute efficient? 2011-07-26

    I'm wondering whether a select statement like this would be efficient: elements = document.body().select("[data-custom-attr=blahblah]"); Does JSoup create a Map for all element attributes and values so that it can look them up efficiently, or would t

Copyright (C), All Rights Reserved.

processed in 0.683 (s). 13 q(s)