6 Quick & Easy Ways to Speed Up Your Laravel Website

Image for post
Image for post

Introduction

1. Only fetch the fields you need in your database queries

$users = User::all(); foreach($users as $user) {
// Do something here
}
$users = User::select(['id', 'first_name', 'last_name'])->get(); foreach($users as $user) {
// Do something here
}

2. Use eager loading wherever possible

$comments = Comment::all();foreach ($comments as $comment ) {
print_r($comment->author->name);
}
$comments = Comment::with('authors')->get();foreach ($comments as $comment ) {
print_r($comment->author->name);
}

3. Get rid of any unneeded or unwanted packages

4. Cache, cache, cache!

Route caching

php artisan route:cache
php artisan route:clear

Config caching

php artisan config:cache
php artisan config:clear

Caching queries and values

$users = DB::table('users')->get();
$users = Cache::remember('users', 120, function () { 
return DB::table('users')->get();
});

5. Use the latest version of PHP

6. Make use of the queues

class ContactController extends Controller
{
/**
* Store a new podcast.
*
* @param Request $request
* @return JsonResponse
*/
public function store(ContactFormRequest $request)
{
$request->storeContactFormDetails();
Mail::to('mail@ashallendesign.co.uk')->send(new ContactFormSubmission);

return response()->json(['success' => true]);
}
}
class ContactController extends Controller
{
/**
* Store a new podcast.
*
* @param Request $request
* @return JsonResponse
*/
public function store(ContactFormRequest $request)
{
$request->storeContactFormDetails();
dispatch(function () {
Mail::to('mail@ashallendesign.co.uk')->send(new ContactFormSubmission);
})->afterResponse();
return response()->json(['success' => true]);
}
}

Need Any Help?

Written by

I’m a Laravel web developer based in the UK. I specialise in building websites and systems for small businesses to help them grow and increase their sales.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store