Laravel - Getting user details for method used in both web and api routes

1.3k Views Asked by At

I have a project in Laravel where I am using the same method for both a web and api route. So for example i would have the following:

//routes/web.php 
Route::post("/import-results", "ImportController@doImport");

//routes/api.php
Route::post("/import-results/{auto}", "ImportController@doImport");

So regardless of the route the doImport() function will be called in the ImportContoller.

The import controller has a function like this (there is validation in the function but I have taken it out for simplicity):

public function doImport($auto = null){
   $importData = new DataImport();
   $importData->type = $_POST['type'];
   $importData->data = $_POST['data'];
   $importData->user = Auth::user()->name;
   $importData->save();

   $data = [
      "success" => true,
      "message" => "Message Here!"
   ]

   if($auto){
      return json_encode($data);
   }else{
      return view('import-message', $data);
   }
}

As you can see this method uses Auth::user()->name; to identify which user imported the data. This is fine if i am logging in and using a regular web route but what about if i'm using an API and using basic auth where no sessions are created and I don't want sessions to persist if the api routes are called.

How do i get the user info when calling API routes?

Also for the web routes i have customised my login as i'm using ldap but essentially the login happens by doing $this->guard()->login($user, false); in a class with the AuthenticatesUsers trait.

I could do this for my API routes too but does this creates a session and how do i clear this session once the request has ended? Or is there a better way??

1

There are 1 best solutions below

1
On

To make session work for both page submitting and api. You need work in web.php

Make both route in web.php

   //Web.php
   Route::post("/import-results", "ImportController@doImport");

   Route::post("/api/import-results/{auto}", "ImportController@doImport");

api.php is stateless mean no session exist in api.php . It's working with token based like JWT.