100 Essential Laravel Helper Functions with Examples
Laravel provides many built-in helper functions that make coding faster, cleaner, and more readable. Here’s a comprehensive list of 100 Laravel helpers with basic usage examples.
1. Authentication & User Helpers
-
auth()
– Access logged-in user
$user = auth()->user();
-
auth()->check()
– Check if user is logged in
if(auth()->check()) { echo "Logged in"; }
-
auth()->id()
– Get current user ID
$userId = auth()->id();
-
optional()
– Safely access nullable object
$name = optional(auth()->user())->name;
-
bcrypt()
– Hash passwords
$hashed = bcrypt('secret');
-
filled()
– Check if value is not empty
if(filled(request('name'))) { echo 'Not empty'; }
-
blank()
– Check if value is empty
if(blank(request('email'))) { echo 'Empty'; }
2. URL & Routing Helpers
-
url()
– Get full URL
$url = url('profile');
-
route()
– Generate URL for named route
route('dashboard');
-
secure_url()
– HTTPS URL
secure_url('login');
-
action()
– URL for controller action
action([HomeController::class, 'index']);
-
redirect()
– Redirect to URL or route
return redirect()->route('home');
-
back()
– Redirect to previous page
return back()->with('status', 'Done!');
-
response()
– Return response instance
return response('Hello World', 200);
-
abort()
– Stop request with HTTP status
abort(403, 'Unauthorized');
-
throw_if()
/throw_unless()
– Conditional exceptions
throw_if($user->isAdmin(), new Exception('Admin cannot perform this action.'));
throw_unless($user->isActive(), new Exception('User is not active.'));
throw_unless($user->isActive(), new Exception('User is not active.'));
3. Request & Input Helpers
-
request()
– Get current request
$request = request();
-
input()
– Get request input
$name = request()->input('name');
-
old()
– Get previous form input
<input type="text" value="{{ old('name') }}">
-
filled()
– Check input is not empty
if(filled(request('email'))) { echo 'Email provided'; }
-
blank()
– Check input is empty
if(blank(request('email'))) { echo 'Email is blank'; }
-
has()
– Check if request has key
if(request()->has('name')) { echo 'Name exists'; }
-
only()
– Get only specific input keys
$data = request()->only(['name','email']);
-
except()
– Get all except certain keys
$data = request()->except(['password']);
4. Session & Cookie Helpers
-
session()
– Access session data
session(['role' => 'admin']);
-
session()->get()
– Get session value
$role = session()->get('role');
-
session()->flash()
– Flash message
session()->flash('message', 'Profile updated');
-
cookie()
– Create cookies
return cookie('key', 'value', 60);
-
forget()
– Remove session data
session()->forget('role');
-
pull()
– Get and remove session data
$role = session()->pull('role');
5. Array & Collection Helpers
-
collect()
– Create a collection
$collection = collect([1,2,3]);
-
data_get()
– Get nested array/object value
$value = data_get($array, 'user.name');
-
array_get()
– Get array value safely
$value = array_get($array, 'key');
-
array_set()
– Set value in array
array_set($array, 'user.name', 'Talha');
-
array_merge()
– Merge arrays
$result = array_merge([1,2], [3,4]);
-
array_except()
– Get array without keys
array_except($array, ['password']);
-
array_only()
– Get only certain keys
array_only($array, ['name','email']);
-
array_first()
– Get first item passing callback
array_first([1,2,3], fn($n)=> $n>1); // 2
-
array_last()
– Get last item passing callback
array_last([1,2,3], fn($n)=> $n<3); // 2
-
array_sort()
– Sort array
array_sort([3,1,2]); // [1,2,3]
6. String Helpers
-
Str::slug()
– Create URL-friendly string
Str::slug('Hello World'); // hello-world
-
Str::limit()
– Limit string length
Str::limit('This is a long text', 10); // This is a…
-
Str::contains()
– Check if string contains text
Str::contains('Laravel Framework', 'Laravel'); // true
-
Str::startsWith()
– Check start
Str::startsWith('Hello', 'He'); // true
-
Str::endsWith()
– Check end
Str::endsWith('Hello', 'lo'); // true
-
Str::camel()
– Convert string to camel case
Str::camel('hello_world'); // helloWorld
-
Str::studly()
– Convert to StudlyCase
Str::studly('hello_world'); // HelloWorld
-
Str::snake()
– Convert to snake_case
Str::snake('HelloWorld'); // hello_world
-
Str::title()
– Convert to title case
Str::title('hello world'); // Hello World
-
Str::random()
– Generate random string
Str::random(10); // 10 char random
7. Debugging Helpers
-
dd()
– Dump & die
dd($data);
-
dump()
– Dump without die
dump($data);
-
logger()
– Log messages
logger('User logged in');
-
ray()
– Debug with Ray (if installed)
ray($variable);
-
report()
– Report exception
report(new Exception('Error occurred'));
8. Security Helpers
-
encrypt()
– Encrypt data
$encrypted = encrypt('secret');
-
decrypt()
– Decrypt data
$decrypted = decrypt($encrypted);
-
csrf_token()
– Get CSRF token
<input type="hidden" name="_token" value="{{ csrf_token() }}">
-
hash()
– Create hash using driver
$hash = hash('sha256', 'password');
-
password_verify()
– Verify password hash
password_verify('secret', $hashedPassword);
9. View & Template Helpers
-
view()
– Return view
return view('welcome');
-
asset()
– URL for assets
<img src="{{ asset('images/logo.png') }}">
-
mix()
– Get versioned asset
<link href="{{ mix('css/app.css') }}" rel="stylesheet">
-
__()
– Translation
__('Welcome');
-
trans()
– Translation alternative
trans('messages.welcome');
-
e()
– Escape HTML
{{ e('<script>alert(1)</script>') }}
-
old()
– Retain old form input
<input type="text" value="{{ old('name') }}">
-
csrf_field()
– CSRF input field
{{ csrf_field() }}
-
method_field()
– Method spoofing
{{ method_field('PUT') }}
-
action()
– Form action URL
<form action="{{ action([HomeController::class, 'store']) }}">
10. Job & Queue Helpers
-
dispatch()
– Dispatch job
dispatch(new SendEmailJob());
-
dispatch_now()
– Dispatch immediately
dispatch_now(new SendEmailJob());
-
dispatch_sync()
– Dispatch synchronously
dispatch_sync(new SendEmailJob());
-
queue()
– Queue job on specific queue
SendEmailJob::dispatch()->onQueue('emails');
-
delay()
– Delay job execution
SendEmailJob::dispatch()->delay(now()->addMinutes(5));
-
all()
– Get all jobs in queue (Queue facade)
Queue::all();
-
later()
– Dispatch job after delay
SendEmailJob::dispatch()->later(now()->addSeconds(10));
-
chain()
– Chain multiple jobs
Job1::withChain([new Job2(), new Job3()])->dispatch();
-
onQueue()
– Specify queue
SendEmailJob::dispatch()->onQueue('notifications');
-
onConnection()
– Specify queue connection
SendEmailJob::dispatch()->onConnection('database');
11. File & Storage Helpers
-
storage_path()
– Get storage path
$path = storage_path('app/file.txt');
-
public_path()
– Get public folder path
$path = public_path('images/logo.png');
-
base_path()
– Get project base path
$path = base_path('routes/web.php');
-
app_path()
– Get app folder path
$path = app_path('Models/User.php');
-
resource_path()
– Get resources folder path
$path = resource_path('views/welcome.blade.php');
-
storage_path()
– Get storage folder path
$path = storage_path('logs/laravel.log');
-
file_exists()
– Check if file exists
if(file_exists(storage_path('logs/laravel.log'))) { echo 'Exists'; }
-
unlink()
– Delete a file
unlink(storage_path('logs/temp.log'));
-
is_dir()
– Check if directory exists
if(is_dir(storage_path('app'))) { echo 'Directory exists'; }
-
mkdir()
– Create directory
mkdir(storage_path('app/new_folder'));
12. Caching Helpers
-
cache()
– Access cache
cache(['key' => 'value'], 60); // Store for 60 minutes
-
cache()->get()
– Get cached value
$value = cache()->get('key');
-
cache()->has()
– Check cache key
if(cache()->has('key')) { echo 'Cached'; }
-
cache()->forget()
– Remove cached value
cache()->forget('key');
-
cache()->remember()
– Cache with callback
$value = cache()->remember('users', 60, function() { return User::all(); });
-
cache()->pull()
– Get and remove cache
$value = cache()->pull('key');
-
cache()->increment()
– Increment numeric value
cache()->increment('counter');
-
cache()->decrement()
– Decrement numeric value
cache()->decrement('counter');
-
cache()->tags()
– Tagged caching
cache()->tags(['users'])->put('key', 'value', 60);
-
cache()->flush()
– Clear cache
cache()->flush();
Conclusion
Laravel provides hundreds of helper functions, and the 100 listed above are the most commonly used in daily development. They cover:
-
Authentication & user management
-
URL, routing & request handling
-
Sessions, cookies & caching
-
Collections & arrays
-
Strings & debugging
-
Security & encryption
-
Views, templates & assets
-
File management & storage
-
Jobs & queues