我在Laravel 8中遇到了一些身份验证中间件问题。目前,当我运行测试时,我会得到错误SymfonyComponentRoutingExceptionRouteNotFoundException: Route [login] not defined
。
我已经安装了jetstream
和livewire
,可以在我的routes
文件夹中看到它们。我的测试应该重定向到login
,因为没有用户登录。我认为这是middleware('auth')
不能到达它需要的地方的问题,但我找不到任何关于如何解决它的信息。
这是我的测试:
<?php
namespace TestsFeature;
use AppModelsProject;
use AppModelsUser;
use IlluminateFoundationTestingRefreshDatabase;
use IlluminateFoundationTestingWithFaker;
use TestsTestCase;
class ProjectsTest extends TestCase
{
use WithFaker, RefreshDatabase;
/** @test */
public function only_authenticated_users_can_create_projects()
{
$this->withoutExceptionHandling();
$attributes = Project::factory()->raw();
$this->post('/projects', $attributes)->assertRedirect('login');
}
}
路由
<?php
use IlluminateSupportFacadesRoute;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/projects', 'ProjectsController@index')->middleware('auth');
Route::get('/projects/{project}', 'ProjectsController@show');
Route::post('/projects', 'ProjectsController@store')->middleware('auth');
Route::get('/home', [AppHttpControllersHomeController::class, 'index'])->name('home');
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
项目控制器
<?php
namespace AppHttpControllers;
use AppModelsProject;
use AppModelsUser;
class ProjectsController extends Controller
{
public function index()
{
//Return all projects. Compact creates an array made up of both variables and values.
$projects = auth()->user()->projects;
return view('projects.index', compact('projects'));
}
public function show(Project $project)
{
//Get the wildcard no passed in as a reference and search for it in Project. If it doesn't exist, fail.
return view('projects.show', compact('project'));
}
public function store()
{
//validate - check for title/description
$attributes = request()->validate([
'title' => 'required',
'description' => 'required',
]);
//Use middleware to check owner is logged in and then pass in project
auth()->user()->projects()->create($attributes);
//redirect - return a new view
return redirect('/projects');
}
}
我在使用livewire和加固时遇到了同样的问题。解决方案是有一个命名的登录路径
Route::get('login', AppHttpLivewireLogin::class)->name('login');
我最近遇到了同样的问题。阅读此处的文档后解决问题
检查路线是否有效并包含:
$ php artisan route:list
然后
$ php artisan route:cache