To achieve login via a URL in a Laravel application using Filament, you can create a custom route that accepts the code from the URL, validates it, and logs the user in. Here’s a step-by-step solution:
-
Create a Route: Define a route in your
web.phpfile that will handle the login via URL.// routes/web.php use App\Http\Controllers\Auth\LoginController; Route::get('/login/{code}', [LoginController::class, 'loginWithCode']); -
Create a Controller Method: In your
LoginController, create a methodloginWithCodethat will handle the login logic.// app/Http/Controllers/Auth/LoginController.php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Models\User; class LoginController extends Controller { public function loginWithCode($code) { // Find the user by the code $user = User::where('login_code', $code)->first(); if ($user) { // Log the user in Auth::login($user); // Redirect to the intended page or dashboard return redirect()->intended('/dashboard'); } // If the code is invalid, redirect to the login page with an error return redirect('/login')->withErrors(['code' => 'Invalid login code.']); } } -
Add a Login Code to Users: Ensure that your
Usermodel has alogin_codefield. You might need to add this field to your users table.// database/migrations/xxxx_xx_xx_xxxxxx_add_login_code_to_users_table.php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddLoginCodeToUsersTable extends Migration { public function up() { Schema::table('users', function (Blueprint $table) { $table->string('login_code')->nullable()->unique(); }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('login_code'); }); } } -
Generate Login Codes: You need a way to generate and assign login codes to users. This can be done when creating a user or through a separate process.
// Example of generating a login code use Illuminate\Support\Str; $user->login_code = Str::random(10); $user->save(); -
Secure the Login Code: Ensure that the login code is secure and not easily guessable. Using
Str::random(10)generates a random 10-character string which should be sufficiently secure for most applications.
By following these steps, you can bypass the traditional login form and allow users to log in directly via a URL containing a unique code.