在添加laravel 4.2之前,检查数据库中是否已存在名称

时间:2015-09-19 08:31:13

标签: php database laravel-4

Laravel 4.2新手在这里!我的控制器中有这个代码

public function store()
{
    //
    $rules = array(
        'name'   => 'required|min:2|max:20|regex:/^[a-zA-Z0-9\-\s]+$/',
        'stock'  => 'required|numeric|min:1',
        'origin' => 'required|min:5|max:200'
    );
    $validator = Validator::make(Input::all(), $rules);

    // process the login
    if ($validator->fails()) {
        return Redirect::to('weapons/create')
            ->withErrors($validator)
            ->withInput(Input::except('password'));
    } else {
        // check first if the name exists already then store
        $weapon = new Weapon;
        $weapon->name   = Input::get('name');
        $weapon->stock  = Input::get('stock');
        $weapon->origin = Input::get('origin');
        $weapon->save();

        // redirect
        Session::flash('message', 'Successfully created nerd!');
        return Redirect::to('create');
    }
}

我需要检查数据库中是否已存在该名称;我怎样才能做到这一点?

我可以在控制器内声明一个新功能吗?请帮忙。

1 个答案:

答案 0 :(得分:2)

您可以在规则中验证:

 $rules = array(
    'name'   => 'required|min:2|max:20|regex:/^[a-zA-Z0-9\-\s]+$/|exists:TableName,name',
    'stock'  => 'required|numeric|min:1',
    'origin' => 'required|min:5|max:200'
);