Laravel使用Auth中间件强制用户登录

具体情景为后台的添加文章需要登录后才有权限操作,未登录用户通过url地址访问跳转至登录页

  • 1.在app/Http/Controllers/StudentsController.php中使用中间件
public function __construct()
{
      $this->middleware('auth', [
      // 添加例外(未登录也可以访问,其他的默认不能访问)
      'except' => ['index', 'show']
      ]);
}
  • 2.或者在routes/web.php中使用中间件组(和上面的效果一样)
Route::group(['middleware' => 'auth'], function () {
    Route::get('/students', 'StudentsController@index')->name('students.index');
    Route::get('/students/create', 'StudentsController@create')->name('students.create');
    Route::get('/students/{student}', 'StudentsController@show')->name('students.show');
    Route::post('/students', 'StudentsController@store')->name('students.store');
    Route::get('/students/{student}/edit', 'StudentsController@edit')->name('students.edit');
    Route::put('/students/{student}', 'StudentsController@update')->name('students.update');
    Route::delete('/students/{student}', 'StudentsController@destroy')->name('students.destroy');
});
  • 跳转至登录页后登录成功后跳转回上一页,如没有上一页则跳转默认至students.index
return redirect()->intended('students.index')->with('success', '登录成功');

你可能感兴趣的:(Laravel使用Auth中间件强制用户登录)