I developed a laravel API for flutter app. Here's my AuthController and the following are the function. What I want to do is that once I submit the request on postman, it will display the current info of the logged-in user. Currently, I manage to retrieved the info but it instead display the data of the first user in the table instead of the corresponding user that I logged in(in postman). How do I fix this ? Please help
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function login(Request $request)
{
$fields = $request->validate([
'email' => 'required|string',
'password' => 'required|string'
]);
//Check email
$user = User::where('email', $fields['email'])->first();
//Check password
if (!$user || !Hash::check($fields['password'], $user->password)) {
$result = [];
$result['status'] = false;
$result['message'] = "Bad creds";
return response()->json($result);
} else {
$result = [];
$result['status'] = true;
$result['message'] = "Login successfully";
$data = User::first(['staff_id', 'name']);
$result['data'] = $data;
return response()->json($result);
}
}
}
CodePudding user response:
In your else
block the
$data = User::first(['staff_id','name']);
means that it will fetch the first user in your database. Instead of querying again you can use the already declared $user
since it is the data that you are looking for.
$data = $user;
How about :
$data = [
'staff_id' => $user->staff_id,
'name' => $user->name,
];