Laravel 11 Project Setup, Authentication, and Profile Display

Laravel 11 Project Setup, Authentication, and Profile Display

Laravel 11 Project Setup, Authentication, and Profile Display

Step 1: Installing Laravel 11

Prerequisites:

  • PHP: Ensure you have PHP (version 8.2 or later) installed on your system. You can check your version with php -v in the terminal. Refer to Laravel’s documentation under “Server Requirements” for the most up-to-date information: Laravel 11
  • Composer: Composer is PHP’s package manager. Make sure it’s globally installed. You can check by running composer -v in your terminal. If not installed, download it from https://getcomposer.org/.

Installation using Composer:

  1. Open your terminal or command prompt.
  2. Navigate to the desired directory for your project:

cd C:\xampp\htdocs  (Example: If using XAMPP on Windows)

  1. Create a new Laravel project using Composer
composer create-project laravel/laravel my-chat-app "11.*" 

Notes:

  • The 11.* part of the command ensures you get the latest version of Laravel 11.
  • This process downloads all the necessary Laravel framework files.

Step 2: Understanding the Directory Structure!

Let’s do a deep dive into understanding Laravel 11’s directory structure. Here’s a breakdown of the key folders and their purposes:

  1. Core Folders
  • app: Contains the heart of your application logic.
    • Models: Define database entities and their relationships.
    • Http/Controllers: Handle incoming HTTP requests and return responses.
    • You may see other folders as your project grows (Services, Repositories, etc.) for organizing application logic.
  • bootstrap: Handles framework initialization and bootstrapping processes.
    • Contains the app.php file responsible for bootstrapping the Laravel application.
  • config: Holds all of your project’s configuration files.
    • Files like app.php, database.php, auth.php, etc., control core aspects of your application.
  • database: Houses database migrations (code-based blueprints for your database tables).
    • May also contain seed files for populating your database with initial data.
  • public: The entry point of your application accessible over the web.
    • Contains the index.php file, which initiates the Laravel request lifecycle.
    • Stores compiled CSS, JavaScript, images, and other assets.
  • resources: Contains raw assets for your project.
    • views: Houses your Blade templates that render the HTML front-end of your application.
    • js: For uncompiled JavaScript components.
    • css: For uncompiled CSS stylesheets. (Commonly you’ll find lang for translations as well).
  • routes: Contains files defining the routes (URLs) of your application.
    • web.php: Typically defines routes accessible via the web browser.
    • api.php (Optional): Define routes specifically for API endpoints.
      • Command to create: php artisan install:api
  • storage: Used for storing various files generated by your application.
    • File uploads, cached data, logs, and session files may be stored here.
  • tests: Houses your test files (both feature tests and unit tests)

Other Important Files

  • .env (root directory): Stores environment variables (database credentials, API keys, etc.).
  • artisan (root directory): The command-line interface (CLI) for interacting with your Laravel application.
  • composer.json (root directory): Manages project dependencies.
  1. Middleware:
    • No longer have a dedicated directory in Laravel 11. They are part of the framework itself.
    • To apply middleware to routes, lets go ahead and do this.
  1. Creating a Custom Middleware

First create the profiles table: php artisan make: model Profile -m

Schema::create('profiles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('age');
            $table->string('phone_number');
            $table->string('address');
            $table->timestamps();
        });

Profile.php

protected $fillable = [
        'name',
        'age',
        'phone_number',
        'address', 
    ];

Run the

php artisan migrate

Create the Profile Factory class

Command:

php artisan make:factory ProfileFactory

ProfileFactory.php

public function definition(): array
    {
        return [
            'name' => $this->faker->name(),
            'age' => $this->faker->numberBetween(18, 100),
            'phone number' => $this->faker->phoneNumber(),
            'address' => $this->faker->address(),
        ];
    }

Create the Profile seeder

Command:

php artisan make:seeder ProfileSeeder
class ProfileSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */

    public function run()
    {
        \App\Models\Profile::factory(10)->create();
    }
}

Run the seeder:

Command:

php artisan db:seed --class=ProfileSeeder

Let’s create the ProfileController

Command:

php artisan make: controller ProfileController
<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Profile;

class MyProfileController extends Controller
{
    /**
     * Display a listing of the profiles.
     *
     * @return \Illuminate\Http\Response
     */

    public function index()
    {
        $profiles = Profile::all();
        return view('myprofile', ['profiles' => $profiles]);
    }
}

 

Profile View:

resources/views/myprofile.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
  <!-- Display the user's profile information -->
        {{-- 'name',
        'age',
        'phone number',
        'address', --}}
    <!--loop over the profiles table and display the above information-->
    @foreach ($profiles as $profile)
        <h1>{{ $profile->name }}</h1>
        <h2>{{ $profile->age }}</h2>
        <h3>{{ $profile->phone_number }}</h3>
        <h4>{{ $profile->address }}</h4>
    @endforeach
</body>
</html>

