SlideShare a Scribd company logo
1 of 35
Download to read offline
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

More Related Content

What's hot

Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.SWAAM Tech
 
Integration with dropbox
Integration with dropboxIntegration with dropbox
Integration with dropboxSon Nguyen
 
Integrate with facebook connector
Integrate with facebook connectorIntegrate with facebook connector
Integrate with facebook connectorSon Nguyen
 
Part 1 implementing a simple_web_service
Part 1 implementing a simple_web_servicePart 1 implementing a simple_web_service
Part 1 implementing a simple_web_servicekrishmdkk
 
Deploy with maven
Deploy with mavenDeploy with maven
Deploy with mavenSon Nguyen
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran TochAdil Jafri
 
Expose web service
Expose web serviceExpose web service
Expose web serviceSon Nguyen
 
Ruby on rails integration testing with minitest and capybara
Ruby on rails integration testing with minitest and capybaraRuby on rails integration testing with minitest and capybara
Ruby on rails integration testing with minitest and capybaraAndolasoft Inc
 
Integrate to retrieve data microsoft azure
Integrate to retrieve data microsoft azureIntegrate to retrieve data microsoft azure
Integrate to retrieve data microsoft azureSon Nguyen
 
Serverless and Kubernetes Workshop on IBM Cloud
Serverless and Kubernetes Workshop on IBM CloudServerless and Kubernetes Workshop on IBM Cloud
Serverless and Kubernetes Workshop on IBM CloudAnsgar Schmidt
 
Cis407 a ilab 5 web application development devry university
Cis407 a ilab 5 web application development devry universityCis407 a ilab 5 web application development devry university
Cis407 a ilab 5 web application development devry universitylhkslkdh89009
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performancerudib
 
Enterprising JavaFX
Enterprising JavaFXEnterprising JavaFX
Enterprising JavaFXRichard Bair
 
Test Coverage for Your WP REST API Project
Test Coverage for Your WP REST API ProjectTest Coverage for Your WP REST API Project
Test Coverage for Your WP REST API ProjectPantheon
 
Laravel installation
Laravel installationLaravel installation
Laravel installationphptpoint0123
 

What's hot (20)

Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.
 
Integration with dropbox
Integration with dropboxIntegration with dropbox
Integration with dropbox
 
Integrate with facebook connector
Integrate with facebook connectorIntegrate with facebook connector
Integrate with facebook connector
 
Sqlite3 databases
Sqlite3 databasesSqlite3 databases
Sqlite3 databases
 
Part 1 implementing a simple_web_service
Part 1 implementing a simple_web_servicePart 1 implementing a simple_web_service
Part 1 implementing a simple_web_service
 
Php
PhpPhp
Php
 
Anypoint lessons
Anypoint lessonsAnypoint lessons
Anypoint lessons
 
Deploy with maven
Deploy with mavenDeploy with maven
Deploy with maven
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Asp net-mvc-3 tier
Asp net-mvc-3 tierAsp net-mvc-3 tier
Asp net-mvc-3 tier
 
Asp.Net Tutorials
Asp.Net TutorialsAsp.Net Tutorials
Asp.Net Tutorials
 
Expose web service
Expose web serviceExpose web service
Expose web service
 
Ruby on rails integration testing with minitest and capybara
Ruby on rails integration testing with minitest and capybaraRuby on rails integration testing with minitest and capybara
Ruby on rails integration testing with minitest and capybara
 
Integrate to retrieve data microsoft azure
Integrate to retrieve data microsoft azureIntegrate to retrieve data microsoft azure
Integrate to retrieve data microsoft azure
 
Serverless and Kubernetes Workshop on IBM Cloud
Serverless and Kubernetes Workshop on IBM CloudServerless and Kubernetes Workshop on IBM Cloud
Serverless and Kubernetes Workshop on IBM Cloud
 
Cis407 a ilab 5 web application development devry university
Cis407 a ilab 5 web application development devry universityCis407 a ilab 5 web application development devry university
Cis407 a ilab 5 web application development devry university
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performance
 
