I have created the following migration for lang:
class CreateLangTable extends Migration
{
public function up()
{
Schema::create('lang', function (Blueprint $table) {
$table->string('code')->primary();
$table->string('name');
$table->timestamps();
});
}
}
class CreateMachineryCategoriesTranslationTable extends Migration
{
public function up()
{
Schema::create('machinery_categories_translation', function (Blueprint $table) {
$table->increments('id');
$table->string('lang_code')->index();
$table->foreign('lang_code')->references('code')->on('lang')->onDelete('cascade')->onUpdate('cascade');
$table->integer('machinery_categories_id')->unsigned()->index();
$table->foreign('machinery_categories_id')->references('id')->on('machinery_categories')->onDelete('cascade')->onUpdate('cascade');
$table->string('name')->nullable();
$table->timestamps();
});
}
But when I try to seed with:
class MachineryCategoriesTranslationTableSeeder extends Seeder
{
public function run()
{
$el = Lang::find('el');
$en = Lang::find('en');
$loaderCat = new MachineryCategory();
$loaderCat->save();
$loaderCatEl = new MachineryCategoriesTranslation();
$loaderCatEl->machineryCategories()->associate($loaderCat);
$loaderCatEl->lang()->associate($el);
$loaderCatEl->name = 'Φορτωτές';
$loaderCatEl->save();
$loaderCatEn = new MachineryCategoriesTranslation();
$loaderCatEn->machineryCategories()->associate($loaderCat);
$loaderCatEn->lang()->associate($en);
$loaderCatEn->name = 'Loaders';
$loaderCatEn->save();
}
}
I get the error
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`ps4cat`.`machinery_categories_translation`, CONSTRAINT `machinery_categories_translation_lang_code_foreign` FOREIGN KEY (`lang_code`) REFERENCES `lang` (`code`) ON DELETE CASCADE ON UPDATE CA)
(SQL: insert into `machinery_categories_translation` (`machinery_categories_id`, `lang_code`, `name` , `updated_at`, `created_at`) values (1, 0, Φορτωτές, 2016-04-08 16:24:06, 2016-04-08 16:24:06))
Where the 0 in values for lang_code is clearly wrong. What is the issue?
Related
I am currently learning Laravel through a personal project.
Context
In a blog like application, I need to link an article to its author. When I save the article, I get the error below.
Error
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (parabolica-dev.articles, CONSTRAINT articles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into articles (title, content, excerpt, updated_at, created_at) values (rgergregerg, regergergregerg, regregregregreg, 2020-04-29 09:55:12, 2020-04-29 09:55:12))
Models
Article
class Article extends Model
{
protected $fillable = ['title', 'content', 'excerpt', 'user_id'];
public function user() {
return $this->belongsTo('App\User');
}
}
User
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
public function article()
{
return $this->hasMany('App\Article');
}
}
Migrations
Users
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
Articles
class CreateArticlesTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('title');
$table->text('excerpt');
$table->text('content');
$table->string('type');
$table->string('status');
// Relationship between article and user
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
public function down()
{
Schema::dropIfExists('articles');
}
}
Controller
ArticleController
class ArticleController extends Controller
{
public function store(StoreArticle $request)
{
$validatedData = $request->validated();
$user = Auth::user()->id;
$article = Article::create($validatedData);
$article->user_id = $user;
$request->session()->flash('status', 'Article was created!');
return redirect()->route('articles.show', ['article' => $article->id]);
}
}
Solutions tried
Adding user_id to the $fillable array in my Article model, I still get the error.
Adding the nullable() method to user_id in my migration. Saving the article goes through without the error message but the user_id is recorded as null in my table afterwards.
Those are the 2 most proposed solutions across SO / LaravelCasts from what I found. Any suggestions on what I did wrong ?
Thanks for helping me !
The create method creates and saves a new instance of your model. Since the model does not include the users id at that point, it fails.
You could fix that by adding user_id to the fillables array of your model and also add the user id to the $validatedData array before creating the model.
Alternatively, you can also create a new instance of your model with the new keyword, set all data and explicitely save it once you're done:
$article = new Article($validatedData);
$article->user()->associate( Auth::user() );
$article->save();
You have to change this three lines. You insert a row but at the time user_id is null. That's why it shows the error because you assigned the user_id field not nullable.
$article = new Article;
$article->fill($validatedData);
$article->user_id = Auth::user()->id;
$article->save();
i have two tables annonces and category and souscategories between them BelongsTo HasMany relationship, same thing between table annonces and souscategories, when I want to insert the data in annonces it gives me error Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (aswak.annonces, CONSTRAINT annonces_category_id_foreign FOREIGN KEY (category_id) REFERENCES category (id) ON DELETE CASCADE) .
AnnoncesController.php
public function store(Request $request)
{
// Salarie::create($request->all());
$Annonce = new Annonce($request->all());
//$Annonce->user_id = Auth::user()->id;
$Annonce->save();
session()->flash('success','Annonce add successfully');
return redirect('annonces');
}
2020_05_31_164745_create_category_table.php
public function up()
{
Schema::create('category', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('image')->nullable();
$table->timestamps();
});
}
2020_06_22_152000_create_annonces_table
public function up()
{
Schema::create('annonces', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')
->on('category')->onDelete('cascade');
$table->bigInteger('souscategory_id')->unsigned()->nullable();
$table->foreign('souscategory_id')->references('id')
->on('souscategories')->onDelete('cascade');
$table->boolean('type')->default(false);
$table->text('images');
$table->timestamps();
});
}
2020_06_22_151000_create_souscategories_table.php
public function up()
{
Schema::create('souscategories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('souscategorie')->unique();
$table->string('slug')->unique();
$table->bigInteger('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')
->on('category')->onDelete('cascade');
$table->timestamps();
});
}
I have table named companies and other table named ads, I try to get company id in ads column named company_id.
This is my ads migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAdTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('ads', function (Blueprint $table) {
$table->increments('id');
$table->integer('company_id')->unsigned();
$table->string('title')->unique();
$table->string('slug')->unique();
$table->string('image')->nullable();
$table->string('description');
$table->timestamps();
});
Schema::table('ads', function($table) {
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('ads');
}
}
this will create me ads table with no problem but when i try to save ads it returns me this error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`jobid`.`ads`, CONSTRAINT `ads_company_id_foreign` FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`)) (SQL: insert into `ads` (`title`, `slug`, `description`, `image`, `updated_at`, `created_at`) values (first ad test, first-ad-test, <p>rwv R4QF Q4R</p>, 1494998776.png, 2017-05-17 12:26:17, 2017-05-17 12:26:17))
How can I fix that?
UPDATE
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('company_name');
$table->string('manager_name');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('image')->nullable();
$table->string('password');
$table->text('about')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
Store function
public function store(Request $request)
{
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required|alpha_dash|min:5|max:255|unique:ads,slug',
'image' => 'sometimes|image',
'description' => 'required'
));
$ad = new Ad;
$ad->title = $request->input('title');
$ad->slug = $request->input('slug');
$ad->description = $request->input('description');
if ($request->hasFile('image')) {
$avatar = $request->file('image');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
$location = public_path('ads/');
$request->file('image')->move($location, $filename);
$ad->image = $filename;
}
$ad->save();
Session::flash('success', 'Your ad published successfully!');
return redirect()->route('company.adslist', $ad->id);
}
in your company form
<input type="hidden" name="company_id" value ="{{ company_id }}">
then in store method
$ad->company_id=Input::get('company_id');
you can make the id dynamic according to user input, i am just hardcoding for the moment
This question has already been asked many times, I went through all the answers, but none solves the error I'm getting.
I'm using Laravel 5.2
I have 2 tables - Classifieds and Categories. When I want to create a classified, I get the error message:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (myclassified.classifieds, CONSTRAINT classifieds_category_id_foreign FOREIGN KEY (category_id) REFERENCES categories (id))
Migration files defined like this:
for classifieds table:
public function up()
{
Schema::create('classifieds', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('description');
$table->string('price');
$table->timestamps();
});
}
public function down()
{
Schema::drop('classifieds');
}
for categories table:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('categories');
}
and to add the foreign key,
public function up()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
});
}
public function down()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->dropForeign('classifieds_category_id_foreign');
});
}
The Models are:
Classified model:
class Classified extends Model
{
protected $table = 'classifieds';
protected $fillable = ['title', 'category_id', 'description', 'price'];
protected $hidden = [];
public function category(){
return $this->belongsTo('App\Category');
}
}
and the Category model:
class Category extends Model
{
protected $table = 'categories';
protected $fillable = ['name'];
protected $hidden = [];
public function classifieds(){
return $this->hasMany('App\Classified');
}
}
and the store method in controller is defined like this:
public function store(Request $request)
{
$title = $request->input('title');
$category_id = $request->input('category_id');
$description = $request->input('description');
$price = $request->input('price');
Classified::create([
'title' => $this->title,
'category_id' => $this->category_id,
'description' => $this->description,
'price' => $this->price
]);
return \Redirect::route('classifieds.index')
->with('message', 'Ad created');
}
What is my mistake in database set up?
This happens, when you are trying to save Classified and assign the foreign key with an id of category that does not exist yet in Category table.
If you don't have the foreign ID yet, just leave it to be null and make sure you do this on migration to allow null values;
public function up()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
});
}
public function down()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->dropForeign('classifieds_category_id_foreign');
});
}
I am using two pivot tables to store two different relations of a table. One relation works fine on insert. but the next one throws the following error. I don't know what's causing this.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (sdesk.approvers, CONSTRAINT approvers_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into approvers (user_id, request_id, updated_at, created_at) values (2, 6, 2014-04-29 10:54:37, 2014-04-29 10:54:37))
Here's my code:
UrequestsController.php
public function postCreate() {
$request = new Urequest;
$request->vms = Input::get('vms');
$request->location = Input::get('location');
$request->descr = Input::get('descr');
$request->status = Input::get('status');
//$request->role_group = Input::get('team');
$request->save();
$ruser = new Ruser;
$ruser->user_id = Input::get('userid');
$ruser->urequest()->associate($request);
$ruser->save();
$approver = new Approver;
$approver->user_id = Input::get('aid');
$approver->urequest()->associate($request);
$approver->save();
return Redirect::to('users/dashboard')->with('message', 'Saved!');
}
Approver.php
class Approver extends Eloquent {
protected $fillable = array('request_id', 'user_id');
public function urequest() {
return $this->belongsTo('Urequest','request_id');
}
}
Ruser.php
class Ruser extends Eloquent {
protected $fillable = array('request_id', 'user_id');
public function urequest() {
return $this->belongsTo('Urequest','request_id');
}
}
urequest.php
class Urequest extends Eloquent {
protected $table = 'requests';
protected $fillable = array('vms', 'location', 'descr', 'status');
public function ruser() {
return $this->hasOne('Ruser');
}
public function approver() {
return $this->hasOne('Approver');
}
}
Schema
Schema::create('requests', function($table)
{
$table->increments('id');
$table->string('vms', 20);
$table->string('location', 20);
$table->string('descr', 255);
$table->string('status', 20);
$table->timestamps();
});
Schema::create('rusers', function($table)
{
$table->increments('id');
$table->integer('request_id')->unsigned();
$table->foreign('request_id')->references('id')->on('requests');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('approvers', function($table)
{
$table->increments('id');
$table->integer('request_id')->unsigned();
$table->foreign('request_id')->references('id')->on('requests');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
"A foreign key constraint" usually fails when you don't have a row for the value(s) you are inserting/updating in the foreign table.
In this case you probably doesn't have a user_id of 2 in the users table or a request_id of 6 in the requests table.
EDIT just saw morawcik answered it in comments.