Laravel Tips from my recent projects

I been working for a few Laravel project recently, just to note down some of the interesting tips that I learn about recently

  • It’s still ok to do multiple db connection pulling data , but is a nightmare if you need to pull with relation ( belongTo, hasMany etc) .
  • Pulling the same name table from multiple db is really pain, because you can’t merge the collection if the records having the same keys.
  • If you need extra attribute to return for a model , declare protected $append = array(‘additional parameter’) within the model , the model will now return with this new additional attribute.
  • If you want to manipulate any return attribute , use getAttribute function, for example need a new shop name attribute , declare getShopNameAttribute function and you can follow up combine or modify the string as return result.
  • Use the newQuery function within the model to using some condition by default, for example I have table with a removed field, so I can add this condition in the newQuery function to filter all records which have removed =1
  • If you having a primary key which is not auto id , set the $incrementing = false within the model , if not when you save the record and the return result might be an empty primary key.
  • the created_at, updated_at,deleted_at attribute name can be renamed.
  • using findOrFail and do a catch-all event for all model not found exception can save quite a lot repeated code.

While working on Laravel project, try to poke around the source code , you might find some additional function which really helpful but didn’t mention on the documentation. Laracast is another good resource to learn more about Laravel.

Share it with your friends, thanks !
Share on FacebookTweet about this on TwitterShare on Google+Share on TumblrBuffer this pagePin on PinterestEmail this to someone

You may also like...