www.techtic.com | info@techtic.com
www.techtic.com | info@techtic.com
Laravel Tips
1. Increments and Decrements
2. XorY methods
3. Model boot() method
4. Relationship with conditions and ordering
5. Model properties: timestamps, appends etc.
6. Find multiple entries
7. WhereX
8. Order by relationship
9. Eloquent::when() – no more if-else’s
10. BelongsTo Default Models
11. Order by Mutator
12. Default ordering in global scope
13. Raw query methods
14. Replicate: make a copy of a row
15. Chunk() method for big tables
16. Create additional things when creating a
model
17. Override updated_at when saving
18. What is the result of an update()?
19. Transform brackets into an Eloquent query
20. orWhere with multiple parameters
21. onDelete('set null')
22. dropForeign([]);
23. Model Validation
List of Laravel Tips
www.techtic.com | info@techtic.com
Instead of this:
1. Increments and Decrements
Do this:
Also these will work:
Laravel Tips
www.techtic.com | info@techtic.com
Eloquent has quite a few functions that combine two methods, like “please do X,
otherwise do Y”.
Ex 1 – findOrFail():
Instead of:
2. XorY Methods
Do this:
Laravel Tips
www.techtic.com | info@techtic.com
Ex 2 – firstOrCreate():
Instead of:
2. XorY Methods
Do this:
Laravel Tips
www.techtic.com | info@techtic.com
There is a magical place called boot() in an Eloquent model where you can override
default behavior:
3. Model boot() method
Probably one of the most popular examples is setting some field value at the
moment of creating the model object.
Laravel Tips
www.techtic.com | info@techtic.com
Define Relationship:
4. Relationship with conditions and ordering
Already add where or orderBy?
For example, if you want a specific relationship for some type of users, also ordered
by email, you can do this:
Laravel Tips
www.techtic.com | info@techtic.com
There are a few “parameters” of an Eloquent model, in the form of properties of
that class. The most popular ones are probably these:
5. Model properties: timestamps, appends etc.
there’s more:
Laravel Tips
www.techtic.com | info@techtic.com
find() Method
6. Find multiple entries
Few people know about that it can accept multiple IDs as an array:
Laravel Tips
www.techtic.com | info@techtic.com
There’s an elegant way to turn this:
7. WhereX
Do this:
Also, there are some pre-defined methods in Eloquent, related to date/time:
Laravel Tips
www.techtic.com | info@techtic.com
Separate relationship for the latest post on the topic:
8. Order by Relationship
And then, in our controller, we can do this “magic”:
Laravel Tips
www.techtic.com | info@techtic.com
write conditional queries with “if-else”, something like this:
9 Eloquent::when() – no more if-else’s
there’s a better way – to use when():
Laravel Tips
www.techtic.com | info@techtic.com
It may not feel shorter or more elegant, but the most powerful is passing of the
parameters:
9 Eloquent::when() – no more if-else’s
Laravel Tips
www.techtic.com | info@techtic.com
Post belonging to Author and then Blade code:
10 BelongsTo Default Models
But what if the author is deleted, or isn’t set for some reason? You will get an error,
something like “property of non-object”.
Of course, you can prevent it like this:
But you can do it on Eloquent relationship level:
Laravel Tips
www.techtic.com | info@techtic.com
Guess you have this:
11 Order by Mutator
Now, you want to order by that full_name? This won’t work:
Solution is simple. We need to order the results after we get them.
Function name is different – it’s not orderBy, it’s sortBy.
Laravel Tips
www.techtic.com | info@techtic.com
What if you want to have User::all() always be ordered by name field? You can
assign a global scope. Let’s go back to the boot() method, which we mentioned
already above.
12 Default ordering in global scope
Laravel Tips
www.techtic.com | info@techtic.com
Add raw queries to our Eloquent statements. functions for that.
13 Raw query methods
www.techtic.com | info@techtic.com
Short one. Without deep explanations, here’s the best way to make a copy of
database entry:
14 Replicate: make a copy of a row
Laravel Tips
www.techtic.com | info@techtic.com
Still powerful – to process bigger datasets, you can chunk them into pieces.
Instead of:
15 Chunk() method for big tables
Do this:
Laravel Tips
www.techtic.com | info@techtic.com
This Artisan command:
16 Create additional things when creating a model
There are three useful flags to generate related files to the model?
 m will create a migration file
 c will create a controller
 r will indicate that controller should be resourceful
