Back to Course |
Build Laravel API for Car Parking App: Step-By-Step

User Area: User Login

Now, in the same fashion, let's generate a Controller for the login mechanism:

php artisan make:controller Api/V1/Auth/LoginController

This will be the new route, in the routes/api.php file:

Route::post('auth/login', Auth\LoginController::class);

Again, the route prefix and Controller namespace will come automatically from the other logic we've discussed earlier, for RegisterController.

Inside the Controller, we log the user in and return the Sanctum token, similarly to the Registration function:

app/Http/Controllers/Api/V1/Auth/LoginController.php:

namespace App\Http\Controllers\Api\V1\Auth;
 
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
 
class LoginController extends Controller
{
public function __invoke(Request $request)
{
$request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
 
$user = User::where('email', $request->email)->first();
 
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
 
$device = substr($request->userAgent() ?? '', 0, 255);
$expiresAt = $request->remember ? null : now()->addMinutes(config('session.lifetime'));
 
return response()->json([
'access_token' => $user->createToken($device, expiresAt: $expiresAt)->plainTextToken,
], Response::HTTP_CREATED);
}
}

I think the logic is pretty clear here: we validate the data, get the user by email.

If there's no user or wrong password - we throw the validation exception, which automatically is transformed to this structure with the HTTP Status code 422:

Laravel API Login

If the login attempt is successful, we return the newly generated Laravel Sanctum token for the future requests.

Laravel API Login

The new thing here is that we implement the "remember me" functionality: if the $request->remember is present and true, then we set the additional expiresAt parameter in the Sanctum createToken() method.

Now, time to create the endpoints with the logged in user?