laravel-cms登录功能(表单验证)

现在我们点击登录提交数据到后台了,但是,这些伟过来的数据是否正确呢?这就需要我们的表单验证了。

php artisan make:request LoginRequest
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class LoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            // 
            'username'=>'required',
            'password'=>'required'
        ];
    }

    public function messages()
    {
        return [
            'username.required'=>':attribute 不能为空',
            'password.required'=>':attribute 不能为空'
        ];  
    }

    public function attributes()
    {
        return [
            'username'=>'用户名',
            'password'=>'密码'
        ];
    }
}

注:查看我们生成的LoginRequest.php文件,这里我们把authorized这个方法里的返回设为true,这里是用来验证某些用户是否可以执行某个操作的判断的地方,有的时候,我们的某个操作只能是某些特定用户才能操作,那么我们就可以在这里写上判断逻辑,返回true表示能操作,返回false表示不能操作,由于我们这里是登录,所以,返回true;

rules方法里返回我们登录时需要的那些字段,username,password,这些是form表单传递过来的数据,requried是laravel为我们提供的验证方法,表示必须传这两个值,还有nullable表示是否为空,可以通过 | 分割符来链接,比如: 'username'=>'required|nullable'表示必传,可为空,哈哈,这只是说明啊,千万别这么写,太怪了,你也可以自定义规则,

php artisan make:rule TestRule

这个大家可以看手册上。

messages方法,里面是不满足某个条件时,返回给用户的提示文字,比如“username.required”=>'':attribute 不能为空',当你没有传递username的时候,会返回 ‘用户名不能为空’,这个:attribute是啥?这个就是我们下面的 attributes 方法里写的,默认会是当前的提交的字段 username,通过这个attributes方法,我们把username改成中文‘用户名’。

然后我们改一下上面的LoginController.php这个控制器

<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
    //
    public function index()
    {
        return view("admin.login");
    }
    public function loginAct(LoginRequest $request){
        dd($request);
    }
    public function logout(){

    }
}

注:看下这个loginAct方法里的 LoginRequest,当我们点击提交的时候,会自动在这里验证,就不用我们去手写验证逻辑了。

我们再看我们之前的login.blade.php

@error('username')
       {{ $message }}
@enderror

注:这是laravel为我们提供的模板判断错误消息方法,如果username有错,会通过 $message把错误显示出来。

这里还有一个很重要的东西,@cstf 这是laravel为我们提供的默认生成token的方法,因为,每个post请求laravel都需要一个token避免重复提交,这个也是可以取消的,但是,不提倡取消。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章