I have category table
Its has del_status
when delete category delstatus will change 1
now question is
when update category ,
I want to validate except del_status 0
because category is unique
eg below is pseudo code :)
Rule::except(function ($query){
return $query->where('del_status','1');
})
You should use The softDelete traits in your model. it will spare you a lot of trouble and will work as you want it to.
https://laravel.com/docs/5.7/eloquent#soft-deleting
it will use a field in the DB table name deleted_at
Related
I want to implement unique validation on one column but it should only check active rows of the table.
so is there any way I can implement this logic using laravel validation?
Below is the logic I am using to check unique records but its not working.
unique:users,email,is_active,1
According to the laravel validation document, you can do it as:
Rule::unique('users', 'email')->ignore(0, "is_active"),
You can scope the query with additional clauses like that:
Rule::unique('users', 'email')->where(fn ($query) => $query->where('is_active', 1));
Another syntax is:
unique:users,email,NULL,id,is_active,1
When using the belongsToMany relation in Laravel Eloquent, is it possible to add additional conditions for the intermediate table? Currently, the inserts are duplicating and I am just trying to understand how to fix it.
Here is the relation
Models/Order.php
public function addresses(): BelongsToMany
{
return $this->belongsToMany(CustomerAddress::class)
->withPivot('address_type')
->withTimestamps();
}
Here is how I save the data to the intermediate table
$tenantOrder-addresses()->attach($customerAddress->id, [
'address_type' => 'billing'
]);
Do I need to do anything else to prevent the duplicates? Below is the example of showing the duplicates. The combination being customer_address_id, order_id, address_type.
I did take a look at Eloquent belongsToMany relation with additional conditions, but this doesn't help with the resolution.
If you mean to prevent duplicate on pivot table, can add composite keys on pivot table migrations
Something like this
...
$table->primary(['customer_address_id', 'order_id', 'address_type']);
That will prevent adding new row if the customer, order, and address type in a same value.
Here's a test
Docs
I believe you are looking for syncWithoutDetaching. It helps attach without duplicated record.
Reference: https://laravel.com/docs/9.x/eloquent-relationships#syncing-associations
Using Laravel + Voyager, I have a "Has Many" relationship:
Course hasMany Teachers.
In backend all is fine, but if I try to get the information in the frontend, I only get the value in table, not the relation, so the output goes something like:
0
id 1
teachers_id null
name "Math"
1
id 2
teachers_id null
name "English"
Current code in web routing:
Route::get('/course', function () {
$co= App\Course::all();
return $co;
});
How can I get the correct output?
teachers_id Xav, Titus
so like #Tpojka commented you can start by eager loading the relationship when you are initializing the course likeso $co = App\Course::with('teachers')->get(); after which you do not need to make another unnecessary call to your database for the teachers of that course. You can get a collection of all the teachers of that course by simply calling $teachers = $co->teachers; here $teachers is now a laravel collection you can simply loop through it on the client side and display the information about the teachers you want to display. I hope this helps.
Good luck and happy coding. :)
I am using cakephp 3.4.9. When I am using a table with prefix n field its working properly after baking but if I use prefix in table fields its not working.
Like when I am using post with following fields like
id,
post,
date
it's working fine but if I use following fields its not working
p_id,
p_post,
p_date
it is adding extra codes in model
$this->belongsTo('Ps', [
'foreignKey' => 'p_id',
'joinType' => 'INNER'
]);
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['p_id'], 'Ps'));
return $rules;
}
why ps is adding here? If I use articales table like same its become As.
Please help.
I would like to suggest you, read this article.
CakePHP naming convention documentation
In cakePHP framework everything you have to keep in mind while creating the table is the CakePHP naming conventions. In your case, This is happening because cakePHP expects the primary column of any table will be only 'id', and the foreign key for the table will be the Related table name with an underscore id
(ex: If product table BelogsTO categories you have to make a column in your product table as category_id)
In your case cakePHP considering p_id as a foreign key for the table P. And by default cakePHP has a validation for the forein key that the existsIn which means that while saving that p_id, it will check for the existance of id in P table.
In one sentense this is because of the naming convention issue. You can change only p_id to id and keeping other things same will work for you.
HAPPY CODING :)
I've got a many to many relationship between a student and an institution_contact.
students should only ever have two institution_contacts and I have an attribute on the pivot table named type to be set as 1 or 2.
So, my pivot table looks like this:
institution_contact_student: id, institution_contact_id, student_id, type
I've run into difficulty in deciding how to approach the issue of adding/updating the pivot table. Let's say I have 100 students and I want to assign them a contact with the type of 1.
My current solution is to delete the contact then add it:
$students = Student::all(); // the 100 students
$contactId = InstitutionContact::first()->id; // the contact
foreach ($students as $student) {
// remove existing contact
$student
->institutionContacts()
->newPivotStatement()
->where('type', 1)
->delete();
// add new contact
$student
->institutionContacts()
->attach([$contactId => ['type' => 1]]);
}
However, I'm thinking that this is going to hit the database twice for each student, right? So would I be better off creating a model for the pivot table and removing all entries that matched the student id and the type then simply adding the new ones? Or would creating a model for the pivot table be considered bad practice and is there a better way of accomplishing this that I've missed?
Please note the reason I'm not using sync is because I'm relying on the type attribute to maintain only two contacts per student. I'm not aware of a way to modify an existing pivot without causing issues to my two contacts per student requirement.
Edit:
Instead of creating a model I could run the following code to perform the delete using DB.
DB::table('institution_contact_student') // the pivot table
->whereIn('student_id', $studentIds)
->where('type', 1)
->delete();
If I have understood your question correctly then you can use the updateExistingPivot method for updating your pivot table.But first of course you have to define the pivot in your relationship. For instance,
public function institutionContacts(){
return $this->belongsToMany('institutionContact')->withPivot('type');
}
after this, all you have to do is use the following code:
$student
->institutionContacts()
->updateExistingPivot($contactId, ["type" => 1]);
Hope this helps.