TransWikia.com

Using Unique in Laravel

Stack Overflow Asked by xtremeCODE on December 7, 2021

I am building a Book Portal with Laravel. I have a unique validation rule on name to books.

    $request->validate([
        'name' => 'required|unique:books',
        'about' => 'required',
        'dsecription' => 'required',
        'image' => 'required|mimes:jpeg,bmp,jpg,png|between:1, 6000',
        'author_id' => 'required',
        'publisher' => 'required',
        'recommended' => 'required',
        'epub_url' => 'required',
        'year'=> 'required',
        'pages' => 'required',
    ]);

I found out that an Author can have the same book name. Using unique on the name, will not allow me to upload.

I am thinking, if there is a way, I can check the author and the name of the book i.e

Check if the author has the same name, then apply the unique rule on name else upload.

2 Answers

You can try using the extra where conditions that can be passed to the unique rule to apply the unique constraint under certain conditions:

// we will make sure 'author_id' is an existing value
'author_id' => 'bail|required|integer|exists:authors,id',
'name' => [
    'bail',
    'required',
    Rule::unique('books')
        ->where('author_id', (int) $request->input('author_id')),
],

Assuming author_id is on the books table.

Laravel 7.x Docs - Validation - Rules - unique

Answered by lagbox on December 7, 2021

I didn't find any solution for this. That's why I made my own custom validation like this :

$request->validate([
   'name' => 'required|unique:books',
   'author_id' => 'required',
  // ...
]);

$data = Book::where('author_id', $request->author_id)->where('name', $request->name)->first();

if(!empty($data)) {
   return redirect()->back()->withErrors('This name already taken'); // error message
}

Answered by sta on December 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP