Laravel 4 - Access Auth Class in Validation Class

我是研究僧i 提交于 2019-12-10 22:34:11

问题


I want to access the Auth Class within my ValidatorService Class.

namespace Services\Validators\User;

use \Services\Validators\Validator;

use \Illuminate\Support\Facades\Auth;

class Edit extends Validator {

    public static $rules = [
        'email' => 'required|unique:users,email,'.Auth::user()->id
    ];
}

I tried to use the \Illuminate\Support\Facades\Auth Namespace, but laravel throws an Exception.

Error: syntax error, unexpected '.', expecting ']'

Laravel only throws the exception, when I try to use Auth::user()->id. If I remove Auth::user()->id and add a number, for example 1, it works.

I also tried to implement the Illuminate\Auth\UserInterface but it is not working.

How can I use the Auth Class in my ValidatorService Class?

EDIT: Problem solved -> Scroll down.


回答1:


Solution:

You cannot use functions or variables when setting a variable on a class.

Thanks to AndreasLutro on http://laravel.io/irc

So I removed the class variable and added a method. Now everythings works fine.

Code:

class Edit extends Validator{

    public static function rules(){

        return array(

            'email' => 'required|unique:users,email,'.Auth::user()->id

        );
    }
}

Cheers, Steven.




回答2:


Try to surround the 'required|unique:users,email,'.Auth::user()->id part with ( and ) so that it looks like this:

public static $rules = [
    'email' => ('required|unique:users,email,' . Auth::user()->id)
];


来源:https://stackoverflow.com/questions/21207738/laravel-4-access-auth-class-in-validation-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!