Enterprising JavaFX
Enterprising JavaFXEnterprising JavaFX
Enterprising JavaFX
 
Test Coverage for Your WP REST API Project
Test Coverage for Your WP REST API ProjectTest Coverage for Your WP REST API Project
Test Coverage for Your WP REST API Project
 
Laravel installation
Laravel installationLaravel installation
Laravel installation
 

Similar to Best Laravel Eloquent Tips and Tricks

New Features of Laravel 9​ - Storeemart a Best Laravel Ecommerce Platform
New Features of Laravel 9​ - Storeemart a Best Laravel Ecommerce PlatformNew Features of Laravel 9​ - Storeemart a Best Laravel Ecommerce Platform
New Features of Laravel 9​ - Storeemart a Best Laravel Ecommerce PlatformStoreeMart2
 
What's new in laravel 9 a complete guide for laravel website development
What's new in laravel 9  a complete guide for laravel website developmentWhat's new in laravel 9  a complete guide for laravel website development
What's new in laravel 9 a complete guide for laravel website developmentMoon Technolabs Pvt. Ltd.
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsMike Wilcox
 
Introduction To Ruby On Rails
Introduction To Ruby On RailsIntroduction To Ruby On Rails
Introduction To Ruby On RailsSteve Keener
 
Crash Course HTML/Rails Slides
Crash Course HTML/Rails SlidesCrash Course HTML/Rails Slides
Crash Course HTML/Rails SlidesUdita Plaha
 
A introduction to Laravel framework
A introduction to Laravel frameworkA introduction to Laravel framework
A introduction to Laravel frameworkPhu Luong Trong
 
Backend Development Bootcamp - Node [Online & Offline] In Bangla
Backend Development Bootcamp - Node [Online & Offline] In BanglaBackend Development Bootcamp - Node [Online & Offline] In Bangla
Backend Development Bootcamp - Node [Online & Offline] In BanglaStack Learner
 
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdfcNguyn506241
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersVineet Kumar Saini
 
Principles of MVC for Rails Developers
Principles of MVC for Rails DevelopersPrinciples of MVC for Rails Developers
Principles of MVC for Rails DevelopersEdureka!
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddSrinivasa GV
 
Intro to .NET for Government Developers
Intro to .NET for Government DevelopersIntro to .NET for Government Developers
Intro to .NET for Government DevelopersFrank La Vigne
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applicationshchen1
 
Hidden things uncovered about laravel development
Hidden things uncovered about laravel developmentHidden things uncovered about laravel development
Hidden things uncovered about laravel developmentKaty Slemon
 

Similar to Best Laravel Eloquent Tips and Tricks (20)

New Features of Laravel 9​ - Storeemart a Best Laravel Ecommerce Platform
New Features of Laravel 9​ - Storeemart a Best Laravel Ecommerce PlatformNew Features of Laravel 9​ - Storeemart a Best Laravel Ecommerce Platform
New Features of Laravel 9​ - Storeemart a Best Laravel Ecommerce Platform
 
ASP .NET MVC - best practices
ASP .NET MVC - best practicesASP .NET MVC - best practices
ASP .NET MVC - best practices
 
What's new in laravel 9 a complete guide for laravel website development
What's new in laravel 9  a complete guide for laravel website developmentWhat's new in laravel 9  a complete guide for laravel website development
What's new in laravel 9 a complete guide for laravel website development
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatterns
 
Laravel Tutorial PPT
Laravel Tutorial PPTLaravel Tutorial PPT
Laravel Tutorial PPT
 
Introduction To Ruby On Rails
Introduction To Ruby On RailsIntroduction To Ruby On Rails
Introduction To Ruby On Rails
 
CG_CS25010_Lecture
CG_CS25010_LectureCG_CS25010_Lecture
CG_CS25010_Lecture
 
Article laravel 8
Article laravel 8Article laravel 8
Article laravel 8
 
Crash Course HTML/Rails Slides
Crash Course HTML/Rails SlidesCrash Course HTML/Rails Slides
Crash Course HTML/Rails Slides
 
