laravel 7 Validation unique multiple columns - laravel

how to viladate multiple columns
table name "exam_starts"
columns
id
exam_id
exam_multi_id
student_id
exam_class_id
exam_code_id
Status
class Student extends Model
{
// exam
public function exams(){
return $this->belongsToMany('App\Exam','exam_starts','student_id','exam_id')
->withPivot(['id','exam_multi_id','exam_class_id','exam_code_id','Attend','pass','Status'])-
>withTimestamps();
}
}
how to unique columns student_id and exam_class_id in table exam_starts ?
My Try in controller
class ExamClassController extends Controller
{
$this->validate($request, [
'exam_class_id' => [
'required',
'integer',
'unique:exam_startss,exam_class_id,'.$request->exam_class_id .',student_id' ,
],
'student_id' => 'bail|required|integer',
'exam_start_id' => 'bail|required|integer',
'exam_id' => 'bail|required|integer',
'exam_multi_id' => 'bail|required|integer',
'code' => 'nullable|string',
'student' => 'bail|required|string',
]);
}
this mysql resulte
(SQL: select count(*) as aggregate from `exam_starts` where `exam_class_id` = 1 and `student_id` <> 1)

Use Unique rule class and you can pass multiple wheres to it, to make an unique constraint that takes two columns.
(new Unique('exam_starts'))
->where('student_id ', $request->student_id)
->where('exam_class_id', $request->exam_class_id);
Set it into validation like so
'exam_class_id' => [
'required',
'integer',
(new Unique('exam_starts'))
->where('student_id ', $request->student_id)
->where('exam_class_id', $request->exam_class_id),
],

Related

Laravel | three fields combination Valdiation

How to do a 3 fields combination validation?
I have this table merchant_product, the table has 4 columns :
id
merchant_id
product_id
branch_id
I don't want the same row duplicated like this when storing data.
Example :
id
merhcant_id
product_id
branch_id
1
1
1
1
2
1
1
1
I tried this approach but it seems not to work.
Here is my sample validation method :
$rules = [
'product_id' => ['required','unique:merchant_product,product_id,NULL,id,merchant_id,'.Auth::id()', new Varchar],
'merchant_id' => [new Varchar],
'branch_id' => ['required','unique:merchant_product,branch_id,NULL,id,merchant_id,'.Auth::id()', new Varchar],
];
You can use Rule::unique to validate both column together :
'product_id' => [
'required',
Rule::unique('merchant_product')->where(function ($query) use($request) {
return $query->where('product_id', $request->product_id)
->where('branch_id', $request->branch_id);
}),
],
Don't forget to add use Illuminate\Validation\Rule; on the top
Use firstOrCreate()
MerchantProduct::firstOrCreate([
'product_id' => $productId,
'merchant_id' => $merchantId,
'branch_id' => $brandId
]);
This will stop any duplicate record being created, using all 3 columns without doing extra processing with rules.
See the following article for usage:
https://laravel.com/docs/8.x/eloquent#retrieving-or-creating-models

Laravel Backpack select2_from_ajax select change the result and default value

For the backpack-demo, I would like to show the ID and Title together.
For the search result no issue, selected at the select2 also no issue, the problem is after save, it will not display, it become blank.
How can I set it?
Like below
backpack-demo/app/Http/Controllers/Admin/MonsterCrudController.php
[ // select2_from_ajax: 1-n relationship
'label' => 'Select2_from_ajax', // Table column heading
'type' => 'select2_from_ajax',
'name' => 'select2_from_ajax', // the column that contains the ID of that connected entity;
'entity' => 'article', // the method that defines the relationship in your Model
'attribute' => 'id_title', // foreign key attribute that is shown to user
'model' => "Backpack\NewsCRUD\app\Models\Article", // foreign key model
'data_source' => url('api/article'), // url to controller search function (with /{id} should return model)
'placeholder' => 'Select an article', // placeholder for the select
'minimum_input_length' => 2, // minimum characters to type before querying results
'tab' => 'Relationships',
'wrapperAttributes' => ['class' => 'form-group col-md-12'],
],
backpack-demo/app/Http/Controllers/Api/ArticleController.php
if ($search_term) {
return Article::
selectRaw("CONCAT('Article ID: ', id,' | Title: ', Title) AS id_title, articles.*")
->where('title', 'LIKE', '%'.$search_term.'%')->paginate(10);
} else {
return Article::selectRaw("CONCAT('Article ID: ', id,' | Title: ', Title) AS id_title, articles.*")
->paginate(10);
}
The solution is at the Article Model create another accessor function
public function getIdTitleAttribute()
{
return 'Article ID: ' . $this->id . ' | Title: ' . $this->title;
}

Include related table from pivot table in Fractal's Transformers

In my Laravel project, I have 4 tables:
location
location_product
product
status
location_product is the intermediate table between location and product and it has a foreign key status pointing to the product_status table.
I'm using Fractal's transformers to transform my models:
//Filter the products
$products = $location->products()->unarchived()->get();
return $this->response()->collection($products, new ProductDetailsTransformer());
and in my ProductDetailsTransformer.php, I want to include the status from the intermediate table using '''defaultIncludes''':
/**
* List of resources to automatically include
*/
protected $defaultIncludes = [
'status',
];
public function includeStatus(Product $product) {
return $this->item($product->pivot->status, new ProductStatusTransformer());
}
but I receive an
Call to undefined relationship [status] on model [App\Models\Product].
How can I correctly include the status table using Fractal's transformers?
At the moment, I'm using the following:
public function transform(Product $product) {
return [
'id' => (int)$product->id,
'name' => $product->name,
'amount' => $product->pivot->amount,
'delivery_on_site' => (bool)$product->pivot->delivery_on_site,
'status' => [
'id' => $product->pivot->status->id,
'name' => $product->pivot->status->name
]
];
}
But I'd like to use a Transformer if that's possible for the status.

Avoid duplication in doctor_id field with where clause in laravel 5.4

this is my doctors id
this is my user id
I can't insert anything when I put unique in the validation of doctor_id. When there's no unique it works fine.
I want to avoid duplicate doctor_id where auth::id == 1. Any advice is appreciated.
public function store(Request $request, $id)
{
$auth = Auth::id();
$constraints = [
'doctor_id' => 'required|unique',
'day1' => 'required|max:20',
'day2'=> 'required|max:60',
'day3' => 'required|max:60'
];
$input = [
'users_id' => $auth,
'doctor_id' => $id,
'day1' => $request['day1'],
'day2' => $request['day2'],
'day3' => $request['day3'],
'day4' => $request['day4'],
...
'day27' => $request['day27'],
'status' => '1'
];
$this->validate($request, $constraints);
Itinerary::create($input);
$added = array('added'=> 'Added Doctor to Itinerary Successful!!');
return redirect()->back()->with($added);
Have you tried this? (assuming your table is named itineraries):
'doctor_id' => 'unique:itineraries'
According to Laravel Doc, you should add the table name, and column name if possible:
unique:table,column,except,idColumn

Showing relation table fields with filters in yii2

I'm showing has many relation table value in my girdview as follows
[
'attribute' => 'Resume Title',
'value' => function($model, $key, $index) {
return implode(\yii\helpers\ArrayHelper::map(
$model->jobSeekerProfiles,
'job_seeker_profile_id',
'resume_title'
));
},
],
my table relation is
public function getJobSeekerProfiles()
{
return $this->hasMany(JobSeekerProfile::className(), ['user_id' => 'user_id']);
}
But how to make this column with filter and sortable ?

Resources