doushi1510 2015-07-25 17: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 22:18
    关注

    You can make a rule like this:

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

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改