Usually I save temporary data/array inside session while working with Website (Non API).
Today I want to do the same thing (save temporary data/array inside session) with Laravel API.
So here is my route.
Route::middleware(['auth:api', 'isMember'])->group(function () {
Route::get('createSession', function (){
$a = Session::put('example', 'this is example session.');
return "session created";
});
Route::get('getSession', function () {
return Session::get('example');
});
});
When I visit /api/createSession
it return session created
, but when I visit /api/getSession
it return nothing.
So how do I work with session inside API?
What I think why this not work because API use Token based authentication instead of Session based Authentication, refer to config/auth.php
Authentication Guards section.
If work with session inside API is consider as bad practice, What is your suggestion to save temporary data/array inside API for shared hosting?
What I have tried so far is save data/array in Storage::disk(local)
but I don't think it best practice.
Thanks in advance.
PS: I will use Session to store temporary data about Cart
Middleware api did not include StartSession middleware, so you can not get the session. Check it here: https://github.com/laravel/laravel/blob/master/app/Http/Kernel.php#L33
You can add middleware "web" to your route or add \Illuminate\Session\Middleware\StartSession::class,
to middleware api but I'm not recommended it. APIs should not use session.
Hope that it can help you.