Sure! Here's an example of how you can create a login form for an admin in Laravel:
First, you need to create a route to handle the login form and the authentication process. You can define the route in your
routes/web.php file:
PHP:
Route::get('/admin/login', 'AdminController@showLoginForm')->name('admin.login');
Route::post('/admin/login', 'AdminController@login')->name('admin.login.submit');
Route::get('/admin', 'AdminController@admin')->name('admin.home');
Next, create a controller named
AdminController using the following command:
Bash:
php artisan make:controller AdminController
Then, in the
AdminController controller, you can define the
showLoginForm,
login, and
admin methods as follows:
PHP:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
class AdminController extends Controller
{
public function showLoginForm()
{
return view('admin.login');
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended(route('admin.home'));
} else {
return back()->withInput()->withErrors(['email' => 'Invalid email or password']);
}
}
public function admin()
{
return view('admin.home');
}
}
In the
showLoginForm method, we return the view for the login form. In the
login method, we attempt to authenticate the user with the provided credentials. If successful, the user is redirected to the admin page; otherwise, an error message is displayed.
Next, create a view for the login form at
resources/views/admin/login.blade.php:
HTML:
<form method="POST" action="{{ route('admin.login.submit') }}">
@csrf
<input type="email" name="email" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
Finally, create a view for the admin page at
resources/views/admin/home.blade.php. This can be your admin dashboard page.
Make sure to update your database configuration in the
.env file with your database credentials.
This is a basic example to get you started. You can further enhance it by adding validation, error handling, and improving the UI.