Validate multiple fields to be unique in Laravel - laravel

My table is named Cars with 2 fields (id, matriculation), how to adapt my syntax below?
'input_field' => 'unique:<table name>,<column name for this input field>, <unique id>, <unique id column in table>';
I have tried this: ???
'matriculation' => 'required|unique:cars,matriculation, uniqueID ???? , unique id colum in table ????
Do know you what is the unique id and unique id column ?
Thank you for your help.

If you want to validate the matriculation upon update to be unique but keep the id intact, force ignoring it with a custom Validator rule
$car = Get_The_Car_Here; // Here assign the car to a variable
Validator::make($data, [
'marticulation' => [
'required',
\Illuminate\Validation\Rule::unique('cars')->ignore($car->id),
],
]);
Hope this helps

Related

firstOrNew with "or" statement

I have a table with columns like "name", "surname", "user_id", and I need to check if entry exists first by id, and then by name and surname together, if there is none, create it. How do I do it neatly, instead of making two update statements, and if both return 0 just create a new one (which seems too bulky)
I thought of using firstOrNew, but it seems that it only can work while matching all of the parameters.
Is there any method I've missed that would apply well to my situation?
You could try something like this (assuming you want to create a model [saved to the database]):
$attributes = [
'name' => ...,
'surname' => ...,
];
$model = Model::where('id', $id)
->orWhere(fn ($q) => $q->where($attributes))
->firstOr(fn () => Model::create($attributes));
This would search for a record by id OR name and surname. If it doesn't find one it will create a new record with the name and surname (assuming those attributes are fillable on the Model).
Laravel 8.x Docs - Eloquent - Retrieving Single Models / Aggregates firstOr

OctoberCMS belongsTo relationship saving problem

I have two models:
Brands
Mods
I can display all brands via belongsTo function. Problem is when I try to save same brand two times, I get error duplicated entry.
This belongsTo is causing duplicated entry error when saving to DB two same brands.
Mods.php
public $belongsTo = [
'brand' => [\Slasher\Farming\Models\Brands::class, 'key' => 'id'],
];
This belongsToMany works, and save's data to DB, but is generating checkbox field (I only want to select one brand at one mod enty). I'm using pivot table for this relation.
Mods.php
public $belongsToMany =[
'brand' =>[
'Slasher\Farming\Models\Brands',
'table' => 'slasher_farming_mods_brands',
'order' => 'brand_name'
],
];
BelongsTo example: (Brands are visible and I can save them. But problem is when saving same brand for more than two times).
Error I get when saving with belongsTo.
I tried also creating inverse relationships on Brands model with (belongsTo and belongsToMany), but still getting this error.
What type of relation should I make, to save Brands as dropdown list and to fix this duplicate error?
If you're using a pivot table for your relation, then you should use $belongsToMany. Pivot table is only used for many-to-many relations.
I fixed this problem with changing column in the mods name brand to brand_id and also changing belongsTo relation. I just removed key, and it works like a charm. No need for pivot table here.
Mods.php
public $belongsTo = [
'brand' => ['Slasher\Farming\Models\Brands']
];
"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3' for key 'PRIMARY' (SQL: update liam_blog_blogs set id = 3, liam_blog_blogs.updated_at = 2022-07-26 09:30:09 where id = 2)"

How to check the data already exists or not laravel

I have 2 tables. Patient table and reservation table.
Patient table:
ID
name
medical record number (norekmed)
Table of reservations
ID
idpatient
idroom
How do I check patient data already or not if I make a reservation?
Checking is by comparing between a reservation form field with norekmed in the patient table.
If patient data already exists, we can make a reservation. And if there is no patient data, we cannot make a reservation.
If it turns out this is not good, and there is a better method, I accept that.
Reservation controller (store)
$this->validate($request,
[
'idpatient' => 'required|unique:reservation,idpatient',
'idroom' => 'required',
]);
Patient::where(function($query) {
$query->has('id')
->orHas('norekmed');
})->find(1);
$reservasi = new Reservasi();
$reservasi->idpatient = $request->idpatient;
$reservasi->idroom = $request->idroom;
$reservasi->save();
A simple solution could be to use firstOrCreate and let the validator check if the patient id and room id exist. If I would have done this I would do the following:
$this->validate($request, [
// This will check if the patient exists.
'idpatient' => 'required|exists:patients,id',
// This will check if the room exists.
'idroom' => 'required|exists:room,id',
]);
// Get the reservation or create one if it does not exist.
$reservasi = Reservasi::firstOrCreate([
'idpatient' => $request->idpatient,
'idroom' => $request->idroom,
]);
...

laravel backpack crud display relationship in list view filter by and update

How can you display relationships fields and filter by in the list and update views?
lets say I have a transactions table
Id, customer_id, product_id, purchase_date, payment_status
a customer table
Id, first_name, last_name, email, password
a products table
Id, product_name, product_description, product_price, stock
for example. And I wanted to show in my transactions view:
ID, customer.first_name customer.last_name, product.product_name, purchase_date, payment_status
and wanted to filter the results by customer name and product name, I have read through the docs and cannot see how to achieve this.
In your CrudController in the setup() method :
$this->crud->setListView('your-custom-view');
If you want, you can use the default list view as a starter and modify it
you can find the default file in vendor/backpack/crud/src/resources/views/list.blade.php.
Don't modify it there because it will show on all Crud views..just take it as a template and save 'your-custom-view' in views.
Maybe this will be of help : https://laravel-backpack.readme.io/v3.3/docs/filters
Edit:
Instead of customer_id you want the customer first_name and so on right? This will do the trick:
In your TransactionCrudController:
$this->crud->addColumn([
// 1-n relationship
'label' => "customer", // Table column heading
'type' => "select",
'name' => 'customer_id', // the column that contains the ID of that connected entity;
'entity' => 'customer', // the method that defines the relationship in your Model
'attribute' => "first_name", // foreign key attribute that is shown to user
'model' => "App/Models/Customer", // foreign key model
]);
Is this what you are looking for? If not let me know.

Unique on several fields in Laravel Requests

I would like to define a unique on 2 fields ( championship_id, name ) in my TeamRequest.php
But I only know how to do a unique for a field > table like that...
'email' => 'required|unique:users',
Is it posible???
Two field in combination should be unique in Database
You can do this in your migration file:
Schema::create('Table_name', function ($table) {
// ...
$table->unique(array('championship_id', 'name'));
});

Resources