Sessions and Caching

πŸ“˜ Laravel πŸ‘ 42 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

Sessions and caching in Laravel are used to store data temporarily to improve user experience and application performance. Sessions keep user-specific data across requests, while caching stores frequently accessed data to reduce processing time and database queries.


1. Sessions in Laravel

What Are Sessions?

Sessions allow you to store user data (such as login status or preferences) across multiple requests.

Common uses:

  • Authentication state

  • Flash messages

  • Shopping carts


Session Configuration

Session settings are defined in:

config/session.php

Session drivers include:

  • file (default)

  • cookie

  • database

  • redis

  • memcached

Driver is set in .env:

SESSION_DRIVER=file

Storing Data in Sessions

session(['username' => 'John']);

Retrieve session data:

$username = session('username');

Removing Session Data

session()->forget('username'); session()->flush();

Flash Data (Temporary Data)

Flash data exists for only one request:

session()->flash('success', 'Data saved successfully!');

Display in Blade:

@if(session('success')) {{ session('success') }} @endif

Session via Request Object

$request->session()->put('cart', $cart);

2. Caching in Laravel

What Is Caching?

Caching stores frequently used data to speed up application performance and reduce database load.


Cache Configuration

Cache settings are stored in:

config/cache.php

Cache drivers include:

  • file

  • database

  • redis

  • memcached

  • array

Set in .env:

CACHE_DRIVER=file

Storing Data in Cache

use Illuminate\Support\Facades\Cache; Cache::put('key', 'value', 600);

Retrieve data:

$value = Cache::get('key');

Cache with Expiration

Cache::put('users', $users, now()->addMinutes(10));

Cache Forever

Cache::forever('settings', $settings);

Removing Cache

Cache::forget('key'); Cache::flush();

Cache Helper Method

$users = Cache::remember('users', 600, function () { return User::all(); });

3. Session vs Cache

FeatureSessionCache
ScopeUser-specificApplication-wide
LifetimeShort-termConfigurable
Use CaseLogin, flash messagesPerformance optimization

4. Clearing Session and Cache

php artisan cache:clear php artisan session:clear

Conclusion

Laravel’s session and caching systems provide efficient ways to manage temporary data and optimize performance. By using the right drivers and methods, developers can build fast, scalable, and user-friendly applications.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes