Table of Contents
Laravel 5 framework learning user authentication, laravel5 framework authentication
Home Backend Development PHP Tutorial Laravel 5 framework learning user authentication, laravel5 framework authentication_PHP tutorial

Laravel 5 framework learning user authentication, laravel5 framework authentication_PHP tutorial

Jul 13, 2016 am 09:57 AM
laravel framework php User Authentication

Laravel 5 framework learning user authentication, laravel5 framework authentication

Laravel has been shipped with a user authentication system. Let’s take a look at routes.php. If deleted, add it :

Route::controllers([
  'auth' => 'Auth\AuthController',
  'password' => 'Auth\PasswordController'
]);
Copy after login

You can use php artisan route:list to check it out. Visit /auth/login in the browser and you will see the login interface. It is best to comment out the things about google in the system default app.blade.php, otherwise you will go crazy.

You can use register, login or even forget password.

Actually registering a user failed after submission. In fact, it did not fail, but larave automatically jumped to /home. We have deleted this controller. You can use tinker to see if the user has been created.

Trait is actually used in AuthAuthController, what is triat? Well, PHP only supports single inheritance, and traits were added in PHP5.4. A trait is actually an encapsulation of a set of methods, and you can include it in another class. Like an abstract class, you cannot instantiate it directly.

There is a reference to the trait in AuthAuthController:

Copy code The code is as follows:
use AuthenticatesAndRegistersUsers;

Let’s find him and see how he jumps after registration. He is hidden quite deep in vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesAndregistersUsers.php, wow.

 public function redirectPath()
 {
 if (property_exists($this, 'redirectPath'))
 {
  return $this->redirectPath;
 }
    
    //如果用户设置了 redirectTo 属性,则跳转到用户设置的属性,否则到home
 return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
 }
Copy after login

OK, we know, just set the redirectTo attribute to customize the jump after registration. We modify it in AuthAuthContotroller:

Copy code The code is as follows:
protected $redirectTo = 'articles';

Let’s use /auth/logout first to make sure we log out. Don’t be afraid if something goes wrong, we don’t have a default homepage. Re-visit: auth/register to create a new user. This time it should be ok.

Logout again, and then use login to log in.

Now we can delete the temporarily set hidden fields in form_partial and modify the controller:

  public function store(Requests\ArticleRequest $request) {
    //你可以这样
    //$request = $request->all();
    //$request['user_id'] = Auth::id();

    //更简单的方法
    $article = Article::create($request->all());
    //laravel 自动完成外键关联
    Auth::user()->articles()->save($article);

    return redirect('articles');
  }

Copy after login

Add an article and check it out using tinker.

Middleware
Of course we don't want anyone to be able to publish articles, at least only by logging in. We add protection in the controller:

  public function create() {
    if (Auth::guest()) {
      return redirect('articles');
    }
    return view('articles.create');
  }
Copy after login

The above code works, but there is a problem. We need to perform the above processing in every method that needs to be protected. This is too stupid. Fortunately, we have middleware.

Middleware can be understood as a processing pipeline. The middleware processes at a certain moment in the pipeline. This moment can be a request or a response. Depending on the processing rules of the middleware, the request may be redirected or passed.

There are three middlewares included in app/http/middleware. You can tell what they do by their names. Take a closer look. Note that Closure $next represents the next middleware.

Register the middleware in app/http/kernel.php. The $middleware section declares middleware that processes all http, $routeMiddleware only processes routing, and you must explicitly declare to use one or more of these middlewares.

Suppose we want to protect the entire ArticlesController, we add middleware directly in the constructor:

  public function __construct() {
    $this->middleware('auth');
  }
Copy after login

Every method is now protected.

But we probably don’t want the entire controller to be protected, what if it’s just one or two of its methods? We can handle it like this:

  public function __construct() {
    $this->middleware('auth', ['only' => 'create']);
    //当然可以反过来
    //$this->middleware('auth', ['except' => 'index']);
  }
Copy after login

We don’t have to introduce middleware in the constructor of the controller, we can declare it directly in the route:

Copy code The code is as follows:
Route::get('about', ['middleware' => 'auth', 'uses' => 'PagesController@about']);

The system middleware provided in kernel.php, such as 'IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode', allows us to enter maintenance mode. For example, the system is online, but now it needs to be temporarily shut down for a period of time for processing. We can process it on the command line. Take a look at this middleware in action:

Copy code The code is as follows:
php artisan down

Visit the website and you can see that any URL request will be returned immediately. Website online:

Copy code The code is as follows:
php artisan up

Let’s make our own middleware:

Copy code The code is as follows:
php artisan make:middleware Demo

Then add the code:

 public function handle($request, Closure $next)
 {
    //如果请求中含有 foo,我们就回到控制器首页
    if ($request->has('foo')) {
      return redirect('articles');
    }

 return $next($request);
 }

Copy after login

If you want to use middleware for all requests, you need to register it in $middleware in kernel.php:

 protected $middleware = [
 ...
 'App\Http\Middleware\Demo',

 ];

Copy after login

Now we can test it, let’s say we visit /articles/create?foo=bar and we are redirected to the homepage.

Let’s get rid of this display middleware and let’s create a middleware that is actually useful. Suppose we want to protect a page. This page must be accessible by administrators.

Copy code The code is as follows:
php artisan make:middleware RedirectIfNotAManager

Let’s add the processing code:

 public function handle($request, Closure $next)
 {
    if (!$request->user() || !$request->user()->isATeamManager()) {
      return redirect('articles');
    }

 return $next($request);
 }

Copy after login

下面修改我们的模型:

  public function isATeamManager() {
    return false;
  }
Copy after login

简单起见,我们直接返回false。这次我们把中间件放置在 kernel.php 中的$routeMiddleware 中。

 protected $routeMiddleware = [
 ...
 'manager' => 'App\Http\Middleware\RedirectIfNotAManager',
 ];
Copy after login

我们做一个测试路由测试一下:

Route::get('foo', ['middleware' => 'manager', function() {
  return 'This page may only be viewed by manager';
}]);
Copy after login

guest身份访问或者登录身份访问都会返回主页,但是如果修改 isATeamManager() 返回 true,登录身份访问可以看到返回的信息。

以上就是本文所述的全部内容,希望对大家熟悉Laravel5框架能够有所帮助。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/981353.htmlTechArticleLaravel 5框架学习之用户认证,laravel5框架认证 Laravel 出厂已经带有了用户认证系统,我们来看一下 routes.php,如果删除了,添加上: Route::...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles