Laravel save session value by jquery | How to save session in jquery

How to set session value throw jquery. Here we will discuss set a session value by jquery in laravel 7, laravel 8 and laravel 9.

Set session value by jquery

When we want to set session value in jquery sent value by ajax request to PHP and save it in session. In our example, we will make an ajax request for a set session. A session is only set in the backend because it saves on server.

Web Routes

Route::get('set-data', [SessionController::class, 'setData'])->name('session.create');

SessionController

create a function for set data in session

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Session;

class SessionController extends Controller{
  public function setData(Request $request){
  	$data = [
  		'name' => $request->name,
  		'age' => $request->age,
  		'phone' => $request->phone
  	];
    Session::put('user_data', $data);
    return response()->json(['session successfully saved']);
  }
}

Blade file index.blade.php

Create an index blade file where we make a ajax request for set user detail in session. you also get session value in jquery.

<html>
  <body>
  	<button id="set_session">Set Session</button>
  </body>

  <script src="jquery.js"><script>
  <script type="text/javascript">
  	$(document).on('click', '#set_session', function(){
	    $.ajax({ 
	      url: "{{ route('session.create') }}",
	      data: {'name': 'anmol sharma', 'age': '25', 'phone': '1234567890'},
	      type: 'get',
	      success: function(response){
	          console.log(response);
	      }
	    });
  	});
  </script>
</html>
php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links