Unique on several fields in Laravel Requests - laravel

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'));
});

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

How do I return the ID field in a related table in Laravel request

I have two related tables and I want to return all fields including the ID (key) field. My query below returns all fields except the ID. how do I return the ID field from one of the tables?
'programmes' => ProgrammeInstances::with('programmes')->get(),
the query below returns Unknown column 'programmes.programme_title' as it is looking for it in the table 'programme_instances'
'programmes' => ProgrammeInstances::with('programmes')->select('programmes.programme_title', 'programmeInstances.id', 'programmeInstances.name', 'programmeInstances.year')->get(),
Laravel provides multiple relationships, one of these is the hasMany() relationship which should return a collection where a User hasMany rows inside of your database
For example, inside your User model :
public function programmes() {
return $this->hasMany(Program::class);
}
Now in your controller, you can do :
public function edit($id) {
$programmes = User::find($id)->with('programmes')->get();
return view('user.edit')->with('programmes', $programmes);
}
And then you can loop over it inside your view
#forelse($programmes->programmes as $program)
// provide the data
#empty
// the user doesn’t have any programmes
#endforelse
a solution i found below - still not sure why ID isnt automatically returned when i get all fields, but works when i specify individual fields:
'programmes' => ProgrammeInstances::with('programmes')
->get()
->transform(fn ($prog) => [
'programme_title' => $prog->programmes->programme_title,
'id' => $prog->id,
'name' => $prog->name,
'year' => $prog->year,
]),

Validate multiple fields to be unique in 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

Laravel how to load specific column of related table?

I have the following code, what I want is to take specific columns of related tables.
auth()->user()->load(['business', 'passwordSecurity']);
To select only specific columns from a relationship you should be able to do it like this:
auth()->user()->load([
'business' => function ( $query ) {
$query->select('id', 'title');
},
'passwordSecurity',
]);
Or like this:
auth()->user()->load(['business:id,name', 'passwordSecurity']);
Please note that you have to select IDs and foreign key constraints that are needed to form this relationship.

Laravel Factory Can't Save Relation

I use Laravel 5.6, and I have a problem with my seeder.
I use this :
factory(\App\Models\Merchant::class)->create([
'email' => 'admin#domain.com',
])->each(function ($m) {
$m->stores()->save(factory(\App\Models\Store::class)->create()
->each(function ($s) {
$s->products()->save(factory(\App\Models\Product::class, 10)->create());
})
);
});
All are hasMany relations.
Doing this, I have this error :
General error: 1364 Field 'merchant_id' doesn't have a default value
(SQL: insert into stores ....)
It's like my first $stores->save( ... ) doesn't use the merchant created.
In my DB, I have one merchant created.
If I use ->make() instead of ->create(), it works for the Store, but I can't save products because it's not persisted...
Is it possible to use multiple save in factories like this ?
Your code may need a little refactoring as you may be chaining creation of models incorrectly:
factory(\App\Models\Merchant::class, 2)->create([
'email' => 'admin#domain.com',
])->each(function ($m) {
$store = factory(\App\Models\Store::class)->create(['merchent_id' => $m->id]);
factory(\App\Models\Product::class, 10)->create(['store_id' -> $store->id]);
);
});
Note: In order to use the ->each() method, you need to have a collection instance. I do not think creating only one merchant will return a collection. In the example, we create 2 merchents.

Resources