I can't set Session Items in laravel inertia

Viewed 76

I am using Laravel with inertia, but I am not able to set session items in laravel.
here is my laravel code:

use Illuminate\Support\Facades\Session;    
public function index()
        {
            Session::put('message', 'showCatergories');
            $categories = Category::all();
            return Inertia::render('Admin/Categories', ['categories' => $categories]);
        }

nothing appears in application -> storage-> sessoin storage
my route:

Route::middleware(['auth', 'web'])->group(function () {
    Route::resource('/categories', CategoriesController::class);
}); 

How to tackle this issue?

1 Answers

Working with session items and flash messages in Inertia.js is done by appending it to the shared method in the HandleInertiaRequests middleware.

class HandleInertiaRequests extends Middleware
{
    public function share(Request $request)
    {
        return array_merge(parent::share($request), [
            'flash' => [
                'message' => fn () => $request->session()->get('message')
            ],
        ]);
    }
}

Here we get the message item on the session and append it as a flash prop on the request.

Then we can use it in our frontend of choice. Here is a React.js example:

import { usePage } from '@inertiajs/inertia-react'

export default function Layout({ children }) {
  const { flash } = usePage().props

  return (
    <main>
      <header></header>
      <content>
        {flash.message && (
          <div class="alert">{flash.message}</div>
        )}
        {children}
      </content>
      <footer></footer>
    </main>
  )
}

You can read more about flash messages in the documentation.

Related