I have to setup my authentication for my reservations system in Laravel.
The basic routing methods by Laravel and a lot of tutorials is by writing the function for the route inside the web.php like this Laraval example:
Route::get('/flights', function () {
// Only authenticated users may access this route...
})->middleware('auth');
However, I was told this isn't the best way to set up routing and that I should use a controller to manage routes. But that means I have to setup authentification methods inside the controller and to be honest, I don't have the vision to do this.. I thought I could do it like this (My Code)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Auth;
class PagesController extends Controller
{
public function home() {
return view('home');
}
public function reservations() {
return view('reservations')
->middleware(['auth']);
}
public function newreservations() {
return view('reservations_new');
}
}
combined with this web.php setup:
Route::get('/reservations.html', [PagesController::class, 'reservations']);
Route::get('/reservations.html/login', [AuthenticatedSessionController::class, 'create']);
Route::post('/reservations.html/login', [AuthenticatedSessionController::class, 'store']);
Route::get('/reservations_new.html', [PagesController::class, 'newReservations']);
but then I got the error: Method Illuminate\View\View::middleware does not exist.
So any tips/tricks/methods to do it the right way?
CodePudding user response:
There is no right or wrong way as long as you follow the same principal.
I personally do this:
Route::middleware('auth')->group(function () {
// Authenticated routes
});
you can check this extended discussion
also if you want to use middlewares in controller, this is the right way
class UserController extends Controller
{
/**
* Instantiate a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('log')->only('index');
$this->middleware('subscribed')->except('store');
}
}
CodePudding user response:
Thanks to PJB I got the right solution
I wanted to implement the middleware module inside my controller but it could simply be done by changing the route to:
Route::get('/reservations', [PagesController::class, 'reservations'])->middleware('auth');