Update the Route

Route::get('/myprofile', [MyProfileController::class, 'index'])->name('myprofile');

 

Create a Custom Middleware and Apply to the Profile View:

Command:

php artisan make:middleware EnsureTokenIsValid

EnsureTokenIsValid.php

public function handle(Request $request, Closure $next): Response
    {
        $token = $request->input('token'); // Get 'token' from the request
        if ($token !== 'your_secret_token') {
            return redirect('/'); // Redirect to home if the token is invalid
        }
        return $next($request);
    }

Apply the Middleware to a Route

In your routes/web.php or routes/api.php file:

Route::get('/myprofile', [MyProfileController::class, 'index'])->middleware(EnsureTokenIsValid::class);

 

How to Test

Valid Token: Access the /protected-route with  the correct token appended as a query parameter (e.g., /myprofile?token=your_secret_token). You should see the protected content.

Invalid Token:  Try accessing the route without a token or with an incorrect token. You should be redirected to your homepage.

Global Middleware Registration: (bootstrap/app.php)

  • Global Middleware: The primary purpose is to apply middleware to all or a large subset of your application’s routes. This is common for middleware handling things like:
    • Authentication
    • CSRF Protection
    • Rate Limiting
    • API Token Verification
  • Organization: It centralizes middleware registration, improving code organization and maintainability.
->withMiddleware(function (Middleware $middleware) {
        $middleware->append(EnsureTokenIsValid::class);
    })

How It Works:

  1. The Closure: The withMiddleware closure receives an instance of the Middleware class.
  2. Registration: Inside the closure, you use methods like append() or prepend() on the Middleware instance to register your middleware.
  3. Request Flow: When a request enters your Laravel application, any middleware registered within the withMiddleware closure will be executed as part of the request pipeline.

Why Too Many Redirects:

The error “This page isn’t working 127.0.0.1 redirected you too many times” usually occurs when there’s a redirect loop. In your case, it seems like the `EnsureTokenIsValid` middleware is also applied to the `‘/’` route, either directly or indirectly.

When the token is invalid, the middleware redirects to `’/’`, but if the middleware is also applied to `‘/’`, it will keep redirecting to itself, causing the loop.

To solve this issue, you should ensure that the `EnsureTokenIsValid` middleware is not applied to the `’/’` route. If you have applied this middleware to all routes globally, you should remove it from the global middleware stack and only apply it to specific routes.

In this setup, the `EnsureTokenIsValid` middleware is only applied to the `/myprofile` route, and not to the `’/’` route, so there won’t be a redirect loop.

Middleware With Laravel breeze:

  • Use the middleware method in your route definitions.
  • Let’s install Laravel breeze for this.
    1. Installation:
composer require laravel/breeze --dev
php artisan breeze:install
  1. Database Migration:
php artisan migrate
  1. NPM Installation and Build:
npm install && npm run dev

       Breeze will provide you with:

  • Login, registration, password reset, email verification functionality.
  • Basic Blade-based views to start with. You can customize or replace these.

Accessing on the Browser

  1. Default Routes: Breeze adds routes for login, registration, etc., typically:
    • Registration: /register
    • Login: /login
    • You should be able to access these in your browser (e.g., http://127.0.0.1:8000/register )

Protecting the /profile Route

  1. Locate in Routes File: Find your /myprofile route definition in routes /web.php.
  2. Apply Middleware: Add the ‘auth’ middleware:
Route::middleware('auth')->group(function () {
    Route::get('/myprofile', [MyProfileController::class, 'index'])->name('myprofile');
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

 

Modified MyProfile Display with Tailwind:

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('Profile') }}
        </h2>
    </x-slot>
  <!-- Display the user's profile information -->
        {{-- 'name',
        'age',
        'phone number',
        'address', --}}
    <!--loop over the profiles table and display the above information-->
    <div class="container mx-auto py-8">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          @foreach ($profiles as $profile)
              <div class="bg-white rounded-lg shadow-md p-6">
                  <h1>{{ $profile->name }}</h1>
                  <h2 class="text-gray-600">{{ $profile->age }}</h2>
                  <h3 class="text-gray-600">{{ $profile->phone_number }}</h3>
                  <h4 class="text-gray-600">{{ $profile->address }}</h4>
              </div>
          @endforeach
        </div>
    </div>
</x-app-layout>

Missing Config Files In Laravel 11:

  • There are missing configuration files such as mail, queue, services, session and view. You can publish them using the following two commands
php artisan config:publish or

php artisan config:publish --all

Watch the YouTube Video:

Sign up for free tutorials in your inbox.

We don’t spam! Read our privacy policy for more info.

1 thought on “Laravel 11 Project Setup, Authentication, and Profile Display”

  1. Pingback: Real-Time Updates with Laravel 11 Reverb, Livewire 3, and Broadcasting - Webdev Trainee

Leave a Comment

Your email address will not be published. Required fields are marked *