1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravelの初期セットアップ&認証機能のインストール&自動ログインの遷移先変更

Last updated at Posted at 2025-08-09

Laravel11以降のアップデートに対応した、Breezeの自動ログイン時の遷移先の変更方法が意外となかったので記事にしました。Laravelの初期セットアップと合わせて記載しました。

新規Laravelプロジェクトの作成&セットアップ

1. 新規プロジェクトを作成

  • 適切なファイルパスで実行
composer create-project laravel/laravel (プロジェクト名)
cd (プロジェクト名)

2. MySQLに (プロジェクト名) データベースを作成する

CREATE DATABASE (プロジェクト名) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

3. .env の環境設定

  • .envファイルを開いて、MySQL接続情報を設定:
.env
DB_CONNECTION=mysql
DB_HOST=your_host
DB_PORT=your_port
DB_DATABASE=プロジェクト名
DB_USERNAME=your_mysql_user
DB_PASSWORD=your_mysql_password

4. 🧱標準セットアップを実行

composer install
php artisan key:generate

5. Storageへのパスを通しておく

php artisan storage:link

6. .envファイルの防御

.envファイルと同じディレクトリ(プロジェクト直下)に以下の.htaccessを作成する。

.htaccess
<Files .env>
    deny from all
</Files>

認証機能のインストール&自動ログインの遷移先変更

認証機能(Laravel Breezwのインストール)

composer require laravel/breeze --dev
php artisan breeze:install blade
npm install
php artisan migrate

ミドルウェアを作成

php artisan make:middleware RedirectIfAuthenticated

生成された app/Http/Middleware/RedirectIfAuthenticated.php を編集

RedirectIfAuthenticated.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next, string ...$guards)
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
                // 遷移させたいページへ
                return redirect()->route('遷移させたいルート');
            }
        }

        return $next($request);
    }
}

bootstrap/app.php に登録

app.php
->withMiddleware(function ($middleware) {
    $middleware->alias([
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    ]);
})

routes/auth.php の guest ミドルウェアが自動的にこの新しい動きになる

auth.php
Route::middleware('guest')->group(function () {
    // ログイン・登録ルートなど
});

エラーメッセージの日本語化

composer require --dev laravel-lang/lang
php artisan lang:update

関連リンク

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?