Solution:
You can achieve this by leveraging session variables to store the "active store" for the customer and also saving the last active store in the database (in the user's profile, for example) so you can restore it when the user logs back in.
Here's a high-level approach:
1. Update Customer Model
Add a field to your users (or customers) table to store last_store_id.
// migration example
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('last_store_id')->nullable();
});
2. Store Selected Store in Session
When the user selects a store, update the session and the user's last_store_id:
public function selectStore(Request $request, Store $store)
{
// Put the store ID in session
session(['current_store_id' => $store->id]);
// Update user's last_store_id
Auth::user()->update([
'last_store_id' => $store->id
]);
return redirect()->back();
}
3. Set Store on Login
When the user logs in, check if last_store_id is set, and put it in the session:
public function authenticated(Request $request, $user)
{
if ($user->last_store_id) {
session(['current_store_id' => $user->last_store_id]);
}
}
Register this method in your LoginController. In Laravel, you can use the authenticated method for this:
// app/Http/Controllers/Auth/LoginController.php
protected function authenticated(Request $request, $user)
{
if ($user->last_store_id) {
session(['current_store_id' => $user->last_store_id]);
}
}
4. Retrieve Data Based on Selected Store
Whenever you need to fetch store-specific data, use session('current_store_id'):
public function someControllerMethod()
{
$storeId = session('current_store_id');
$store = Store::findOrFail($storeId);
// Fetch data related to this store
$products = $store->products;
// ...
}
5. Optional: Middleware for Store Context
If you want, you can create a middleware to ensure the session always has a store, redirecting the user to select one if not:
public function handle($request, Closure $next)
{
if (!session('current_store_id')) {
return redirect()->route('select.store');
}
return $next($request);
}
Apply this middleware to any routes that require a store context.
Summary:
- Use a session variable to store the active store.
- Save the last active store in the user/customer table.
- Restore this when the user logs in.
- Always fetch data using the store from the session.
This approach will make sure the app always serves up data for the selected store, and that the user's last-used store is remembered on re-login.