Skip to content

Authentication

Security

Authentication

Introduction

Laravel provides built-in authentication backed by sessions and "remember me" cookies, along with password resets and email verification, while letting your application control its own login pages and forms. If you want users to sign in with Google, GitHub, or Microsoft, check out the Social login guide.

Authentication works through a "guard" and a "user provider". The guard identifies the user for each incoming request, while the provider loads that user from storage, typically your users table. The built-in session guard uses the session cookie on web routes; for token-based APIs, you can define a request guard.

Once authentication determines who the user is, authorization decides which actions they are permitted to perform.

Setting up

New applications include a User model, a users migration, and the session guard registered in src/app.rs, while leaving login, registration, and logout routes up to your application. The sections below walk through each piece so you can customize them, such as signing users in by username instead of email.

Your user type

Your user is a model that derives Authenticatable. The derive reads the user's ID, password hash, and remember token from the id, password, and remember_token fields. The default User model in src/models/user.rs looks like this:

1use laravel::auth::{Authenticatable, RememberToken};
2use laravel::hash::PasswordHash;
3use laravel::model::model;
4use laravel::time::Timestamp;
5 
6#[model]
7#[derive(Authenticatable)]
8pub struct User {
9 pub id: i64,
10 pub name: String,
11 pub email: String,
12 pub email_verified_at: Option<Timestamp>,
13 #[serde(skip)]
14 pub password: PasswordHash,
15 #[serde(skip)]
16 pub remember_token: Option<RememberToken>,
17 pub created_at: Timestamp,
18 pub updated_at: Timestamp,
19}
1use laravel::auth::{Authenticatable, RememberToken};
2use laravel::hash::PasswordHash;
3use laravel::model::model;
4use laravel::time::Timestamp;
5 
6#[model]
7#[derive(Authenticatable)]
8pub struct User {
9 pub id: i64,
10 pub name: String,
11 pub email: String,
12 pub email_verified_at: Option<Timestamp>,
13 #[serde(skip)]
14 pub password: PasswordHash,
15 #[serde(skip)]
16 pub remember_token: Option<RememberToken>,
17 pub created_at: Timestamp,
18 pub updated_at: Timestamp,
19}

Neither PasswordHash nor RememberToken implements Serialize, so User compiles only once you skip both fields. That way, neither the password hash nor the remember token can leak into a page or JSON response.

Users log in with their email address. To log them in by another column, such as a username, mark its field with #[auth(username)].

The users table needs a password column and a nullable remember_token column. The default migration creates both:

1tx.schema()
2 .create("users", |table| {
3 table.id();
4 table.string("name");
5 table.string("email").unique();
6 table.timestamp("email_verified_at").nullable();
7 table.string("password");
8 table.remember_token();
9 table.timestamps();
10 })
11 .await
1tx.schema()
2 .create("users", |table| {
3 table.id();
4 table.string("name");
5 table.string("email").unique();
6 table.timestamp("email_verified_at").nullable();
7 table.string("password");
8 table.remember_token();
9 table.timestamps();
10 })
11 .await

Registering the session guard

The session guard keeps the logged-in user's ID in the session, and asks a provider for the user on each request. When your users are a model, the provider is model::Users, which finds them with the model's queries. Register the guard with it in src/app.rs:

1use laravel::model;
2 
3use crate::models::User;
4 
5Application::configure()
6 .with_auth(|auth, _| {
7 auth.session::<model::Users<User>>();
8 })
1use laravel::model;
2 
3use crate::models::User;
4 
5Application::configure()
6 .with_auth(|auth, _| {
7 auth.session::<model::Users<User>>();
8 })

