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'],
]);
}
Related
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 :)
I am attempting to integrate social logins with my existing laravel app. I am attempting to change email and password to nullable but I also need email to remain unique. On executing my migration I am getting an error for duplicate key name 'users_email_unique'
Laravel 5, already fixed the issue with enum I had for altering a column.
Schema::table('users', function (Blueprint $table) {
$table->string('email')->unique()->nullable()->change();
$table->string('password')->nullable()->change();
});
Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1061 Duplicate key name 'users_email_unique' (SQL: alter table users add unique users_email_unique(email))
Exception trace:
1 Doctrine\DBAL\Driver\PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1061 Duplicate key name 'users_email_unique'")
/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:119
2 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1061 Duplicate key name 'users_email_unique'")
/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:117
Edit
If I remove Unique() from email, will it remain unique since that was previously set in a different migration?
You can change the uniqueness behaviour in a new migration by following below:
public function up()
{
Schema::table('contacts', function (Blueprint $table) {
$table->dropUnique(['email']);
});
}
/**
* Reverse the migrations.
*
*/
public function down()
{
Schema::table('contacts', function (Blueprint $table) {
$table->string('email')->unique()->change();
});
}
The Nullable() attribute will stay with the email column, since it was created with it.
It sound like the database is detecting a repeated value. That's impossible with nulls, so it could be an empty string maybe.
If that's the case, you can write a mutator function in your model to check if the value is empty and, set it to null before it goes to the database engine, like this:
public function setNameOfYourAttribute($value) {
if ( empty($value) ) {
$this->attributes['nameofyourattribute'] = NULL;
}
}
Hope it helps.
NOTE:
Full Documentation
Figured this out myself, as mentioned in the comment on the above answer.
Simply because the table was already created with unique() if I remove that it will allow the migration and will also persist the unique() functionality that was in the original User table migration.
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();
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');
}
I'm progmatically importing products into Magento 1.7.0.2 from an XML feed.
The script has run fine for the best part of a week, but now I'm getting the error shown below when products are saving.
How serious is this error, what can cause it?
I've tried reindexing everything and truncating a bunch of tables, the error seems to persist.
The Error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '51-1' for key 'UNQ_CATALOGINVENTORY_STOCK_ITEM_PRODUCT_ID_STOCK_ID'
Import php (sample):
$sProduct = $this->_productModel;
$sProduct->setTypeId($this->_productTypeSimple)
->setWebsiteIds(array(1))
->setStatus($this->_productStatusDisabled)
->setVisibility($this->_productVisibilityNotVisible)
->setTaxClassId(2) //Taxable Good
->setAttributeSetId(XML_FEED_PRODUCT_ATTRIBUTE_SET)
->setSku($arrayProductData['ProductSKU'])
->setName($arrayProductData['ProductName'])
->setShortDescription($arrayProductData['ProductShortDescription'])
->setDescription($arrayProductData['ProductLongDescription'])
->setPrice(sprintf("%0.2f", $arrayProductData['ProductPrice']))
->setRRP(sprintf("%0.2f", $arrayProductData['ProductPrice']))
->setWeight(0)
->setCategoryIds($arrayProductData['ProductCategories'])
->setUrlKey(str_replace(array(" ","'","&"),"-",$arrayProductData['ProductName']) . "-" . $arrayProductData['ProductSKU']);
$sProduct->setStockData(
array(
'use_config_manage_stock' => 1,
'is_in_stock' =>1,
'qty' => $arrayProductData['ProductStockQty']
)
);
$sProduct->setMetaTitle($arrayProductData['ProductName'])
->setMetaDescription(str_replace("<<THE_PRODUCT>>",$arrayProductData['ProductName'], DEFAULT_META_DESC));
if(isset($arrayProductData['ProductSize'])) {
$sProduct->setData("sizes", $arrayProductData['ProductSize']);
}
if(isset($arrayProductData['ProductColour'])) {
$sProduct->setData("color", $arrayProductData['ProductColour']);
}
try {
$sProduct->save();
}
catch (Mage_Core_Exception $e) {
echo $e->getMessage();
}
Thanks for looking.
As the error show
UNQ_CATALOGINVENTORY_STOCK_ITEM_PRODUCT_ID_STOCK_ID
There is duplicate entry in DB table ( cataloginventory_stock_item ) for the same product_id / stock_id
This could happen for different reasons
You can solve this by setting the ID of the product manually before save so it won't conflict get the last product ID and increment it.
or delete the row related to this new product from the table before save
Further down the script I was creating configurable products based on certain criteria.
For reasons I've not yet uncovered the SKU of this configurable product doesn't appear to be unique, causing the issue above.
Thanks anyway Meabed.