Laravel Tips
www.techtic.com | info@techtic.com
->save() method can accept parameters? As a result, we can tell it to
“ignore” updated_at default functionality to be filled with current timestamp.
See this:
17 Override updated_at when saving
Overriding default updated_at with our pre-defined one.
Laravel Tips
www.techtic.com | info@techtic.com
This code actually returns?
18 What is the result of an update()?
what would that $result contain? The answer is affected rows. So if you need to
check how many rows were affected, you don’t need to call anything else –
update() method will return this number for you.
Laravel Tips
www.techtic.com | info@techtic.com
and-or mix SQL query, like this:
19 Transform brackets into an Eloquent query
How to translate it into Eloquent? This is the wrong way:
The order will be incorrect. The right way is a little more complicated, using closure
functions as sub-queries:
Laravel Tips
www.techtic.com | info@techtic.com
pass an array of parameters to orWhere().
“Usual” way:
20 orWhere with multiple parameters
Do this:
Laravel Tips
www.techtic.com | info@techtic.com
Used onDelete('cascade'); on foreign keys in Laravel migrations, know about 'set
null'? This allows you to preserve models when their related model is deleted.
21 onDelete('set null')
Laravel Tips
www.techtic.com | info@techtic.com
when rolling back multiple foreign keys using array syntax didn't work.
22 dropForeign([]);
the array syntax on dropForeign is for dropping a foreign key using a shorthand
column name.
Laravel Tips
www.techtic.com | info@techtic.com
Here is drop foreign:
22 dropForeign([]);
Laravel Tips
www.techtic.com | info@techtic.com
22 dropForeign([]);
abstracted call to dropIndexCommand which looks like this:
Laravel Tips
www.techtic.com | info@techtic.com
23 Model Validation
This approach was inspired by the Elixir framework, Phoenix.
Laravel Tips
www.techtic.com | info@techtic.com
23 Model Validation
Laravel Tips
www.techtic.com | info@techtic.com
23 Model Validation
if your front-end only ends values that have changes for updating, you don't
want all fields marked as required.
Laravel Tips
www.techtic.com | info@techtic.com
Techtic Solutions, Inc. is one of the most trusted Laravel development company
with 10+ years of web development experience. Our team of experienced Laravel
developers are adept at building simple to the most complex website apps
seamlessly using Laravel PHP frameworks. Our clients swear by the codes we write
– they are simple, expressive and scalable. We help build sophisticated websites
that help maximize ROI for your business.
Get in touch if you are looking to hire Certified Laravel developers to deliver, secure,
high performance and faster web applications.
Our Services:
Custom Laravel Web Development
Laravel CMS development
Laravel Application Development
Laravel Ecommerce Development
Laravel Enterprise Solution
Laravel Customization
Laravel Theme/Template Design
Laravel Plugin Development
Laravel REST API Development
Laravel Support & Maintenance
www.techtic.com | info@techtic.com
Techtic Solutions is a 9+ years young IT firm offering solutions to various verticals
for branding, online marketing, web and mobile applications design &
development. With the vast experience of designing & developing 3000+ web
projects, 150+ mobile app development projects & 200+ digital marketing projects.
Our efficient team of 50+ engineers, marketers, designers & business analysts have
track record of offering the most intuitive, efficient & winning solutions to the
small, medium and large businesses & corporates to successfully address their
business models accuracy & enhancements.
Enabling businesses with technological advancements to improve the business
model, increase sales channels is the vision of Techtic Solutions. Our professionals
work in some of the most innovative areas like Ionic, Swift, iOS, Android, Magento
2.X, Laravel, Yii, AngularJS, CodeIgniter, WordPress and many other open source
technologies. Our efficient team management, quality control and willingness to
deliver the most innovative solutions to our customers are what set us apart from
other I.T. vendors.
About Techtic Solutions
Continued on Next Page
www.techtic.com | info@techtic.com
Techtic is an innovative technology agency with a cavalry of multi-talented and
pulsating professionals in quest of challenges to deliver quality digital products. We
use leading project development methodology, super efficient process and most
advanced tool chain.
About Techtic Solutions
Mobile App Development
React Native Development
Full Stack Development
Laravel Development
Node.JS Development
Angular Development
React JS Development
WorkPress Development
Magento Development
IOT Development
Digital Marketing
Travel
Social Networking
Life Style
Health & Fitness
Productivity
Business
Navigation
Entertainment
Advertising
Real Estate
Services Industries we serve
Contact Us
Visit us: https://www.techtic.com
Email: info@techtic.com
Phone: +1 201.793.8324
Source by: https://laravel-news.com/eloquent-tips-tricks