model::Users looks up users by their email address (or whichever column is marked #[auth(username)]). If you need to block specific accounts from accessing your application, such as suspended users, you can reject their requests in a middleware or check their account status during login.

An application registers a single session guard for one user type. For roles such as administrators, store the role on your User model and check it in a policy.

Marking pages

Laravel needs to know which routes serve a few core authentication pages so it can redirect guests to your login form and generate password reset or email verification links. Annotate each corresponding handler with #[laravel::auth::page(..)]:

1use laravel::inertia::{self, Page, props};
2 
3#[laravel::auth::page(login)]
4pub async fn show_login() -> Page {
5 inertia::render("auth/Login", props! {})
6}
1use laravel::inertia::{self, Page, props};
2 
3#[laravel::auth::page(login)]
4pub async fn show_login() -> Page {
5 inertia::render("auth/Login", props! {})
6}

The attribute doesn't change the handler, so you route it and link to it as usual. You do not need to mark every page; only annotate the ones your application actually uses (for example, omit verification_notice and verify_email if your application does not require email verification):

Attribute Page Who sends users there
#[laravel::auth::page(login)] The login page Authenticate, for guests
#[laravel::auth::page(home)] The logged-in user's home, such as a dashboard RedirectIfAuthenticated, for logged-in users
#[laravel::auth::page(reset_password)] The form that sets a new password The link in password reset emails
#[laravel::auth::page(verification_notice)] The page that asks the user to verify their email RequireVerifiedEmail, for users who haven't
#[laravel::auth::page(verify_email)] The handler that verifies the email The link in verification emails

Logging users in

Users log in through a form on your login page. The handler that the form posts to checks the user's email and password, then stores the user in the session, so your handlers can retrieve them on later requests.

Attempting a login

In that handler, take Auth<User> as an argument and call attempt with the email and password from the form. It finds the user, checks the password, and logs them in:

1use laravel::auth::Auth;
2use laravel::hash::Password;
3use laravel::prelude::*;
4 
5#[laravel::input]
6#[validate(anyone)]
7pub struct Login {
8 #[transform(lowercase)]
9 #[validate(required, email)]
10 email: String,
11 #[validate(required)]
12 password: Password,
13 #[serde(default)]
14 remember: bool,
15}
16 
17pub async fn login(auth: Auth<User>, form: Valid<Login>) -> laravel::Result<Redirect> {
18 auth.attempt(&form.email, &form.password).remember(form.remember).await?;
19 
20 Ok(Redirect::intended(dashboard::show, ()))
21}
1use laravel::auth::Auth;
2use laravel::hash::Password;
3use laravel::prelude::*;
4 
5#[laravel::input]
6#[validate(anyone)]
7pub struct Login {
8 #[transform(lowercase)]
9 #[validate(required, email)]
10 email: String,
11 #[validate(required)]
12 password: Password,
13 #[serde(default)]
14 remember: bool,
15}
16 
17pub async fn login(auth: Auth<User>, form: Valid<Login>) -> laravel::Result<Redirect> {
18 auth.attempt(&form.email, &form.password).remember(form.remember).await?;
19 
20 Ok(Redirect::intended(dashboard::show, ()))
21}

The form declares its password field as laravel::hash::Password rather than a String. A Password keeps the plain-text password out of your logs, and fails validation on the field when a password is too long to hash. To learn more, check out the hashing guide's section on password fields.

When the email or password is wrong, attempt returns a validation error. The browser goes back to the form with "These credentials do not match our records." on the email field, and a JSON client gets a 422. If User marks a field #[auth(username)], the error goes on that field instead, so give the form field the same name.

On success, attempt regenerates the session ID, stores the user in the session, and returns the user. Redirect::intended sends the user back to the URL they originally tried to visit before Authenticate redirected them to login, falling back to the route you specify.

Laravel hashes passwords using Bcrypt. When you raise BCRYPT_ROUNDS, attempt automatically rehashes the user's password with the new work factor on their next login, as Hashing describes.

Throttling login attempts

Throttle your login handler so an attacker can't try thousands of passwords a minute. To count only failed attempts and clear the counter once the user signs in, extract ValidRequest<Login> so you have the client's IP address, check the rate limit before calling attempt, and call hit only on failure:

1use laravel::auth::Auth;
2use laravel::prelude::*;
3use laravel::rate_limit::{self, Limit};
4use laravel::validation::ValidRequest;
5 
6pub async fn login(auth: Auth<User>, login: ValidRequest<Login>) -> laravel::Result<Redirect> {
7 let limit = Limit::per_minute(5);
8 
9 let key = format!("login:{}|{}", login.email.to_lowercase(), login.request().ip());
10 
11 rate_limit::check(&key, limit).await??;
12 
13 if let Err(error) = auth.attempt(&login.email, &login.password).remember(login.remember).await {
14 rate_limit::hit(&key, limit).await?;
15 return Err(error);
16 }
17 
18 rate_limit::clear(&key).await?;
19 
20 Ok(Redirect::intended(dashboard::show, ()))
21}
1use laravel::auth::Auth;
2use laravel::prelude::*;
3use laravel::rate_limit::{self, Limit};
4use laravel::validation::ValidRequest;
5 
6pub async fn login(auth: Auth<User>, login: ValidRequest<Login>) -> laravel::Result<Redirect> {
7 let limit = Limit::per_minute(5);
8 
9 let key = format!("login:{}|{}", login.email.to_lowercase(), login.request().ip());
10 
11 rate_limit::check(&key, limit).await??;
12 
13 if let Err(error) = auth.attempt(&login.email, &login.password).remember(login.remember).await {
14 rate_limit::hit(&key, limit).await?;
15 return Err(error);
16 }
17 
18 rate_limit::clear(&key).await?;
19 
20 Ok(Redirect::intended(dashboard::show, ()))
21}

Remembering users

Many applications show a "remember me" checkbox on their login form. Pass its boolean value to remember when calling attempt:

1auth.attempt(&form.email, &form.password)
2 .remember(form.remember)
3 .await?;
1auth.attempt(&form.email, &form.password)
2 .remember(form.remember)
3 .await?;

A remembered user receives an encrypted cookie that lasts 400 days. After their session expires, the cookie signs them back in automatically on their next visit.

Logging in a user you already have

To log in a user without checking a password, such as immediately after registration, pass them to login:

1use laravel::auth::Auth;
2use laravel::hash::Password;
3use laravel::model::create;
4use laravel::prelude::*;
5 
6#[laravel::input]
7#[validate(anyone)]
8pub struct SignUp {
9 #[validate(required, max_length(255))]
10 name: String,
11 #[transform(lowercase)]
12 #[validate(required, email, unique(User::email))]
13 email: String,
14 #[validate(required, password, confirmed)]
15 password: Password,
16}
17 
18pub async fn sign_up(
19 auth: Auth<User>,
20 Valid(form): Valid<SignUp>,
21) -> laravel::Result<Redirect> {
22 let user = create!(User {
23 name: &form.name,
24 email: &form.email,
25 password: &form.password,
26 })
27 .await?;
28 
29 auth.login(&user).await?;
30 
31 Ok(redirect!(dashboard::show))
32}
1use laravel::auth::Auth;
2use laravel::hash::Password;
3use laravel::model::create;
4use laravel::prelude::*;
5 
6#[laravel::input]
7#[validate(anyone)]
8pub struct SignUp {
9 #[validate(required, max_length(255))]
10 name: String,
11 #[transform(lowercase)]
12 #[validate(required, email, unique(User::email))]
13 email: String,
14 #[validate(required, password, confirmed)]
15 password: Password,
16}
17 
18pub async fn sign_up(
19 auth: Auth<User>,
20 Valid(form): Valid<SignUp>,
21) -> laravel::Result<Redirect> {
22 let user = create!(User {
23 name: &form.name,
24 email: &form.email,
25 password: &form.password,
26 })
27 .await?;
28 
29 auth.login(&user).await?;
30 
31 Ok(redirect!(dashboard::show))
32}

create! hashes the password for you, so the plain text never reaches your database. login also takes .remember(true).

On PostgreSQL and SQLite, text comparisons are case-sensitive, so [email protected] and [email protected] don't match during sign-up or login. Adding #[transform(lowercase)] normalizes the email address before unique(User::email) and attempt run. To learn more, check out the validation guide's section on transforming input fields.

Handling a failed login yourself

Internally, attempt calls validate followed by login. When you want custom behavior on failure, call both methods yourself: validate checks the email and password and returns Option<User> without signing the user in.

For example, suppose your users table has a nullable suspended_at column. This handler for the Login form above logs failed attempts and informs suspended users why their account is locked:

1use laravel::auth::Auth;
2use laravel::prelude::*;
3use laravel::validation::invalid;
4 
5pub async fn login(auth: Auth<User>, form: Valid<Login>) -> laravel::Result<Redirect> {
6 let Some(user) = auth.validate(&form.email, &form.password).await? else {
7 tracing::info!(email = form.email, "failed login");
8 
9 invalid!(email => "These credentials do not match our records.");
10 };
11 
12 if user.suspended_at.is_some() {
13 invalid!(email => "This account has been suspended.");
14 }
15 
16 auth.login(&user).remember(form.remember).await?;
17 
18 Ok(Redirect::intended(dashboard::show, ()))
19}
1use laravel::auth::Auth;
2use laravel::prelude::*;
3use laravel::validation::invalid;
4 
5pub async fn login(auth: Auth<User>, form: Valid<Login>) -> laravel::Result<Redirect> {
6 let Some(user) = auth.validate(&form.email, &form.password).await? else {
7 tracing::info!(email = form.email, "failed login");
8 
9 invalid!(email => "These credentials do not match our records.");
10 };
11 
12 if user.suspended_at.is_some() {
13 invalid!(email => "This account has been suspended.");
14 }
15 
16 auth.login(&user).remember(form.remember).await?;
17 
18 Ok(Redirect::intended(dashboard::show, ()))
19}

Retrieving the logged-in user

For handlers that require an authenticated user, extract Authenticated<User>, which dereferences directly to your User model:

1use laravel::auth::Authenticated;
2use laravel::inertia::{self, Page, props};
3 
4pub async fn show(user: Authenticated<User>) -> Page {
5 inertia::render("Dashboard", props! { "name" => &user.name })
6}
1use laravel::auth::Authenticated;
2use laravel::inertia::{self, Page, props};
3 
4pub async fn show(user: Authenticated<User>) -> Page {
5 inertia::render("Dashboard", props! { "name" => &user.name })
6}

If a guest hits the route, Laravel redirects them to the login page (or responds with 401 for JSON requests) before the handler runs, matching the Authenticate middleware.

For routes accessible to both guests and signed-in users, extract Auth<User> and call auth.user().await?, which returns Option<User>:

1use laravel::auth::Auth;
2use laravel::inertia::{self, Page, props};
3 
4pub async fn home(auth: Auth<User>) -> laravel::Result<Page> {
5 let name = auth.user().await?.map(|user| user.name);
6 
7 Ok(inertia::render("Home", props! { "name" => name }))
8}
1use laravel::auth::Auth;
2use laravel::inertia::{self, Page, props};
3 
4pub async fn home(auth: Auth<User>) -> laravel::Result<Page> {
5 let name = auth.user().await?.map(|user| user.name);
6 
7 Ok(inertia::render("Home", props! { "name" => name }))
8}

Auth<User> also provides check() (returning a bool) and id() (returning Option<Id>), and works anywhere extractors are supported, including middleware:

1if auth.check().await? {
2 // The user is logged in...
3}
4 
5if let Some(user_id) = auth.id().await? {
6 // ...
7}
1if auth.check().await? {
2 // The user is logged in...
3}
4 
5if let Some(user_id) = auth.id().await? {
6 // ...
7}

When you have a &Request without extractors, such as inside your Inertia middleware's share method, call request.user() with an explicit type annotation:

1async fn share(&self, request: &Request) -> laravel::Result<Props> {
2 let user: Option<User> = request.user().await?;
3 
4 Ok(props! { user => user })
5}
1async fn share(&self, request: &Request) -> laravel::Result<Props> {
2 let user: Option<User> = request.user().await?;
3 
4 Ok(props! { user => user })
5}

If you only need to check whether someone is signed in without loading the model, call request.authenticated(), which returns a bool without requiring a type parameter:

1if request.authenticated().await? {
2 // ...
3}
1if request.authenticated().await? {
2 // ...
3}

Laravel caches the resolved user for the duration of the request, so Auth, Authenticated, request.user(), and request.authenticated() all share the same lookup.

Protecting routes

The Authenticate middleware lets only logged-in users through. Attach it to a group of routes in your route file:

1use laravel::auth::Authenticate;
2use laravel::prelude::*;
3 
4pub fn routes(route: &mut Router) {
5 route.middleware(Authenticate).group(|route| {
6 route.get("/dashboard", dashboard::show);
7 route.get("/settings", settings::show);
8 });
9}
1use laravel::auth::Authenticate;
2use laravel::prelude::*;
3 
4pub fn routes(route: &mut Router) {
5 route.middleware(Authenticate).group(|route| {
6 route.get("/dashboard", dashboard::show);
7 route.get("/settings", settings::show);
8 });
9}

Redirecting guests

Authenticate sends a guest to the login page. If the guest was visiting a page with GET, the session stores that URL so Redirect::intended can redirect them back after logging in. A request expecting JSON, or an application without a login page, receives a 401 instead.

Pages for guests only

The RedirectIfAuthenticated middleware sends logged-in users to the home page, or else to /. Use it for pages that only guests need, such as the login page:

1use laravel::auth::RedirectIfAuthenticated;
2 
3route.middleware(RedirectIfAuthenticated).group(|route| {
4 route.get("/login", auth::show_login);
5 route.post("/login", auth::login);
6});
1use laravel::auth::RedirectIfAuthenticated;
2 
3route.middleware(RedirectIfAuthenticated).group(|route| {
4 route.get("/login", auth::show_login);
5 route.post("/login", auth::login);
6});

Logging out

To log the user out, call logout. It clears the session, regenerates the session ID and CSRF token, and invalidates the user's "remember me" cookies across all devices:

1use laravel::auth::Auth;
2use laravel::inertia::Inertia;
3use laravel::prelude::*;
4 
5pub async fn logout(auth: Auth<User>, inertia: Inertia) -> laravel::Result<Redirect> {
6 auth.logout().await?;
7 
8 inertia.clear_history();
9 
10 Ok(Redirect::to("/"))
11}
1use laravel::auth::Auth;
2use laravel::inertia::Inertia;
3use laravel::prelude::*;
4 
5pub async fn logout(auth: Auth<User>, inertia: Inertia) -> laravel::Result<Redirect> {
6 auth.logout().await?;
7 
8 inertia.clear_history();
9 
10 Ok(Redirect::to("/"))
11}

After a logout, the browser's back button can still show pages the user saw while logged in. With Inertia, turn on history encryption in your Inertia middleware, and call clear_history when the user logs out, as above. The back button then can't restore those pages:

1impl inertia::Middleware for HandleInertiaRequests {
2 // ...
3 
4 fn configure(&self, config: inertia::Config) -> inertia::Config {
5 config.encrypt_history(true)
6 }
7}
1impl inertia::Middleware for HandleInertiaRequests {
2 // ...
3 
4 fn configure(&self, config: inertia::Config) -> inertia::Config {
5 config.encrypt_history(true)
6 }
7}

Logging out other devices

To sign a user out of their other active sessions without logging out their current device, confirm their current password and pass it to update_password:

1use laravel::auth::Auth;
2use laravel::hash::Password;
3use laravel::prelude::*;
4 
5#[laravel::input]
6#[validate(authenticated)]
7pub struct LogoutOtherDevices {
8 #[validate(required, current_password)]
9 password: Password,
10}
11 
12pub async fn logout_other_devices(
13 auth: Auth<User>,
14 Valid(form): Valid<LogoutOtherDevices>,
15) -> laravel::Result<Redirect> {
16 auth.update_password(&form.password).await?;
17 
18 Ok(Redirect::back().with("status", "You're logged out on your other devices."))
19}
1use laravel::auth::Auth;
2use laravel::hash::Password;
3use laravel::prelude::*;
4 
5#[laravel::input]
6#[validate(authenticated)]
7pub struct LogoutOtherDevices {
8 #[validate(required, current_password)]
9 password: Password,
10}
11 
12pub async fn logout_other_devices(
13 auth: Auth<User>,
14 Valid(form): Valid<LogoutOtherDevices>,
15) -> laravel::Result<Redirect> {
16 auth.update_password(&form.password).await?;
17 
18 Ok(Redirect::back().with("status", "You're logged out on your other devices."))
19}

Under the hood, Laravel stores a signed fingerprint of the user's password hash in each session and "remember me" cookie and verifies it on every request. Because Bcrypt generates a new random salt every time it hashes a password, calling update_password produces a different stored hash even for the same password. Laravel refreshes the fingerprint on the current device (keeping it signed in), while every other device's session and "remember me" cookie fails the fingerprint check on its next request and is automatically logged out.

Changing a password

To change the logged-in user's password, call update_password. It hashes the password, stores the hash, and keeps the current device logged in. Ask for the current password too, so someone who finds the user's laptop unlocked can't take over the account:

1use laravel::auth::Auth;
2use laravel::hash::Password;
3use laravel::prelude::*;
4 
5#[laravel::input]
6#[validate(authenticated)]
7pub struct UpdatePassword {
8 #[validate(required, current_password)]
9 current_password: Password,
10 #[validate(required, password, confirmed)]
11 password: Password,
12}
13 
14pub async fn update(
15 auth: Auth<User>,
16 Valid(form): Valid<UpdatePassword>,
17) -> laravel::Result<Redirect> {
18 auth.update_password(&form.password).await?;
19 
20 Ok(Redirect::back().with("status", "Password updated."))
21}
1use laravel::auth::Auth;
2use laravel::hash::Password;
3use laravel::prelude::*;
4 
5#[laravel::input]
6#[validate(authenticated)]
7pub struct UpdatePassword {
8 #[validate(required, current_password)]
9 current_password: Password,
10 #[validate(required, password, confirmed)]
11 password: Password,
12}
13 
14pub async fn update(
15 auth: Auth<User>,
16 Valid(form): Valid<UpdatePassword>,
17) -> laravel::Result<Redirect> {
18 auth.update_password(&form.password).await?;
19 
20 Ok(Redirect::back().with("status", "Password updated."))
21}

Changing a password logs the user out of every other session and "remember me" cookie, including any an attacker is using. This happens whenever the stored hash changes, even when you store it another way, such as from a console command.

Stateless authentication

API clients, such as mobile apps or other servers, typically authenticate each request with a bearer token, API key header, or signed credential instead of a session cookie. To authenticate stateless requests, implement RequestGuard on a service. Its user method inspects the incoming Request and returns the matching user, or None if the request cannot be authenticated.

Store a hash of each API token rather than the plaintext token so a database leak does not expose live credentials. Suppose your users table has an api_token column holding a SHA-256 hash computed with the sha2 and hex crates, installed with cargo add sha2 hex. This guard, in src/http/guards.rs, reads the bearer token from the Authorization: Bearer header:

1use laravel::auth::RequestGuard;
2use laravel::container::singleton;
3use laravel::prelude::*;
4use sha2::{Digest, Sha256};
5 
6use crate::models::User;
7 
8#[singleton]
9pub struct ApiTokens;
10 
11impl RequestGuard for ApiTokens {
12 type User = User;
13 
14 async fn user(&self, request: &Request) -> laravel::Result<Option<User>> {
15 let Some(token) = request.bearer_token() else {
16 return Ok(None);
17 };
18 
19 let hash = hex::encode(Sha256::digest(token));
20 
21 User::first_where(User::api_token.eq(hash)).await
22 }
23}
1use laravel::auth::RequestGuard;
2use laravel::container::singleton;
3use laravel::prelude::*;
4use sha2::{Digest, Sha256};
5 
6use crate::models::User;
7 
8#[singleton]
9pub struct ApiTokens;
10 
11impl RequestGuard for ApiTokens {
12 type User = User;
13 
14 async fn user(&self, request: &Request) -> laravel::Result<Option<User>> {
15 let Some(token) = request.bearer_token() else {
16 return Ok(None);
17 };
18 
19 let hash = hex::encode(Sha256::digest(token));
20 
21 User::first_where(User::api_token.eq(hash)).await
22 }
23}

To protect routes with the guard, use Authenticate::via, which runs the guard for each request:

1use laravel::auth::Authenticate;
2 
3route.middleware(Authenticate::via::<ApiTokens>()).group(|route| {
4 route.get("/me", users::me);
5});
1use laravel::auth::Authenticate;
2 
3route.middleware(Authenticate::via::<ApiTokens>()).group(|route| {
4 route.get("/me", users::me);
5});

If the guard returns None, Laravel returns the same unauthenticated response as Authenticate: 401 for JSON requests, or a redirect to the login page for browser requests. Otherwise, Authenticated<User>, Auth<User>, and request.user() resolve to the authenticated user:

1use laravel::prelude::*;
2 
3pub async fn me(Authenticated(user): Authenticated<User>) -> Json<User> {
4 Json(user)
5}
1use laravel::prelude::*;
2 
3pub async fn me(Authenticated(user): Authenticated<User>) -> Json<User> {
4 Json(user)
5}

A request guard needs no session, so it works on routes in the api group. Because there's no session there, login, attempt, logout, and update_password return a server error on those routes.

Testing

To send a test request as a logged-in user, use acting_as:

1use app::models::User;
2use laravel::testing::prelude::*;
3 
4#[laravel::test]
5async fn the_dashboard_greets_the_user(app: Application) -> laravel::Result<()> {
6 let user = User::factory().create().await?;
7 
8 app.get("/dashboard")
9 .acting_as(&user)
10 .await
11 .assert_ok()
12 .assert_see(&format!("Hello, {}", user.name));
13 
14 Ok(())
15}
1use app::models::User;
2use laravel::testing::prelude::*;
3 
4#[laravel::test]
5async fn the_dashboard_greets_the_user(app: Application) -> laravel::Result<()> {
6 let user = User::factory().create().await?;
7 
8 app.get("/dashboard")
9 .acting_as(&user)
10 .await
11 .assert_ok()
12 .assert_see(&format!("Hello, {}", user.name));
13 
14 Ok(())
15}

acting_as works on routes that a request guard protects too, without running the guard.

To test logging in itself, create a user with a factory and post their credentials to your login route:

1use app::models::User;
2use laravel::model::create;
3use laravel::testing::prelude::*;
4 
5#[laravel::test]
6async fn users_can_log_in(app: Application) -> laravel::Result<()> {
7 let user = create!(User::factory() { password: "password" }).await?;
8 
9 let response = app
10 .post("/login")
11 .form([("email", user.email.as_str()), ("password", "password")])
12 .await;
13 
14 response
15 .assert_redirect_to("/dashboard")
16 .assert_authenticated_as(&user);
17 
18 app.get("/dashboard")
19 .with_cookies_from(&response)
20 .await
21 .assert_ok();
22 
23 Ok(())
24}
1use app::models::User;
2use laravel::model::create;
3use laravel::testing::prelude::*;
4 
5#[laravel::test]
6async fn users_can_log_in(app: Application) -> laravel::Result<()> {
7 let user = create!(User::factory() { password: "password" }).await?;
8 
9 let response = app
10 .post("/login")
11 .form([("email", user.email.as_str()), ("password", "password")])
12 .await;
13 
14 response
15 .assert_redirect_to("/dashboard")
16 .assert_authenticated_as(&user);
17 
18 app.get("/dashboard")
19 .with_cookies_from(&response)
20 .await
21 .assert_ok();
22 
23 Ok(())
24}

assert_authenticated verifies that a user is signed into the session, assert_authenticated_as(&user) verifies which user is signed in, and assert_guest confirms that no user is authenticated (such as after submitting an invalid password). Passing with_cookies_from(&response) carries the response's session cookie into the next request.