A introduction to Laravel framework
A introduction to Laravel frameworkA introduction to Laravel framework
A introduction to Laravel framework
 
Backend Development Bootcamp - Node [Online & Offline] In Bangla
Backend Development Bootcamp - Node [Online & Offline] In BanglaBackend Development Bootcamp - Node [Online & Offline] In Bangla
Backend Development Bootcamp - Node [Online & Offline] In Bangla
 
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and Answers
 
Principles of MVC for Rails Developers
Principles of MVC for Rails DevelopersPrinciples of MVC for Rails Developers
Principles of MVC for Rails Developers
 
A4 from rad to mvc
A4 from rad to mvcA4 from rad to mvc
A4 from rad to mvc
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
 
Intro to .NET for Government Developers
Intro to .NET for Government DevelopersIntro to .NET for Government Developers
Intro to .NET for Government Developers
 
Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
 
Hidden things uncovered about laravel development
Hidden things uncovered about laravel developmentHidden things uncovered about laravel development
Hidden things uncovered about laravel development
 

More from Techtic Solutions

The Top 5 Benefits of Engaging a Dedicated Development Team for Your Upcoming...
The Top 5 Benefits of Engaging a Dedicated Development Team for Your Upcoming...The Top 5 Benefits of Engaging a Dedicated Development Team for Your Upcoming...
The Top 5 Benefits of Engaging a Dedicated Development Team for Your Upcoming...Techtic Solutions
 
Top 5 Vital Trends in UX and Product Design for Emerging FinTech Ventures
Top 5 Vital Trends in UX and Product Design for Emerging FinTech VenturesTop 5 Vital Trends in UX and Product Design for Emerging FinTech Ventures
Top 5 Vital Trends in UX and Product Design for Emerging FinTech VenturesTechtic Solutions
 
7 Essential Tips for Building a Successful Shopify Store - Insights from D2C ...
7 Essential Tips for Building a Successful Shopify Store - Insights from D2C ...7 Essential Tips for Building a Successful Shopify Store - Insights from D2C ...
7 Essential Tips for Building a Successful Shopify Store - Insights from D2C ...Techtic Solutions
 
Shopify vs WooCommerce eCommerce Platform Migration 2023.pptx
Shopify vs WooCommerce eCommerce Platform Migration 2023.pptxShopify vs WooCommerce eCommerce Platform Migration 2023.pptx
Shopify vs WooCommerce eCommerce Platform Migration 2023.pptxTechtic Solutions
 
Building MVP with Team Augmentation
Building MVP with Team AugmentationBuilding MVP with Team Augmentation
Building MVP with Team AugmentationTechtic Solutions
 
Powerful features that drive success for health and wellness ecommerce stores
Powerful features that drive success for health and wellness ecommerce storesPowerful features that drive success for health and wellness ecommerce stores
Powerful features that drive success for health and wellness ecommerce storesTechtic Solutions
 
Top 10 Marketing Automation Tools for eCommerce Stores.pptx
Top 10 Marketing Automation Tools for eCommerce Stores.pptxTop 10 Marketing Automation Tools for eCommerce Stores.pptx
Top 10 Marketing Automation Tools for eCommerce Stores.pptxTechtic Solutions
 
Why Having the Right Tech Stack is Critical for eCommerce?
Why Having the Right Tech Stack is Critical for eCommerce?Why Having the Right Tech Stack is Critical for eCommerce?
Why Having the Right Tech Stack is Critical for eCommerce?Techtic Solutions
 
8 Factors will Drive Fintech Growth in 2021
8 Factors will Drive Fintech Growth in 20218 Factors will Drive Fintech Growth in 2021
8 Factors will Drive Fintech Growth in 2021Techtic Solutions
 
Top 12 Advantages of Laravel Framework
Top 12 Advantages of Laravel FrameworkTop 12 Advantages of Laravel Framework
Top 12 Advantages of Laravel FrameworkTechtic Solutions
 
10 Common Applications of Artificial Intelligence in Healthcare
10 Common Applications of Artificial Intelligence in Healthcare10 Common Applications of Artificial Intelligence in Healthcare
10 Common Applications of Artificial Intelligence in HealthcareTechtic Solutions
 
