Here’s a quick explanation on how you go about Authentication and some tips.
Building Registration & Login Forms
- Create
register.blade.phpandlogin.blade.phpviews under anauthdirectory. - Use the form components to build inputs for first name, last name, email, password, and password confirmation.
- Add
requiredattributes for client-side validation.
Defining Authentication Routes and Controllers
- Add routes for showing registration and login forms (
GET /register,GET /login). - Add routes for handling form submissions (
POST /register,POST /login). - Create corresponding controllers like
RegisteredUserControllerandSessionControllerwithcreateandstoremethods.
Displaying Content Conditionally
Use Blade directives to show login and register links only to guests:
@guest
<x-nav-link href="/login">Login</x-nav-link>
<x-nav-link href="/register">Register</x-nav-link>
@endguestUse @auth to show content only to authenticated users.
Registration Process
When a user submits the registration form, the following steps occur:
- Validation: Use
$request->validate()to ensure required fields like first name, last name, email, and password meet your criteria. Laravel provides many validation rules, including a fluentPasswordhelper for complex password requirements. - Creating the User: After validation, create the user in the database. You can pass the validated attributes directly to
User::create(). - Logging In: Use
Auth::login($user)to sign in the newly registered user. - Redirecting: Redirect the user to a desired page, such as the jobs listing or dashboard.
Example Validation Rules
$request->validate([
'first_name' => ['required', 'min:1'],
'last_name' => ['required', 'min:1'],
'email' => ['required', 'email'],
'password' => ['required', 'confirmed', Password::min(6)],
]);The confirmed rule requires a matching password_confirmation field.
Login Process
When a user submits the login form:
- Validation: Validate the email and password fields.
- Authentication Attempt: Use
Auth::attempt($credentials)to try logging in. - Session Regeneration: On successful login, regenerate the session token for security.
- Redirect: Redirect the user to the intended page.
- Handling Failure: If login fails, throw a validation exception with an appropriate error message.
Preserving Input on Validation Errors
Use the old() helper in Blade to repopulate form fields after validation errors, improving user experience.
<input name="email" value="{{ old('email') }}" />Remember to prefix with : in Blade to treat as an expression:
:value="old('email')"Authentication Tips
1. Establishing Relationships for Authorization
To perform user authorization on a job, there must be a relationship between the job and a user. Currently, jobs relate to employers, but employers don’t relate to users. Fix this by adding a foreign key user_id to the employers table and updating the Employer factory to associate an employer with a user.
2. Inline Authorization in Controller
Add a simple authorization check in your job controller’s edit action:
- Redirect guests to login.
- Check if the authenticated user is responsible for the job.
- If not authorized, abort with a 403 status.
Use Eloquent relationships to traverse from job to employer to user, and compare with the authenticated user using the is method.
3. Gates
Extract authorization logic into gates for reusability and clarity.
- Define gates in
AppServiceProviderusing theGatefacade. - Gates return a boolean indicating authorization.
- Use
Gate::authorize('edit-job', $job)in your controller to enforce authorization.
Gates automatically abort with 403 if authorization fails, but you can use Gate::allows or Gate::denies for custom handling.
4. Using can and cannot Methods
Your User model has can and cannot methods to check permissions against gates. Use these in controllers or Blade views to conditionally allow actions.
@can('edit', $job)
<p class="mt-6">
<x-button href="/jobs/{{ $job->id }}/edit">Edit Job</x-button>
</p>
@endcanThis code allows a user to only see the edit Job button if he’s authorized to do so. In this case that would be if he created the note.
5. Middleware Authorization
Apply authorization at the route level using middleware:
Route::patch('/jobs/{job}', [JobController::class, 'update'])
->middleware(['auth', 'can:edit,job']);This ensures users are authenticated and authorized before accessing the route.
You can specify middleware per route or group routes for cleaner code.
6. Policies
Policies are classes that encapsulate authorization logic for a model.
- Generate a policy with
php artisan make:policy JobPolicy --model=Job. - Define methods like
edit,deleteto control access. - Register policies in
AuthServiceProvider. - Use policies via gates or
canmethods.
Policies provide a structured, scalable way to manage complex authorization rules.
