Laravel Shortcuts: 5 Simple Functions to Speed Up Your Coding Workflow
Laravel is already a powerful PHP framework — but sometimes, the real magic lies in the little things. Small helper functions can make your code cleaner, shorter, and easier to maintain. In this article, we’ll go over 5 simple Laravel functions that can significantly speed up your development process.
1. first()
– Get the First Match, Quickly
If you’re only looking for a single record, don’t bother chaining ->get()->first()
. Just use first()
directly.
$user = User::where('email', 'user@example.com')->first();
🔍 Tip:
first()
retrieves only the first matched row—saving memory- Use
firstOrFail()
when you want Laravel to throw a 404 if nothing is found:
$user = User::where('email', 'user@example.com')->firstOrFail();
2. latest()
– Easily Get the Newest Record
Need the latest post or newest transaction? Laravel makes it simple with latest()
. By default, it uses the created_at
column.
$latestPost = Post::latest()->first();
🔍 Tip:
- You can sort by a different timestamp column:
$latestPost = Post::latest('published_at')->first();
3. pluck()
– Quickly Extract Column Values
Want to get a list of just names from a table? Use pluck()
to return a clean collection or array.
$names = User::pluck('name');
🔍 Tip:
- Use a second argument to set the key:
$users = User::pluck('name', 'id');
This gives you an associative array like [1 => 'John', 2 => 'Jane']
.
4. select()
– Optimize Queries by Fetching Only What You Need
Don’t load all columns if you only need a few. This is especially useful for APIs and performance tuning.
$users = User::select('id', 'name')->get();
🔍 Tip:
- You can rename columns too:
$users = User::select('id', 'name as full_name')->get();
5. with('profile:address,phone,user_id')
– Eager Load with Selected Columns
When eager loading relationships, you don’t have to pull all columns. You can limit what’s loaded for better performance.
$users = User::with('profile:address,phone,user_id')->get();
🔍 Tip:
- Don’t forget to include the foreign key (
user_id
) in the select, otherwise Laravel won't be able to map the relationship.
Final Thoughts
It’s the little things that often have the biggest impact. Using shortcuts like first()
, latest()
, pluck()
, select()
, and smart with()
usage helps keep your code clean and efficient.
If you’re building APIs, dashboards, or even internal tools with Laravel, mastering these functions can save you time and reduce bugs.