doushi1510 2015-07-25 09:57
浏览 60
已采纳

Laravel Eloquent验证插入异常?

I've created a form which adds a category of product in a Categories table (for example Sugar Products or Beer), and each user has their own category names.

The Categories table has the columns id, category_name, userId, created_At, updated_At.

I've made the validation and every thing is okay. But now I want every user to have a unique category_name. I've created this in phpMyAdmin and made a unique index on (category_name and userId).

So my question is this: when completing the form and let us say that you forgot and enter a category twice... this category exist in the database, and eloquent throws me an error. I want just like in the validation when there is error to redirect me to in my case /dash/warehouse and says dude you are trying to enter one category twice ... please consider it again ... or whatever. I am new in laravel and php, sorry for my language but is important to me to know why is this happens and how i solve this. Look at my controller if you need something more i will give it to you.

class ErpController extends Controller{
public function __construct()
{
    $this->middleware('auth');
}

public function index()
{
    return view('pages.erp.dash');
}

public function getWarehouse()
{
    $welcome = Auth::user()->fName . ' ' . Auth::user()->lName;
    $groups = Group::where('userId',Auth::user()->id)->get();
    return view('pages.erp.warehouse', compact('welcome','groups'));


}

public function postWarehouse(Request $request)
{
    $input = \Input::all();
    $rules = array(
        'masterCategory' => 'required|min:3|max:80'
    );
    $v = \Validator::make($input, $rules);
    if ($v->passes()) {
        $group = new Group;
        $group->group = $input['masterCategory'];
        $group->userId = Auth::user()->id;
        $group->save();
        return redirect('dash/warehouse');
    } else {
        return redirect('dash/warehouse')->withInput()->withErrors($v);
    }

}
}

展开全部

  • 写回答

1条回答 默认 最新

  • douxugu5836 2015-07-25 14:18
    关注

    You can make a rule like this:

    $rules = array(
        'category_name' => 'unique:categories,category_name'
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部