What security measures do we take when working remotely?
What security measures do we take when working remotely?What security measures do we take when working remotely?
What security measures do we take when working remotely?Techtic Solutions
 
How Techtic Implements Seamless Project Management?
How Techtic Implements Seamless Project Management?How Techtic Implements Seamless Project Management?
How Techtic Implements Seamless Project Management?Techtic Solutions
 
Facts of Software Development
Facts of Software DevelopmentFacts of Software Development
Facts of Software DevelopmentTechtic Solutions
 
How to Integrate Mobile App with Website?
How to Integrate Mobile App with Website?How to Integrate Mobile App with Website?
How to Integrate Mobile App with Website?Techtic Solutions
 
10 On-demand App Statistics to look at During COVID-19
10 On-demand App Statistics to look at During COVID-1910 On-demand App Statistics to look at During COVID-19
10 On-demand App Statistics to look at During COVID-19Techtic Solutions
 
What’s new in Laravel 7.8?
What’s new in Laravel 7.8?What’s new in Laravel 7.8?
What’s new in Laravel 7.8?Techtic Solutions
 
Laravel Vs Django, Which Backend Framework is better?
Laravel Vs Django, Which Backend Framework is better?Laravel Vs Django, Which Backend Framework is better?
Laravel Vs Django, Which Backend Framework is better?Techtic Solutions
 
Differences between Mobile Apps and Websites – Techtic Solutions
Differences between Mobile Apps and Websites – Techtic SolutionsDifferences between Mobile Apps and Websites – Techtic Solutions
Differences between Mobile Apps and Websites – Techtic SolutionsTechtic Solutions
 
How to Integrate Mobile App with Website? – Techtic Solutions
How to Integrate Mobile App with Website? – Techtic SolutionsHow to Integrate Mobile App with Website? – Techtic Solutions
How to Integrate Mobile App with Website? – Techtic SolutionsTechtic Solutions
 

More from Techtic Solutions (20)

The Top 5 Benefits of Engaging a Dedicated Development Team for Your Upcoming...
The Top 5 Benefits of Engaging a Dedicated Development Team for Your Upcoming...The Top 5 Benefits of Engaging a Dedicated Development Team for Your Upcoming...
The Top 5 Benefits of Engaging a Dedicated Development Team for Your Upcoming...
 
Top 5 Vital Trends in UX and Product Design for Emerging FinTech Ventures
Top 5 Vital Trends in UX and Product Design for Emerging FinTech VenturesTop 5 Vital Trends in UX and Product Design for Emerging FinTech Ventures
Top 5 Vital Trends in UX and Product Design for Emerging FinTech Ventures
 
7 Essential Tips for Building a Successful Shopify Store - Insights from D2C ...
7 Essential Tips for Building a Successful Shopify Store - Insights from D2C ...7 Essential Tips for Building a Successful Shopify Store - Insights from D2C ...
7 Essential Tips for Building a Successful Shopify Store - Insights from D2C ...
 
Shopify vs WooCommerce eCommerce Platform Migration 2023.pptx
Shopify vs WooCommerce eCommerce Platform Migration 2023.pptxShopify vs WooCommerce eCommerce Platform Migration 2023.pptx
Shopify vs WooCommerce eCommerce Platform Migration 2023.pptx
 
Building MVP with Team Augmentation
Building MVP with Team AugmentationBuilding MVP with Team Augmentation
Building MVP with Team Augmentation
 
Powerful features that drive success for health and wellness ecommerce stores
Powerful features that drive success for health and wellness ecommerce storesPowerful features that drive success for health and wellness ecommerce stores
Powerful features that drive success for health and wellness ecommerce stores
 
Top 10 Marketing Automation Tools for eCommerce Stores.pptx
Top 10 Marketing Automation Tools for eCommerce Stores.pptxTop 10 Marketing Automation Tools for eCommerce Stores.pptx
Top 10 Marketing Automation Tools for eCommerce Stores.pptx
 
