One solution to this problem is to use the URL as a reference and create a session with a name that matches the URL. This can be done by passing the URL as a parameter in the AJAX request and using it to create the session name in the controller.
Here's an example of how this can be done:
- In your JavaScript code, add the current URL as a parameter in the AJAX request:
var url = window.location.href;
$.ajax({
url: '/save-session',
type: 'POST',
data: {
filters: filters,
url: url
},
success: function(response) {
// Handle success
},
error: function(xhr) {
// Handle error
}
});
- In your controller, use the URL parameter to create the session name and save the data:
public function saveSession(Request $request)
{
$filters = $request->input('filters');
$url = $request->input('url');
$sessionName = str_replace('/', '_', $url); // Replace slashes with underscores
session([$sessionName => $filters]);
return response()->json(['success' => true]);
}
- To retrieve the session data on a specific page, use the current URL to get the session name and retrieve the data:
$url = window.location.href;
$sessionName = str_replace('/', '_', $url);
var filters = {!! json_encode(session($sessionName)) !!};
This way, you can use the same AJAX route and controller method for all pages, and the session data will be saved and retrieved based on the URL of the page.