Best Laravel Eloquent Tips and Tricks

  • 1.
  • 2.
    www.techtic.com | info@techtic.com LaravelTips 1. Increments and Decrements 2. XorY methods 3. Model boot() method 4. Relationship with conditions and ordering 5. Model properties: timestamps, appends etc. 6. Find multiple entries 7. WhereX 8. Order by relationship 9. Eloquent::when() – no more if-else’s 10. BelongsTo Default Models 11. Order by Mutator 12. Default ordering in global scope 13. Raw query methods 14. Replicate: make a copy of a row 15. Chunk() method for big tables 16. Create additional things when creating a model 17. Override updated_at when saving 18. What is the result of an update()? 19. Transform brackets into an Eloquent query 20. orWhere with multiple parameters 21. onDelete('set null') 22. dropForeign([]); 23. Model Validation List of Laravel Tips
  • 3.
    www.techtic.com | info@techtic.com Insteadof this: 1. Increments and Decrements Do this: Also these will work: Laravel Tips
  • 4.
    www.techtic.com | info@techtic.com Eloquenthas quite a few functions that combine two methods, like “please do X, otherwise do Y”. Ex 1 – findOrFail(): Instead of: 2. XorY Methods Do this: Laravel Tips
  • 5.
    www.techtic.com | info@techtic.com Ex2 – firstOrCreate(): Instead of: 2. XorY Methods Do this: Laravel Tips
  • 6.
    www.techtic.com | info@techtic.com Thereis a magical place called boot() in an Eloquent model where you can override default behavior: 3. Model boot() method Probably one of the most popular examples is setting some field value at the moment of creating the model object. Laravel Tips
  • 7.
    www.techtic.com | info@techtic.com DefineRelationship: 4. Relationship with conditions and ordering Already add where or orderBy? For example, if you want a specific relationship for some type of users, also ordered by email, you can do this: Laravel Tips
  • 8.
    www.techtic.com | info@techtic.com Thereare a few “parameters” of an Eloquent model, in the form of properties of that class. The most popular ones are probably these: 5. Model properties: timestamps, appends etc. there’s more: Laravel Tips
  • 9.
    www.techtic.com | info@techtic.com find()Method 6. Find multiple entries Few people know about that it can accept multiple IDs as an array: Laravel Tips
  • 10.
    www.techtic.com | info@techtic.com There’san elegant way to turn this: 7. WhereX Do this: Also, there are some pre-defined methods in Eloquent, related to date/time: Laravel Tips
  • 11.
    www.techtic.com | info@techtic.com Separaterelationship for the latest post on the topic: 8. Order by Relationship And then, in our controller, we can do this “magic”: Laravel Tips
  • 12.
    www.techtic.com | info@techtic.com writeconditional queries with “if-else”, something like this: 9 Eloquent::when() – no more if-else’s there’s a better way – to use when(): Laravel Tips
  • 13.
    www.techtic.com | info@techtic.com Itmay not feel shorter or more elegant, but the most powerful is passing of the parameters: 9 Eloquent::when() – no more if-else’s Laravel Tips
  • 14.
    www.techtic.com | info@techtic.com Postbelonging to Author and then Blade code: 10 BelongsTo Default Models But what if the author is deleted, or isn’t set for some reason? You will get an error, something like “property of non-object”. Of course, you can prevent it like this: But you can do it on Eloquent relationship level: Laravel Tips
  • 15.
    www.techtic.com | info@techtic.com Guessyou have this: 11 Order by Mutator Now, you want to order by that full_name? This won’t work: Solution is simple. We need to order the results after we get them. Function name is different – it’s not orderBy, it’s sortBy. Laravel Tips
  • 16.
    www.techtic.com | info@techtic.com Whatif you want to have User::all() always be ordered by name field? You can assign a global scope. Let’s go back to the boot() method, which we mentioned already above. 12 Default ordering in global scope Laravel Tips
  • 17.
    www.techtic.com | info@techtic.com Addraw queries to our Eloquent statements. functions for that. 13 Raw query methods
  • 18.
    www.techtic.com | info@techtic.com Shortone. Without deep explanations, here’s the best way to make a copy of database entry: 14 Replicate: make a copy of a row Laravel Tips
  • 19.
    www.techtic.com | info@techtic.com Stillpowerful – to process bigger datasets, you can chunk them into pieces. Instead of: 15 Chunk() method for big tables Do this: Laravel Tips
  • 20.
    www.techtic.com | info@techtic.com ThisArtisan command: 16 Create additional things when creating a model There are three useful flags to generate related files to the model?  m will create a migration file  c will create a controller  r will indicate that controller should be resourceful Laravel Tips
  • 21.
    www.techtic.com | info@techtic.com ->save()method can accept parameters? As a result, we can tell it to “ignore” updated_at default functionality to be filled with current timestamp. See this: 17 Override updated_at when saving Overriding default updated_at with our pre-defined one. Laravel Tips
  • 22.
    www.techtic.com | info@techtic.com Thiscode actually returns? 18 What is the result of an update()? what would that $result contain? The answer is affected rows. So if you need to check how many rows were affected, you don’t need to call anything else – update() method will return this number for you. Laravel Tips
  • 23.
    www.techtic.com | info@techtic.com and-ormix SQL query, like this: 19 Transform brackets into an Eloquent query How to translate it into Eloquent? This is the wrong way: The order will be incorrect. The right way is a little more complicated, using closure functions as sub-queries: Laravel Tips
  • 24.
    www.techtic.com | info@techtic.com passan array of parameters to orWhere(). “Usual” way: 20 orWhere with multiple parameters Do this: Laravel Tips
  • 25.
    www.techtic.com | info@techtic.com UsedonDelete('cascade'); on foreign keys in Laravel migrations, know about 'set null'? This allows you to preserve models when their related model is deleted. 21 onDelete('set null') Laravel Tips
  • 26.
    www.techtic.com | info@techtic.com whenrolling back multiple foreign keys using array syntax didn't work. 22 dropForeign([]); the array syntax on dropForeign is for dropping a foreign key using a shorthand column name. Laravel Tips
  • 27.
    www.techtic.com | info@techtic.com Hereis drop foreign: 22 dropForeign([]); Laravel Tips
  • 28.
    www.techtic.com | info@techtic.com 22dropForeign([]); abstracted call to dropIndexCommand which looks like this: Laravel Tips
  • 29.
    www.techtic.com | info@techtic.com 23Model Validation This approach was inspired by the Elixir framework, Phoenix. Laravel Tips
  • 30.
    www.techtic.com | info@techtic.com 23Model Validation Laravel Tips
  • 31.
    www.techtic.com | info@techtic.com 23Model Validation if your front-end only ends values that have changes for updating, you don't want all fields marked as required. Laravel Tips
  • 32.
    www.techtic.com | info@techtic.com TechticSolutions, Inc. is one of the most trusted Laravel development company with 10+ years of web development experience. Our team of experienced Laravel developers are adept at building simple to the most complex website apps seamlessly using Laravel PHP frameworks. Our clients swear by the codes we write – they are simple, expressive and scalable. We help build sophisticated websites that help maximize ROI for your business. Get in touch if you are looking to hire Certified Laravel developers to deliver, secure, high performance and faster web applications. Our Services: Custom Laravel Web Development Laravel CMS development Laravel Application Development Laravel Ecommerce Development Laravel Enterprise Solution Laravel Customization Laravel Theme/Template Design Laravel Plugin Development Laravel REST API Development Laravel Support & Maintenance
  • 33.
    www.techtic.com | info@techtic.com TechticSolutions is a 9+ years young IT firm offering solutions to various verticals for branding, online marketing, web and mobile applications design & development. With the vast experience of designing & developing 3000+ web projects, 150+ mobile app development projects & 200+ digital marketing projects. Our efficient team of 50+ engineers, marketers, designers & business analysts have track record of offering the most intuitive, efficient & winning solutions to the small, medium and large businesses & corporates to successfully address their business models accuracy & enhancements. Enabling businesses with technological advancements to improve the business model, increase sales channels is the vision of Techtic Solutions. Our professionals work in some of the most innovative areas like Ionic, Swift, iOS, Android, Magento 2.X, Laravel, Yii, AngularJS, CodeIgniter, WordPress and many other open source technologies. Our efficient team management, quality control and willingness to deliver the most innovative solutions to our customers are what set us apart from other I.T. vendors. About Techtic Solutions Continued on Next Page
  • 34.
    www.techtic.com | info@techtic.com Techticis an innovative technology agency with a cavalry of multi-talented and pulsating professionals in quest of challenges to deliver quality digital products. We use leading project development methodology, super efficient process and most advanced tool chain. About Techtic Solutions Mobile App Development React Native Development Full Stack Development Laravel Development Node.JS Development Angular Development React JS Development WorkPress Development Magento Development IOT Development Digital Marketing Travel Social Networking Life Style Health & Fitness Productivity Business Navigation Entertainment Advertising Real Estate Services Industries we serve
  • 35.
    Contact Us Visit us:https://www.techtic.com Email: info@techtic.com Phone: +1 201.793.8324 Source by: https://laravel-news.com/eloquent-tips-tricks