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'
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大