3

I have a table tanks

+----+----------+-------+-------+
| id | capacity | model | width |
+----+----------+-------+-------+
|  1 |     1000 |    15 |   960 |
|  2 |    50000 |    30 |   200 |
|  3 |      100 |    15 |    12 |
|  4 |    80000 |    40 |   100 |
|  5 |     1000 |    30 |   123 |
|  6 |      500 |     5 |  1213 |
|  7 |     1000 |    22 |  2234 |
+----+----------+-------+-------+

And I added the unique property in my table

ALTER TABLE `tanks`
ADD UNIQUE `capacity_model_width` (`capacity`, `model`, `width`);

And my function to store values is like this

public function store(Request $request) {

        $image = new tank();

        $this->validate($request, [
                'capacity' => 'required|numeric',
                'model' => 'required|numeric',
                'width' => 'required|numeric',
            ]                
                );

        $image->capacity = $request->capacity;
        $image->model = $request->model;
        $image->width = $request->width;
        $image->save();

        return redirect()->route('tank.index')
                        ->with('success', 'Tank created successfully');
    }

Now when I insert below error shows

Integrity constraint violation: 1062 Duplicate entry 
'1000-22-2234' for key 'capacity_model_width'

I need to show the error message in my submit if they are unique. I am new to Laravel, How can add a custom validation and error message inside the store function

7
  • So are you concatenating the model width and capacity for the key? Commented Mar 22, 2017 at 11:14
  • There's a validatio rule unique. Commented Mar 22, 2017 at 11:14
  • @ChrisTownsend no concatenation for them Commented Mar 22, 2017 at 11:18
  • @AhmadRezk I know but it is not for two or more fields it doesn't works for me Commented Mar 22, 2017 at 11:19
  • So how did your key turn into '1000-22-2234' ? Commented Mar 22, 2017 at 11:22

3 Answers 3

2

Add this to your code

We are going to check to see if the fields we need exist first then we will concatenate them and add them to the request. From there we can now run our unique validation

public function store(Request $request) {
    $image = new tank();
    //Check to see if fields exist then validate after concatenation

    if(isset($request->capacity) && isset($request->model) && isset($request->width) ){
         $request->request->add(['my_key' => ['capacity' => $request->capacity, 'model' => $request->model, 'width' => $request->width] ]);
    }
    $this->validate($request, [
            'capacity' => 'required|numeric',
            'model' => 'required|numeric',
            'width' => 'required|numeric',
            'my_key' => 'required|uniqueCapacity',
        ]                
            );

    $image->capacity = $request->capacity;
    $image->model = $request->model;
    $image->width = $request->width;
    $image->save();

    return redirect()->route('tank.index')
                    ->with('success', 'Tank created successfully');
}

Adding a custom validator

Firstly access your AppServiceProvider and add the following

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('uniqueCapacity', function ($attribute, $value, $parameters, $validator) {
       $value_array = explode("-", $value);
        $items = DB::select("SELECT count(*) as aggregate FROM tanks WHERE capacity ='$value_array[0]' AND model='$value_array[1]' AND width='$value_array[2]' "); 
        $number=$items[0]->aggregate;
        if ($number > 0) {
            return false;
        } else {
            return true;
        }
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
Sign up to request clarification or add additional context in comments.

13 Comments

Another option is that you could automatically concatenate the fields in JavaScript in a hidden field. This can then be passed through the request
Column not found: 1054 Unknown column 'capacity_model_width' in 'where clause' (SQL: select count(*) as aggregate from tanks where capacity_model_width = 1000-22-2234)
Okay so that column doesn't actually exist in the table? It's just a rule?
Thanks it works with little bit modification on my own
Can you change the answer like this
|
0

Simple change in validation

this->validate($request, [
                'capacity' => 'required|email|unique:table_name',
                'model' => 'required|email|unique:table_name',
                'width' => 'required|email|unique:table_name',
            ]

1 Comment

Its for each one I need Three fields together
0

Add unique validation rule to capacity to be like that

$this->validate($request, [
            'capacity' => 'required|numeric|unique:tanks,capacity',
            'model' => 'required|numeric',
            'width' => 'required|numeric',
        ]                
            );

And you can Adding Additional Where Clauses

 Validator::make($request, [
'capacity' => Rule::unique('tanks')->where(function ($query) use $request {
$query->where('capacity', $request->input('capacity'))->where('width', $request->input('width'))->where('model', $request->input('model'));
})
]); 

laravel unique doc

1 Comment

Its for capacity only I need Three fields together

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.