I have been doing a project right now. In this I am stuck. All I want that to ignore soft delete of laravel in my validation that has unique column of name, parent_id.
For example : Suppose A & B is category. I want that If C is a subcategory of A then no other C data is not written in A. But C can be written in B category.
I also want that If a User SoftDeletes the data then he can insert same data with the same name and with the same category.
My Table is
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('parent_id')->nullable()->default(0);
$table->integer('admin_id')->nullable()->default(0);
$table->boolean('active')->nullable()->default(1);
$table->unique(array('parent_id', 'name', 'deleted_at'));
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
My Store method is
public function store(Request $request)
{
$this->validate($request, [
'category' => 'required|unique:categories,parent_id,NULL,name,NULL,id,deleted_at,NULL',
'parent' => 'required',
'_token' => '',
]);
try {
$category = New Category();
$category->name = $request['category'];
$category->parent_id = $request['parent'];
$category->remember_token = $request['_token'];
$category->save();
$request->session()->flash('alert-success', 'Sub Category Successfully Created!');
return redirect('subcategory');
} catch(\Illuminate\Database\QueryException $e) {
return redirect()->back()
->with('status','<strong>'.$category.' already exist!</strong>');
}
}
My model is
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Category extends Model
{
use Notifiable;
use SoftDeletes;
protected $fillable = [
'category',
];
protected $dates = ['deleted_at'];
}
The Error is
Try
‘category' => 'required|unique:categories,parent_id,NULL,id,deleted_at,NULL,name,’.$request['category'],
For more details, separate the parameters into pairs:
[categories, parent_id]
categories
, column parent_id
. If the position of parent_id is same with the left “category”, it can be ignore. E.g
‘name’ => ‘unique:products,name’ can be simplified to
‘name’ => ‘unique:products’.
[NULL, id]
[deleted_at, NULL]
Therefore, the final scope to implement the unique rule is the results get from below query:
Select count(*) from categories
where id is not null
and deleted_at is null
and name is ??$request['category']??
If the count(*) is 0, then the validation get through. Otherwise, fail.
You can have as many constraints as you need after the third pair. such as:
=> 4. [active, true]
=> 5. [name, hello], you can use '!hello' to mean where the name is not 'hello'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With