简体   繁体   中英

Laravel Eloquent validation insert exception?

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);
    }

}
}

You can make a rule like this:

$rules = array(
    'category_name' => 'unique:categories,category_name'
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM