Laravel 5 inserting row with a foreign key - php

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.

Related

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint

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

Delete all posts related to a user in laravel

this is my posts table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->integer('category_id')->unsigned()->index();
$table->integer('photo_id')->default(0)->unsigned()->index();
$table->string('title');
$table->text('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
});
}
this is my users table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('role_id')->index()->unsigned()->nullable();
$table->integer('photo_id')->index()->default(0);
$table->boolean('is_active')->default(0);
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
these are the relations
public function posts() {
return $this->hasMany('App\Post');
}
public function user() {
return $this->belongsTo('App\User');
}
Delete code of the user
public function destroy($id)
{
$user = User::findOrFail($id);
if($user->photo_id !== 0) {
unlink(public_path() . $user->photo->path);
}
$user->delete();
Session::flash('deleted_user', 'The user has been deleted.');
return redirect('/admin/users');
}
Delete code of the post
public function destroy($id)
{
$post = Post::findOrFail($id);
if($post->photo_id !== 0) {
unlink(public_path() . $post->photo->path);
}
$post->delete();
return redirect('/admin/posts');
}
I am trying to delete all the posts related to a user when I delete a user.
For that, I am using foreign reference constraint in posts table as shown above
But it is not working when I delete the user. The posts are still there.
I dont know what I am doing wrong
This problem occurs most probably because the default table engine in your MySQL instance is set to MyISAM which doesn't support foreign keys. Trying to work with foreign keys on a MyISAM table would definitely not be a bug in Laravel. Although it would be nice if the Schema Builder could automatically set the engine to InnoDB if foreign keys are used.
so, use this line in your schema
$table->engine = 'InnoDB';
or alter the table with
ALTER TABLE table_name ENGINE=InnoDB;
May be help you.
Create you custom method like function destroyAllByUser()
and put the code like
DB::table('posts')->where('user_id', '=', 1)->delete();
I hope it may help
Delete user;
public function destroy($id)
{
$user = User::findOrFail($id);
if($user->photo_id !== 0) {
unlink(public_path() . $user->photo->path);
}
$user->posts->delete();
$user->delete();
Session::flash('deleted_user', 'The user has been deleted.');
return redirect('/admin/users');
}
A alternative way to solve that is to configure database.php file under laravel-project\config folder to work on InnoDB engine.
'mysql' => [
...
'engine' => 'InnoDB'
]
Now you don't need to worry when you using foreign keys...
REMEMBER - If you didn't configured this before you create your tables you should remigrate again.

Laravel foreign key saves issue

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

How i drop foreign and primary key of table in migration?

How I drop multiple foreign key and primary keys in migration file.
Bellow is my migration file code.
Migration File
public function up()
{
Schema::create('role_user', function(Blueprint $table){
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->primary(['role_id', 'user_id']);
});
}
public function down()
{
Schema::drop('role_user');
//how drop foreign and primary key here ?
}
Blueprint class offers dropForeign and dropPrimary methods that allow you to remove foreign key constraints and primary key.
The following should do the trick:
public function down()
{
Schema::table('role_user', function (Blueprint $table) {
$table->dropForeign('role_user_role_id_foreign');
$table->dropForeign('role_user_user_id_foreign');
$table->dropPrimary();
});
}

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

Categories