I want to access session data from database. Currently, I have changed default setting in session.php to database so that I can capture all the session columns in DB. But now I want to access these in my code. Do I need to create some session model or it's present out of the box just like user.php. Please help me.
1 Answer
You should create sessions table with these commands:
php artisan session:table
composer dump-autoload
php artisan migrate
Or you could manually create migration and run it, an example from documentation:
Schema::create('sessions', function ($table) {
$table->string('id')->unique();
$table->text('payload');
$table->integer('last_activity');
});
After doing that, you can just use sessions as usual with Session:: facade or sessions() helper:
session()->flash('message', 'Success!');
Update
If you need to access table data directly, you could do this:
DB::table('sessions')->get();
Or you could create SessionData() model and do this:
SessionData::all();
9 Comments
Unbreakable
I already have created session table in my DB. But I am not able to understand how to access its data.
Unbreakable
I can access User data by using user.php model ex: User::all() . But how to access session data. DO we have to create explicitly session model for it or we can simply access session::all()?
Unbreakable
I am really sorry if I think I did not explain my question properly. What if I want to access all the entries present in my session table. Suppose I want to print all the rows present in my session table from my code. How to achieve it?
Unbreakable
For user we can simply write code as User:all() to access all the contents since we had out of the box user.php model in built with the framework. but how to acheive this with session table?
Alexey Mezenin
You can use Query Builder:
DB::table('sessions')->all();. I guess if you'll create SessionData model, you'll be able to access table data with Eloquent too, like SessionData::all(); |