Laravel foreign key saves issue - php

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

Related

Laravel 7, SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed when trying to add a relationship

I'm running Laravel 7 on PHP 7.4 with MySQL 8.0.
I have three tables, User, Company and Department, with their respective models and factories.
I created a test where I'm adding the relationship:
// MyTest.php
$user = factory(User::class)->create();
$company = factory(Company::class)->make();
$company->user()->associate($user);
$company->create(); // it fails here because of NOT NULL constraint, companies.user_id
$department = factory(Department::class)->make();
$department->company()->associate($company);
$department->create();
I get the following error: Integrity constraint violation: 19 NOT NULL constraint failed: companies.user_id (SQL: insert into "companies" ("updated_at", "created_at") values (2020-03-10 07:27:51, 2020-03-10 07:27:51))
My table schema is defined like this:
// users
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('phone');
$table->integer('user_type');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
// companies
Schema::create('companies', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->string('contact_email');
$table->string('contact_phone');
$table->timestamps();
});
// departments
Schema::create('departments', function (Blueprint $table) {
$table->id();
$table->foreignId('company_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->string('contact_email');
$table->string('contact_phone');
$table->timestamps();
});
It is my understanding that there should be no NULL-values in SQL-tables, which is why I am deliberately trying to avoid ->nullable() in my migrations. Especially for foreign keys like these.
EDIT:
I tried doing it this way, I also made a pivot table for users_companies. Now I can attach a company, but I'm still getting an SQL-error when doing the test this way:
$user = factory(User::class)->create();
$company = factory(Company::class)->create();
$user->companies()->attach($company);
$company->departments()->create([
'name' => 'Department 1',
'contact_email' => 'department1#example.test',
'contact_phone' => '123456789',
]);
This also fails with the error stated below:
$company = factory(Company::class)->create();
$company->departments()->save(factory(Department::class)->make());
The error is this: Integrity constraint violation: 19 NOT NULL constraint failed: departments.company_id (SQL: insert into "departments" ("name", "contact_email", "contact_phone", "company_id", "updated_at", "created_at") values (Department 1, department1#example.test, '123456789', ?, 2020-03-11 07:59:31, 2020-03-11 07:59:31)).
CompanyFactory.php
<?php
/** #var \Illuminate\Database\Eloquent\Factory $factory */
use App\Company;
use Faker\Generator as Faker;
$factory->define(Company::class, function (Faker $faker) {
return [
'name' => 'Company 1',
'contact_email' => 'company#example.test',
'contact_phone' => '123456789',
];
});
Factories
DepartmentFactory.php
<?php
/** #var \Illuminate\Database\Eloquent\Factory $factory */
use App\Department;
use Faker\Generator as Faker;
$factory->define(Department::class, function (Faker $faker) {
return [
'name' => 'Department 1',
'contact_email' => 'department1#example.test',
'contact_phone' => '123456789',
];
});
Some problems with your table structure are very clear at first glance.
It appears you're trying to add a user_id column to your companies table. This is not a good idea, assuming your companies have more than one employee.
If you want to use NOT NULL columns, you'd better define a default value for each of them.
So we can start by writing the migrations something like this, including pivot tables for the company/user and department/user relationships:
// companies
Schema::create('companies', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('contact_email')->default('');
$table->string('contact_phone')->default('');
$table->timestamps();
});
// departments
Schema::create('departments', function (Blueprint $table) {
$table->id();
$table->foreignId('company_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->string('contact_email')->default('');
$table->string('contact_phone')->default('');
$table->timestamps();
});
// users
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('name')->default('');
$table->string('phone')->default('');
$table->integer('user_type')->default(0);
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('company_user', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('company_id')->constrained()->onDelete('cascade');
});
Schema::create('department_user', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('department_id')->constrained()->onDelete('cascade');
});
Now we have links between tables. A department is part of a company; a user can be part of multiple departments and/or multiple companies. This leads to the following relationships:
class User extends Model {
// many-to-many
public function companies() {
return $this->belongsToMany(App\Company::class);
}
// many-to-many
public function departments() {
return $this->belongsToMany(App\Department::class);
}
}
class Company extends Model {
public function departments() {
// one-to-many
return $this->hasMany(App\Department::class);
}
public function users() {
// many-to-many
return $this->belongsToMany(App\User::class);
}
}
class Department extends Model {
public function company() {
// one-to-many (inverse)
return $this->belongsTo(App\Company::class);
}
public function users() {
// many-to-many
return $this->belongsToMany(App\User::class);
}
}
Now code like this should work:
$user = factory(User::class)->create();
$company = factory(Company::class)->create();
$user->companies()->attach($company);
$company->departments()->create([
'name' => 'Department 1',
'contact_email' => 'department1#example.test',
'contact_phone' => '123456789',
]);
Specifically, the attach method is used for updating many-to-many relationships, which you did not appear to have defined, based on your original table layout.

How to create two Foreign Key on pivot table linked to one Primary Key

I'm trying to implement where I need to insert or save the current user that logged in. Inserting the recipient into user_id column works well but I need to manipulate who send the data I need to get the user id. I have two tables users and documents with a pivot table document_user.
users table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('username');
$table->string('password');
$table->string('remember_token');
});
documents table
Schema::create('documents', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
document_user - pivot table
Schema::create('document_user',function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('document_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('document_id')->references('id')->on('documents')->onDelete('cascade');
$table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
});
DB Design:
Note! I only insert few column in my users table migration just to save a line of text.
Model
User
public function documents()
{
return $this->belongsToMany('App\Models\Document', 'document_user', 'user_id', 'document_id');
}
Document
public function recipients()
{
return $this->belongsToMany('App\Models\User', 'document_user', 'document_id', 'user_id');
}
Inserting records based on the user's choice to pivot table works well. But when I try to rollback my migration and alter my pivot table to this.
$table->integer('sender_id')->unsigned();
$table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');
I get a error it says:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`webdev`.`document_user`, CONSTRAINT `document_user_sender_id_foreign` FOREIGN KEY (`sender_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: insert into `document_user` (`document_id`, `user_id`) values (34, 10))
How can I achieve inserting the current user in my pivot table? So I can track who sends and receive the data. Any help would appreciated! Cheers!
UPDATE 1:
Thanks to #Dastur for solving my issue.
document_user table
Schema::create('document_user',function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('document_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('document_id')->references('id')->on('documents')->onDelete('cascade');
$table->unsignedInteger('sender_id')->nullable();
$table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
});
I'm just having a hard time getting the id of the current user and insert this into sender_id column. Still don't have any idea to do this because I need to tracked the created documents of the users.
DocumentController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Document;
use App\Models\User;
use DB;
use Auth;
class DocumentController extends Controller
{
public function getDocuments()
{
//GETTING ALL THE ID OF THE USERS IN THE DATABASE EXCEPT THE ID OF CURRENT USER.
$resultRecipient = DB::table('users')->where('id', '!=', Auth::id())->get();
//GETTING ALL THE CATEGORIES.
$resultCategory = DB::table('categories')->get();
//VIEW
return view ('document.create')->with('resultRecipient', $resultRecipient)->with('resultCategory', $resultCategory);
}
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|alpha_dash|max:255',
'content' => 'required',
'category_id' => 'required',
'recipient_id' => 'required',
]);
$document = new Document();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category_id;
$document->save();
$document->recipients()->sync($request->recipient_id, false);
return redirect()->back();
}
}
UPDATE 2: According to #Dastur I need to create a another Model for my pivot table which is document_user.
UserDocument (Model)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserDocument extends Model
{
protected $table = 'document_user';
}
I looked around a bit online, and found this post on laracasts: http://laravel.io/forum/09-18-2014-foreign-key-not-saving-in-migration. Also, this error is normally thrown when your trying to get a null value from another table and put it into a row that isn't nullable.
Edit:
What your doing here is very strange, I still think the pivot table isn't a smart option. Here's exactly what I would do:
Migrations:
First, I would create my users migration, simple enough:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('username');
$table->string('password');
$table->rememberToken();
});
Next I would create my documents table:
Schema::create('documents', function(Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->integer('category_id');
$table->integer('user_id');
$table->integer('sender_id');
$table->dateTime('dateRecieved')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamps();
});
Models:
In your user and category model you need the following method:
public function documents() {
$this->hasMany(/* Path to your document model */);
}
Finally, in your document model you need the following methods:
public function category() {
$this->belongsTo(/* Path to your category model */);
}
public function user() {
$this->belongsTo(/* Path to your user model */);
}
Document Controller
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|alpha_dash|max:255',
'content' => 'required',
'category_id' => 'required',
'recipient_id' => 'required',
]);
/*
* This part not exactly sure what to do, because of I don't know what
* know what the difference is between the sender and the user, please
* elaborate.
*/
}

Laravel 5.2 - Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

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

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

I know this is a common problem but don't know what's wrong here. As you can see there's this //return $user and it shows an valid id. Checked that in database as well.
$user = new User;
$user->first_name = $data['first_name'];
$user->last_name = $data['last_name'];
$user->email = $data['email'];
$user->phone_no = $data['phone_no'];
$user->created_from = 'Web App';
$user->save();
// return $user;
Session::put('user_id',$user->id);
// return $user->id;
$address = new Address;
$address->user_id = $user->id;
$address->first_name = $data['receiver_first_name'];
$address->last_name = $data['receiver_last_name'];
$address->email = $data['receiver_email'];
$address->address_line_1 = $data['receiver_address_line_1'];
$address->address_line_2 = $data['receiver_address_line_2'];
$address->landmark = $data['receiver_landmark'];
$address->pincode = $data['receiver_pincode'];
$address->phone_no = $data['receiver_phone_no'];
$address->created_from = 'Web App';
$address->save();
Here are the migrations:
This is the users migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function($table){
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email');
$table->string('phone_no', 20)->nullable();
$table->string('password')->nullable();
$table->string('remember_token', 100);
$table->date('date_of_birth')->nullable();
$table->string('created_from');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Addresses
public function up()
{
Schema::create('addresses', function($table){
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('first_name');
$table->string('last_name');
$table->string('email');
$table->string('address_line_1');
$table->string('address_line_2')->nullable();
$table->string('landmark')->nullable();
$table->string('city')->nullable();
$table->string('state')->nullable();
$table->string('phone_no', 13);
$table->integer('pincode');
$table->string('created_from');
$table->timestamps();
$table->softDeletes();
$table->foreign('user_id')->references('id')->on('users');
});
}
Here's a screenshot of error if it helps.
According to the error message, your error is caused by inserting a value in adresses.user_id (FK to src.id), which does not exist in src.id.
In the example, you try to insert 29 in adresses.user_id, check if SELECT id FROM src WHERE id=29 returns any result. If not, there is your problem.
$table->integer('user_id')->unsigned();
but
$table->increments('id');
Should be the same: unsigned
Keys should be the same types of data

Laravel 5 inserting row with a foreign key

I have two tables Users and Posts.
here is my User table migration file:
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('password_temp',60);
$table->integer('active');
$table->string('code',60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
and here is my posts table migration file
public function up()
{
Schema::create('posts', function(Blueprint $table){
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('user_id')->unsigned();
$table->string('slug');
$table->timestamps();
});
Schema::table('posts',function(Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade')
->onUpdate('cascade');
});
}
AdminPostsController extends Controller{
public function store(Request $request)
{
$validator = Validator::make($request->all(),Post::$rules);
if($validator->passes()){
$post = new Post();
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->user_id = $request->get('id');
$post->slug = Slug::generateSlug($request->get('title'));
$post->save();
return Redirect::route('admin.posts.index');
}
else{
return Redirect::route('admin.posts.create')->withErrors($validator)->withInput();
}
}
}
Every time i insert a new post,i always see the following error
"QueryException in Connection.php line 614:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ('blog'.'posts', CONSTRAINT 'posts_user_id_foreign' FOREIGN KEY ('user_id') REFERENCES 'users' ('id') ON DELETE CASCADE ON UPDATE CASCADE)"
i would like to know what i am doing wrong.
This code creates a constrain so that your post MUST be referenced by a valid user id. The user_id field must contain a existing key on the users table id field.
$table->foreign('user_id')
->references('id')
->on('users')
Try associating the user before saving the new post.
$post = new Post();
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->user()->associate($user);
$post->save();
Assuming that you have a valid user model loaded on the $user var and that you have set the relationship between Users and Posts on the Models.

Categories