Why Having the Right Tech Stack is Critical for eCommerce?
Why Having the Right Tech Stack is Critical for eCommerce?Why Having the Right Tech Stack is Critical for eCommerce?
Why Having the Right Tech Stack is Critical for eCommerce?
 
8 Factors will Drive Fintech Growth in 2021
8 Factors will Drive Fintech Growth in 20218 Factors will Drive Fintech Growth in 2021
8 Factors will Drive Fintech Growth in 2021
 
Top 12 Advantages of Laravel Framework
Top 12 Advantages of Laravel FrameworkTop 12 Advantages of Laravel Framework
Top 12 Advantages of Laravel Framework
 
10 Common Applications of Artificial Intelligence in Healthcare
10 Common Applications of Artificial Intelligence in Healthcare10 Common Applications of Artificial Intelligence in Healthcare
10 Common Applications of Artificial Intelligence in Healthcare
 
What security measures do we take when working remotely?
What security measures do we take when working remotely?What security measures do we take when working remotely?
What security measures do we take when working remotely?
 
How Techtic Implements Seamless Project Management?
How Techtic Implements Seamless Project Management?How Techtic Implements Seamless Project Management?
How Techtic Implements Seamless Project Management?
 
Facts of Software Development
Facts of Software DevelopmentFacts of Software Development
Facts of Software Development
 
How to Integrate Mobile App with Website?
How to Integrate Mobile App with Website?How to Integrate Mobile App with Website?
How to Integrate Mobile App with Website?
 
10 On-demand App Statistics to look at During COVID-19
10 On-demand App Statistics to look at During COVID-1910 On-demand App Statistics to look at During COVID-19
10 On-demand App Statistics to look at During COVID-19
 
What’s new in Laravel 7.8?
What’s new in Laravel 7.8?What’s new in Laravel 7.8?
What’s new in Laravel 7.8?
 
Laravel Vs Django, Which Backend Framework is better?
Laravel Vs Django, Which Backend Framework is better?Laravel Vs Django, Which Backend Framework is better?
Laravel Vs Django, Which Backend Framework is better?
 
Differences between Mobile Apps and Websites – Techtic Solutions
Differences between Mobile Apps and Websites – Techtic SolutionsDifferences between Mobile Apps and Websites – Techtic Solutions
Differences between Mobile Apps and Websites – Techtic Solutions
 
How to Integrate Mobile App with Website? – Techtic Solutions
How to Integrate Mobile App with Website? – Techtic SolutionsHow to Integrate Mobile App with Website? – Techtic Solutions
How to Integrate Mobile App with Website? – Techtic Solutions
 

Recently uploaded

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Recently uploaded (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Best Laravel Eloquent Tips and Tricks

  • 2. 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
  • 3. www.techtic.com | info@techtic.com Instead of this: 1. Increments and Decrements Do this: Also these will work: Laravel Tips
  • 4. 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
  • 5. www.techtic.com | info@techtic.com Ex 2 – firstOrCreate(): Instead of: 2. XorY Methods Do this: Laravel Tips
  • 6. 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
  • 7. 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
  • 8. 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
  • 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’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
  • 11. 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
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. www.techtic.com | info@techtic.com Add raw queries to our Eloquent statements. functions for that. 13 Raw query methods
  • 18. 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
  • 19. 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
  • 20. 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
  • 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 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
  • 23. 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
  • 24. www.techtic.com | info@techtic.com pass an array of parameters to orWhere(). “Usual” way: 20 orWhere with multiple parameters Do this: Laravel Tips
  • 25. 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
  • 26. 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
  • 27. www.techtic.com | info@techtic.com Here is drop foreign: 22 dropForeign([]); Laravel Tips
  • 28. www.techtic.com | info@techtic.com 22 dropForeign([]); abstracted call to dropIndexCommand which looks like this: Laravel Tips
  • 29. www.techtic.com | info@techtic.com 23 Model Validation This approach was inspired by the Elixir framework, Phoenix. Laravel Tips
  • 30. www.techtic.com | info@techtic.com 23 Model Validation Laravel Tips
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. 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
  • 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