在laravel

时间:2016-09-06 02:19:13

标签: php model-view-controller laravel-5

尝试学习laravel。

我有一个发布到此路线的用户表单

Route::post('users/add','usersController@store')->middleware('admin');

usersController中的store函数调用另一个名为validateForm的函数,该函数基本上验证了表单的输入,如下所示

class usersController extends Controller
{
/*
 *Store a user in database
*/
function store(){
    $input=Request::all();

    // create the validation rules ------------------------
    $rules = array(
    'name'             => 'required',                        // just a normal required validation
    'lastname'         => 'required',                        // just a normal required validation
    'email'            => 'required|email|unique:users',     // required and must be unique in the users table
    'password'         => 'required',

    );
    $validationResponse=$this->validateForm($input,$rules);

    if($validationResponse=="passed"){


        $user=new \App\User;   
        $user->name=$input['name'];
        $user->email=$input['email'];
        $user->lastname=$input['lastname'];
        $user->password=\Hash::make($input['password']);
        $user->userlevel=isset($input['isAdmin'])?1:0;
        $user->save();

        return redirect('users');
}
else{
        return Redirect::to('users/create')
        ->withErrors($validationResponse)->withInput();


     }


   }

/*
*validate user form input
*/
function validateForm($input,$rules){

         // do the validation ----------------------------------
         // validate against the inputs from our form
        $validator = Validator::make($input, $rules);

        // check if the validator failed -----------------------
        if ($validator->fails()) {

            // get the error messages from the validator
            $messages = $validator->messages();

            return $messages;
        } 
        else{
            return 'passed';
        }
    }
}

现在这可以从userController访问,但是如果我有另一个控制器说projectController并且我想访问相同的功能,即validateForm

我应该放置这个常用功能,如何从任何控制器访问它?

1 个答案:

答案 0 :(得分:0)

Laravel建立的答案是Form Request

只需使用php artisan make:request UserCheck创建表单请求,然后在方法rules

中输入验证规则
/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */

public function rules() {
    return [
       'name'             => 'required',                        // just a normal required validation
       'lastname'         => 'required',                        // just a normal required validation
       'email'            => 'required|email|unique:users',     // required and must be unique in the users table
       'password'         => 'required',

    ]; }

并称之为

/*
 * Store a user in database
 */
public function store(UserCheck $request)
{
    // The incoming request is valid...
}