Laravel Clone /Multi Collection to Model Insert - laravel

I am trying to clone a collection of existing records and create a new model for each with changing properties such as name,promotion_id etc.
$source_voice_messages = VoiceMessage::wherePromotionId($promotion_id)->get();
foreach($source_voice_messages as $source_voice_message ){
VoiceMessage::insert($source_voice_message->toArray());
}
the expected behavior should be a new record with a new primary id.
I am getting:
SQLSTATE[23000]: Integrity constraint violation:
1062 Duplicate entry '83' for key 'PRIMARY'
In addition how would I change $source_voice_message->name

I solved it with replicate()
$voice_message = VoiceMessage::find($source_voice_message->id);
$cloned_voice_message = $voice_message->replicate();
$cloned_voice_message->save();

Related

using observers to delete all relations in Laravel

My tables structure is :
Shopsidname
Productsidnameshop_id
Product_tagsidlabelvalueproduct_id
Problem is: I want to delete products and product tags on deleting shop
I made two Observers and registered both :
ShopObserver
ProductObserver
ShopObserver :
public function deleting(Shop $shop)
{
$shop->products()->delete();
}
ProductObserver :
public function deleting(Product $product)
{
$product->tags()->delete();
}
But I have following error :
"SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`tabadolha`.`product_tags`, CONSTRAINT `product_tags_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`)) (SQL: delete from `products` where `products`.`shop_id` = 26 and `products`.`shop_id` is not null)"
I don't want to use nullOnDelete on my database. I want to delete it by observer.
Any way?
The problem is that your second observer of tags should be fired FIRST, and you can't specify the order of observers in Laravel.
What I would to is delete the tags in the same ShopObserver, before deleting the products, and not create a separate ProductObserver.
Something like:
$shop->products->each(function($product) {
$products->tags()->delete();
});
$shop->products()->delete();
Please test, not sure about the syntax, typed it with phone from my memory :)

Filament SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

When I create a new row in the table 'partidos' I get this message:
'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '
That is ok, I know it is a duplicate entry, but I get an error page from Laravel. My question is, how I can get an alert or similar instead of that error page?
I tried to use laravel validation rules, but I don't know how to use them with Filament
Thanks
A QueryException is being thrown due to the duplicate key violation in your partidos table.
You could encapsulate your statement(s) in a try/catch block to catch and handle the exception however you see fit. For example:
try {
// perform your database action here
} catch(\Illuminate\Database\QueryException $ex){
// $ex->getMessage(); will provide a string representation of the error
// from here you can handle the exception and return a response
}
Alternatively, you can use validation, specifically the unique rule to validate any values that must be unique in the database table are in fact unique.
public function action(Request $request)
{
// if validation fails, laravel will redirect back to the page with errors
$request->validate([
'field' => ['required', 'unique:partidos'],
]);
}

Using sync with many to many relationship in laravel: PostgreSQL Pivot table doesn't update

I'm getting this error whenever i try to sync an array of inputs to a pivot table:
Illuminate\Database\QueryException
SQLSTATE[23503]: Foreign key violation: 7 ERROR: insert or update on table "items_option_parcel"
violates foreign key constraint "items_option_id_fk_2971521" DETAIL: Key (items_option_id)=(0) is not present in table "items_options". (SQL: insert into "items_option_parcel" ("items_option_id", "parcel_id") values (0, 168))
here is a line of my controller:
$parcel->parcel_options()->sync($request->input('parcel_options', []));
function in the first model:
public function parcelOptionsParcels()
{
return $this->belongsToMany(Parcel::class);
}
function in the 2nd model:
public function parcel_options()
{
return $this->belongsToMany(ItemsOption::class);
}
I found out the issue, i checked my pluck() function, i forgot to pluck the items options ID with their SKUs, that's why every time it says a 0 id is not present in the table because it wasn't getting fetched at all.
I changed this:
$parcel_options = ItemsOption::all()>pluck('item_option_sku')>prepend(trans('global.pleaseSelect'), '');
to this
$parcel_options =
ItemsOption::all()->pluck('item_option_sku','id')->prepend(trans('global.pleaseSelect'), '');

laravel 5.4 how to handle query exception with custom exception

whenever I try to delete an artist with the related song in the child table.
it returns this error.
QueryException in Connection.php line 647:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`laravel`.`artist_song`, CONSTRAINT `artist_song_artist_id_foreign` FOREIGN KEY (`artist_id`) REFERENCES `artists` (`id`)) (SQL: delete from `artists` where `id` = 1)
this is what I want. to protect the parent table, but what I want is to make the end user see a message saying like this "yOU CAN NOT DELETE AN ARTIST WITH RELATED SONGS PLEASE DELETE ALL SONGS OF THIS ARTIST, FIRST'. so how can I catch this with the custom exception?
I don't think you need to rely here on database exception. When someone chooses deleting artist you should verify whether artist has any songs and if yes, you should then redirect with message.
Assuming you have in Artist model relationship defined like this:
public function songs()
{
return $this->hasMany(Song::class);
}
in controller you could use code like this:
public function destroy($artistId)
{
$artist = Artist::findOrFail($artistId);
if ($artist->songs()->count()) {
return redirect()->back()->with('message','You cannot delete ...');
}
$artist->delete();
return redirect()->route('artists.index');
}

Foreign key constraint fails on nullable field

I have a table organizations. This table has a primary id (int 10, unsigned, AUTO_INCREMENT).
In the table organizations, I also have a foreign key to the iself: main_organization_id. This has the following attributes: (int 10, unsigned, nullable, empty:TRUE, default:NULL).
Whenever I create a new organization:
$organization = Organization::create($request->all());
Without a main_organization_id in my request, it fails with the following error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(myDB.organizations, CONSTRAINT
organizations_main_organization_id_foreign FOREIGN KEY
(main_organization_id) REFERENCES organizations (id)) (SQL:
insert into organizations (main_organization_id) values
())
But why does this fail? The field is nullable, does that mean I have to implicitly set main_organization_id to null in the request?
My $fillable:
protected $fillable = [
'main_organization_id',
];
My migration:
Schema::table('organizations', function (Blueprint $table) {
$table->integer('main_organization_id')->unsigned()->nullable();
$table->foreign('main_organization_id')->references('id')->on('organizations');
});**strong text**
I want to prevent code like this: $request['main_organization_id'] = null; before creating my new row. Is this possible?
Thank you for reading.
Yes, you should specify the field value while creating an Organization, you should do it like this:
$organization = Organization::create(array_merge([
'main_organization_id' => null,
], request()->all()));
Hope this helps!

Resources