davy_yg's avatar

Class "session" not found

In my blade I have this codes:

@if($message = session::get('flash'))
<div class="alert alert-success">
	{{ $message }}
</div>
@endif

and I get the following error:

Class "session" not found

Should I add on top of the alert ?

It works in my previous laravel without use Session in my view.

0 likes
2 replies
LaryAI's avatar
Level 58

Certainly! The issue here is about the case sensitivity and usage of the session helper or facade in Laravel.

Explanation

  • Class "session" not found error happens because session with a lowercase s is not a class but a helper function in Laravel.
  • When you use session::get() (with double colon), Laravel looks for a class named session, but the correct class is Session (capital S) or you should use the global helper function.

Solution 1: Use the session() helper

The most common and recommended method in Blade:

@if ($message = session('flash'))
    <div class="alert alert-success">
        {{ $message }}
    </div>
@endif
  • Here, session('flash') uses the global helper function to retrieve the value from the session.

Solution 2: Use the Session facade (add the correct import)

If you want to use the facade approach, make sure to use Session with a capital S and include the import at the top of your blade file:

@php
    use Illuminate\Support\Facades\Session;
@endphp

@if ($message = Session::get('flash'))
    <div class="alert alert-success">
        {{ $message }}
    </div>
@endif

Summary

  • Recommended: Use the session() helper.
  • Only use Session::get() if you import the Session facade and use correct casing.

So just change:

@if($message = session::get('flash'))

to:

@if($message = session('flash'))

or, if you want the facade:

@php
    use Illuminate\Support\Facades\Session;
@endphp

@if($message = Session::get('flash'))

Let me know if you have any further questions!

1 like
Shivamyadav's avatar

If you really want to use the facade:

@php
    use Illuminate\Support\Facades\Session;
@endphp

@if ($message = Session::get('flash'))
    <div class="alert alert-success">
        {{ $message }}
    </div>
@endif 

Or just use the session helper function

@if (session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif 

Please or to participate in this conversation.