100 Essential Laravel Helper Functions with Examples

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

  1. auth() – Access logged-in user

$user = auth()->user();
  1. auth()->check() – Check if user is logged in

if(auth()->check()) { echo "Logged in"; }
  1. auth()->id() – Get current user ID

$userId = auth()->id();
  1. optional() – Safely access nullable object

$name = optional(auth()->user())->name;
  1. bcrypt() – Hash passwords

$hashed = bcrypt('secret');
  1. filled() – Check if value is not empty

if(filled(request('name'))) { echo 'Not empty'; }
  1. blank() – Check if value is empty

if(blank(request('email'))) { echo 'Empty'; }


2. URL & Routing Helpers

  1. url() – Get full URL
$url = url('profile');
  1. route() – Generate URL for named route
route('dashboard');
  1. secure_url() – HTTPS URL
secure_url('login');
  1. action() – URL for controller action
action([HomeController::class, 'index']);
  1. redirect() – Redirect to URL or route
return redirect()->route('home');
  1. back() – Redirect to previous page
return back()->with('status', 'Done!');
  1. response() – Return response instance
return response('Hello World', 200);
  1. abort() – Stop request with HTTP status
abort(403, 'Unauthorized');
  1. 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.'));

3. Request & Input Helpers

  1. request() – Get current request
$request = request();
  1. input() – Get request input
$name = request()->input('name');
  1. old() – Get previous form input
<input type="text" value="{{ old('name') }}">
  1. filled() – Check input is not empty
if(filled(request('email'))) { echo 'Email provided'; }
  1. blank() – Check input is empty
if(blank(request('email'))) { echo 'Email is blank'; }
  1. has() – Check if request has key
if(request()->has('name')) { echo 'Name exists'; }
  1. only() – Get only specific input keys
$data = request()->only(['name','email']);
  1. except() – Get all except certain keys
$data = request()->except(['password']);

4. Session & Cookie Helpers

  1. session() – Access session data
session(['role' => 'admin']);
  1. session()->get() – Get session value
$role = session()->get('role');
  1. session()->flash() – Flash message
session()->flash('message', 'Profile updated');
  1. cookie() – Create cookies
return cookie('key', 'value', 60);
  1. forget() – Remove session data
session()->forget('role');
  1. pull() – Get and remove session data
$role = session()->pull('role');

5. Array & Collection Helpers

  1. collect() – Create a collection

$collection = collect([1,2,3]);
  1. data_get() – Get nested array/object value

$value = data_get($array, 'user.name');
  1. array_get() – Get array value safely

$value = array_get($array, 'key');
  1. array_set() – Set value in array

array_set($array, 'user.name', 'Talha');
  1. array_merge() – Merge arrays

$result = array_merge([1,2], [3,4]);
  1. array_except() – Get array without keys

array_except($array, ['password']);
  1. array_only() – Get only certain keys

array_only($array, ['name','email']);
  1. array_first() – Get first item passing callback

array_first([1,2,3], fn($n)=> $n>1); // 2
  1. array_last() – Get last item passing callback

array_last([1,2,3], fn($n)=> $n<3); // 2
  1. array_sort() – Sort array

array_sort([3,1,2]); // [1,2,3]


6. String Helpers

  1. Str::slug() – Create URL-friendly string

Str::slug('Hello World'); // hello-world
  1. Str::limit() – Limit string length

Str::limit('This is a long text', 10); // This is a…
  1. Str::contains() – Check if string contains text

Str::contains('Laravel Framework', 'Laravel'); // true
  1. Str::startsWith() – Check start

Str::startsWith('Hello', 'He'); // true
  1. Str::endsWith() – Check end

Str::endsWith('Hello', 'lo'); // true
  1. Str::camel() – Convert string to camel case

Str::camel('hello_world'); // helloWorld
  1. Str::studly() – Convert to StudlyCase

Str::studly('hello_world'); // HelloWorld
  1. Str::snake() – Convert to snake_case

Str::snake('HelloWorld'); // hello_world
  1. Str::title() – Convert to title case

Str::title('hello world'); // Hello World
  1. Str::random() – Generate random string

Str::random(10); // 10 char random


7. Debugging Helpers

  1. dd() – Dump & die

dd($data);
  1. dump() – Dump without die

dump($data);
  1. logger() – Log messages

logger('User logged in');
  1. ray() – Debug with Ray (if installed)

ray($variable);
  1. report() – Report exception

report(new Exception('Error occurred'));


8. Security Helpers

  1. encrypt() – Encrypt data

$encrypted = encrypt('secret');
  1. decrypt() – Decrypt data

$decrypted = decrypt($encrypted);
  1. csrf_token() – Get CSRF token

<input type="hidden" name="_token" value="{{ csrf_token() }}">
  1. hash() – Create hash using driver

$hash = hash('sha256', 'password');
  1. password_verify() – Verify password hash

password_verify('secret', $hashedPassword);


9. View & Template Helpers

  1. view() – Return view

return view('welcome');
  1. asset() – URL for assets

<img src="{{ asset('images/logo.png') }}">
  1. mix() – Get versioned asset

<link href="{{ mix('css/app.css') }}" rel="stylesheet">
  1. __() – Translation

__('Welcome');
  1. trans() – Translation alternative

trans('messages.welcome');
  1. e() – Escape HTML

{{ e('<script>alert(1)</script>') }}
  1. old() – Retain old form input

<input type="text" value="{{ old('name') }}">
  1. csrf_field() – CSRF input field

{{ csrf_field() }}
  1. method_field() – Method spoofing

{{ method_field('PUT') }}
  1. action() – Form action URL

<form action="{{ action([HomeController::class, 'store']) }}">

10. Job & Queue Helpers

  1. dispatch() – Dispatch job

dispatch(new SendEmailJob());
  1. dispatch_now() – Dispatch immediately

dispatch_now(new SendEmailJob());
  1. dispatch_sync() – Dispatch synchronously

dispatch_sync(new SendEmailJob());
  1. queue() – Queue job on specific queue

SendEmailJob::dispatch()->onQueue('emails');
  1. delay() – Delay job execution

SendEmailJob::dispatch()->delay(now()->addMinutes(5));
  1. all() – Get all jobs in queue (Queue facade)

Queue::all();
  1. later() – Dispatch job after delay

SendEmailJob::dispatch()->later(now()->addSeconds(10));
  1. chain() – Chain multiple jobs

Job1::withChain([new Job2(), new Job3()])->dispatch();
  1. onQueue() – Specify queue

SendEmailJob::dispatch()->onQueue('notifications');
  1. onConnection() – Specify queue connection

SendEmailJob::dispatch()->onConnection('database');

11. File & Storage Helpers

  1. storage_path() – Get storage path

$path = storage_path('app/file.txt');
  1. public_path() – Get public folder path

$path = public_path('images/logo.png');
  1. base_path() – Get project base path

$path = base_path('routes/web.php');
  1. app_path() – Get app folder path

$path = app_path('Models/User.php');
  1. resource_path() – Get resources folder path

$path = resource_path('views/welcome.blade.php');
  1. storage_path() – Get storage folder path

$path = storage_path('logs/laravel.log');
  1. file_exists() – Check if file exists

if(file_exists(storage_path('logs/laravel.log'))) { echo 'Exists'; }
  1. unlink() – Delete a file

unlink(storage_path('logs/temp.log'));
  1. is_dir() – Check if directory exists

if(is_dir(storage_path('app'))) { echo 'Directory exists'; }
  1. mkdir() – Create directory

mkdir(storage_path('app/new_folder'));


12. Caching Helpers

  1. cache() – Access cache

cache(['key' => 'value'], 60); // Store for 60 minutes
  1. cache()->get() – Get cached value

$value = cache()->get('key');
  1. cache()->has() – Check cache key

if(cache()->has('key')) { echo 'Cached'; }
  1. cache()->forget() – Remove cached value

cache()->forget('key');
  1. cache()->remember() – Cache with callback

$value = cache()->remember('users', 60, function() { return User::all(); });
  1. cache()->pull() – Get and remove cache

$value = cache()->pull('key');
  1. cache()->increment() – Increment numeric value

cache()->increment('counter');
  1. cache()->decrement() – Decrement numeric value

cache()->decrement('counter');
  1. cache()->tags() – Tagged caching

cache()->tags(['users'])->put('key', 'value', 60);
  1. 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
By using these helpers, your code becomes cleaner, faster, and easier to maintain.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top