Laravel 5 Basics (Twelve) - Certification
Laravel is shipped with a user authentication system. Let’s take a look at routes.php
. If deleted, add:
<code>Route::controllers([ 'auth' => 'Auth\AuthController', 'password' => 'Auth\PasswordController' ]);</code>
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.
The actual registration of 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.
In fact trait
is 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
:
<code>use AuthenticatesAndRegistersUsers;</code>
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.
<code> public function redirectPath() { if (property_exists($this, 'redirectPath')) { return $this->redirectPath; } //如果用户设置了 redirectTo 属性,则跳转到用户设置的属性,否则到home return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home'; } </code>
OK, we know, just set the redirectTo
attribute to customize the jump after registration. We modified in AuthAuthContotroller
:
<code> protected $redirectTo = 'articles';</code>
We start by using /auth/logout
to make sure we log out, don’t be afraid if something goes wrong, we don’t have a default homepage, revisit: 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:
<code> 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'); }</code>
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:
<code> public function create() { if (Auth::guest()) { return redirect('articles'); } return view('articles.create'); }</code>
The above code can work, 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 are doing by their names. Check them carefully. 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 routes, and you must explicitly declare that you want to use one or more of these middlewares.
Suppose we want to protect the entire ArticlesController
, we add middleware directly in the constructor:
<code> public function __construct() { $this->middleware('auth'); }</code>
Now, any method is 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:
<code> public function __construct() { $this->middleware('auth', ['only' => 'create']); //当然可以反过来 //$this->middleware('auth', ['except' => 'index']); }</code>
We don’t have to introduce middleware in the constructor of the controller, we can declare it directly in the route:
<code>Route::get('about', ['middleware' => 'auth', 'uses' => 'PagesController@about']);</code>
The system middleware provided in kernel.php
, such as 'IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode'
, can allow 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 do it on the command line Processing, take a look at the work of this middleware:
<code>php artisan down</code>
Visit the website and you can see that any URL request will be returned immediately. Website online:
<code>php artisan up</code>
Let’s make our own middleware:
<code> php artisan make:middleware Demo</code>
Then add the code:
<code> public function handle($request, Closure $next) { //如果请求中含有 foo,我们就回到控制器首页 if ($request->has('foo')) { return redirect('articles'); } return $next($request); }</code>
If you want to use middleware for all requests, you need to register it in $middleware
in kernel.php
:
<code> protected $middleware = [ ... 'App\Http\Middleware\Demo', ];</code>
Now we can test it, let’s say we visit /articles/create?foo=bar
and we are redirected to the home page.
Let’s get rid of this display middleware and let’s create a middleware that actually works. Suppose we want to protect a page. This page must be accessible by administrators.
<code>php artisan make:middleware RedirectIfNotAManager</code>
Let’s add the processing code:
<code> public function handle($request, Closure $next) { if (!$request->user() || !$request->user()->isATeamManager()) { return redirect('articles'); } return $next($request); }</code>
Modify our model below:
<code> public function isATeamManager() { return false; }</code>
For simplicity, we return false directly. This time we place the middleware in $routeMiddleware
in kernel.php
.
<code> protected $routeMiddleware = [ ... 'manager' => 'App\Http\Middleware\RedirectIfNotAManager', ];</code>
Let’s make a test route to test it:
<code>Route::get('foo', ['middleware' => 'manager', function() { return 'This page may only be viewed by manager'; }]);</code>
guest identity access or login identity access will return to the homepage, but if you modify isATeamManager()
to return true
, login identity access can see the returned information.
The above introduces the basics of Laravel 5 (Twelve) - Certification, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

The Chinese meaning of request is "request". It is a global variable in PHP and is an array containing "$_POST", "$_GET" and "$_COOKIE". The "$_REQUEST" variable can obtain data and COOKIE information submitted by POST or GET.

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

How to use the urllib.request.urlopen() function in Python3.x to send a GET request. In network programming, we often need to obtain data from a remote server by sending an HTTP request. In Python, we can use the urllib.request.urlopen() function in the urllib module to send an HTTP request and get the response returned by the server. This article will introduce how to use

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

In modern software development, identity authentication is a very important security measure. Auth0 is a company that provides identity authentication services. It can help developers quickly implement multiple identity authentication methods (including OAuth2, OpenIDConnect, etc.) and provide safe and reliable authentication services. In this article, we will introduce how to use Auth0 for authentication in JavaAPI development. Step 1: Create an Auth0 account and register the application. First, we need to

1. Create a new file called request.js and import Axios: importaxiosfrom'axios'; 2. Create a function called request and export it: This will create a function called request and export it Set up a new Axios instance with a base URL. To add timeout settings in a wrapped Axios instance, you can pass the timeout option when creating the Axios instance. exportconstrequest=axios.create({baseURL:'https://example.

Introduction Supabase is a self-proclaimed "open source Firebase alternative". I've been interested in working with Supbase for a while and thought I'd try using their authentication API to set up authentication for a Vue.js3 application. First of all, why should you use SupabaseAuth? The bottom line is that if you're using Supabase as your data store, (which has some pretty sweet benefits), SupabaseAuth is the only way you can manage access to that data. Secondly, although SupabaseAuth also has many different functions. User permissions without middleware (row-level security via Postgres)
