Tuesday, 15 June 2010

php - Add a custom attribute to a Laravel / Eloquent model on load? -


I would like to add a custom attribute / property to a larval / alloconut model when it is loaded, for the same example At this time, in my controller, how can I get: $ model-> open with the method.

  Public function index () {$ sessions = EventSession :: all (); Forex Currency ($ session = $ i = & gt; $ session) {$ session [$ i] - & gt; Available = $ session-> Get (); } Return $ session; }   

It would be nice to be able to eliminate the loop and already have the 'available' attribute set and populated.

I have tried to use something that the events of the model are described in the document, when this object loads, but without success so far

  • There is not a single area in the 'available' underlying table.
  • $ Sessions is being refunded as a JSAN object as part of an API, and therefore the $ session-> gt; Available in a template

    The problem is the fact The model 's toArray () method ignores any of the accessories that are not directly related to any column in the underlying table. Like Taylor O'Tellel, "

    ," It is intentional and for reasons of performance. " Although there is an easy way to achieve this:

      class eventless supernatural [secure $ table = 'sessions'; Protected $ appends = array ('availability'); Public function getAvailabilityAttribute () {return $ this-> calculation availability (); }}   

    Any attribute listed in the Attachment property will automatically be included in the model array or the JSOF form, provided you have added the appropriate accessorator.

    Old Answer (for Lareval versions <4.08):

    The best solution I found is to toArray () < / Code> is to override the method and either sets the expository condition:

      class book extends well (secure $ table = 'books'; Public Function Toure () {$ array = parent :: toArray (); $ Array ['upper'] = $ this- & gt; Upper; Return $ array; } Public Function getUpperAttribute () {Return to Strawper ($ - gt; Title); }}   

    Or, if you have many custom accessories, then loop through them and apply them:

      Class book extended elucidate {Secure $ table = 'books'; Public Function Toure () {$ array = parent :: toArray (); Foreign currency ($ this-> getMutatedAttributes (as the $ key) {if (! Array_key_exists ($ key, $ array)) {$ array [$ key] = $ this- & gt; {$ key};} } $ Array returned;} public function getUpperAttribute () {return ($ - gt; title) on the return;}}    

No comments:

Post a Comment