Laravel Error "Illuminate\Database\QueryException" when run the 'php artisan migrate' - php

I can't run the "php artisan migrate" in laravel project. If I run this command then below error will display.
Migrating: 2021_08_02_173519_create_access_user
Illuminate\Database\QueryException
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'access_id' doesn't exist in table (SQL: alter table access_user add constraint access_user_access_id_foreign foreign key (access_id) references access (id))
at C:\Users\HETTIARACHCHIGEDAMIT\LanexGloble\lanex-internal-backend\api\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
688▕ // If an exception occurs when attempting to run a query, we'll format the error
689▕ // message to include the bindings with SQL, which will make this exception a
690▕ // lot more helpful to the developer instead of just the database's errors.
691▕ catch (Exception $e) {
693▕ $query, $this->prepareBindings($bindings), $e
694▕ );
695▕ }
696▕ }
1 C:\Users\HETTIARACHCHIGEDAMIT\LanexGloble\lanex-internal-backend\api\vendor\laravel\framework\src\Illuminate\Database\Connection.php:485 \Database\Conne
PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'access_id' doesn't exist in table") in table")
2 C:\Users\HETTIARACHCHIGEDAMIT\LanexGloble\lanex-internal-backend\api\vendor\laravel\framework\src\Illuminate\Database\Conne\Database\Connection.php:485
PDOStatement::execute()
this is an error occurred file.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAccessUser extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('access_user', function (Blueprint $table) {
$table->increments('id');
$table->foreign('access_id')->references('id')->on('access');
$table->foreign('user_id')->references('id')->on('user');
$table->boolean('status');
$table->timestamp('updated_at');
$table->timestamp('created_at');
$table->string('updated_by');
$table->string('created_by');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('access_user');
}
}

You should add a column access_id before add foreign key on it. The foreign() is adding foreign key to exists column.
So, you should change migration to below:
public function up()
{
Schema::create('access_user', function (Blueprint $table) {
$table->increments('id');
// add this line
$table->unsignedBigInteger('access_id'); // depend on your foreign column type
$table->foreign('access_id')->references('id')->on('access');
$table->foreign('user_id')->references('id')->on('user');
$table->boolean('status');
$table->timestamp('updated_at');
$table->timestamp('created_at');
$table->string('updated_by');
$table->string('created_by');
});
}
or use foreignId():
public function up()
{
Schema::create('access_user', function (Blueprint $table) {
$table->increments('id');
$table->foreignId('access_id')->constrained('access'); // change here
$table->foreign('user_id')->references('id')->on('user');
$table->boolean('status');
$table->timestamp('updated_at');
$table->timestamp('created_at');
$table->string('updated_by');
$table->string('created_by');
});
}
See docs.

Related

Laravel/MariaDB: errno 150 "Foreign key constraint is incorrectly formed"

I'm on Laravel 5.4, PHP 5.6, Ubuntu 18.04, MariaDB 10.4.8. When I run php artisan migrate, I get:
In Connection.php line 647:
SQLSTATE[HY000]: General error: 1005 Can't create table `test-kursach-backend`.`comments` (errno: 150 "Foreign ke
y constraint is incorrectly formed") (SQL: alter table `comments` add constraint `comments_post_id_foreign` forei
gn key (`post_id`) references `posts` (`id`))
In Connection.php line 449:
SQLSTATE[HY000]: General error: 1005 Can't create table `test-kursach-backend`.`comments` (errno: 150 "Foreign ke
y constraint is incorrectly formed")
I'm trying to use https://github.com/klisl/laravel-comments. Before trying to perform a migration with this package I had created DB at phpMyAdmin, had configured .env by adding DB name and stuff, had successfully run php artisan migrate, php artisan make:auth and php artisan make:controller AuthController. Then, after running php artisan vendor:publish --provider="Klisl\Comments\CommentsServiceProvider" I get 2 new files in migrations folder: date_number_CreateCommentsTable.php and date_number_ChangeCommentsTable.php
Here's source from these 2 files:
CreateCommentsTable.php:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
/**
* Class CreateCommentsTable
*/
class CreateCommentsTable extends Migration
{
/** #return void */
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->text('text');
$table->integer('parent_id')->nullable(); //разрешаем null;
$table->boolean('status')->default(config('comments.show_immediately'));
$table->timestamps();
});
}
/** #return void */
public function down()
{
Schema::dropIfExists('comments');
}
}
ChangeCommentsTable.php:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
/**
* Class ChangeCommentsTable
*/
class ChangeCommentsTable extends Migration
{
/** #return void */
public function up()
{
Schema::table('comments', function (Blueprint $table) {
$table->integer(config('comments.key_field'))->unsigned();
$table->foreign(config('comments.key_field'))->references('id')->on(config('comments.key_table'));
if(config('comments.user')){
$table->integer('user_id')->unsigned()->nullable(); //разрешаем null
$table->foreign('user_id')->references('id')->on('users');
}
});
}
/** #return void */
public function down()
{
Schema::table('comments', function (Blueprint $table) {
//
});
}
}
So then I run php artisan migrate and get the error I've written about above.
I've already tried adding ->unsigned() at CreateCommentsTable. Also I've tried to put the foreign keys out of the function at ChangeCommentsTable like this:
/** #return void */
public function up()
{
Schema::table('comments', function (Blueprint $table) {
$table->integer(config('comments.key_field'))->unsigned();
if(config('comments.user')){
$table->integer('user_id')->unsigned()->nullable(); //разрешаем null
}
});
Schema::table('comments', function ($table){
$table->foreign(config('comments.key_field'))->references('id')->on(config('comments.key_table'));
});
Schema::table('comments', function ($table){
if(config('comments.user')){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
}
});
}
/** #return void */
public function down()
{
Schema::dropForeign([config('comments.key_field')]);
Schema::dropForeign(['user_id']);
Schema::table('comments', function (Blueprint $table) {
//
});
}
and this:
Schema::table('comments', function ($table){
$table->foreign(config('comments.key_field'))->references('id')->on(config('comments.key_table'));
if(config('comments.user')){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
}
});
As any of didn't work out, I decided to post the default version of source above. If you help me with this, you really save my day c:
UPD: Here's source from CommentController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
use App\Comment;
use App\Post;
class CommentController extends Controller
{
/**
* Processing form - AJAX
*
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function store(Request $request)
{
$data = $request->except('_token', 'comment_post_ID', 'comment_parent');
//adding fields with same names like in table (models)
$data['post_id'] = $request->input('comment_post_ID');
$data['parent_id'] = $request->input('comment_parent');
$data['status'] = config('comments.show_immediately');
$user = Auth::user();
if($user) {
$data['user_id'] = $user->id;
$data['name'] = (!empty($data['name'])) ? $data['name'] : $user->name;
$data['email'] = (!empty($data['email'])) ? $data['email'] : $user->email;
}
$validator = Validator::make($data,[
'post_id' => 'integer|required',
'text' => 'required',
'name' => 'required',
'email' => 'required|email',
]);
$comment = new Comment($data);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()->all()]);
}
$post = Post::find($data['post_id']);
$post->comments()->save($comment);
$data['id'] = $comment->id;
$data['hash'] = md5($data['email']);
$data['status'] = config('comments.show_immediately');
$view_comment = view(env('THEME').'.comments.new_comment')->with('data', $data)->render();
return response()->json(['success'=>true, 'comment'=>$view_comment, 'data'=>$data]);
}
}
There is a foreign key missing in the comments table, give this a try:
Schema::create('comments', function (Blueprint $table) {
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')
I am not sure how to add a foreign key in laravel 5.4 let me know if this works.
I haven't had posts table so the problem was solved by adding it. I'll mark this answer as a correct when it's possible.

Laravel foreign key constraint is incorrectly formed I have searched and cannot find the answer

class CreateMediaTable extends Migration
{
public function up()
{
Schema::create('media', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('id_users');
$table->unsignedBigInteger('id_posts');
$table->char('type', 1); //P: photo or V: video
$table->string('file');
$table->timestamps();
$table->foreign('id_posts')->references('id')->on('posts');
$table->foreign('id_users')->references('id')->on('users');
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
and my createprofilemigration
/**
* #author Alex Madsen
*
* #date November 6, 2018
*/
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserProfilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_profiles', function (Blueprint $table) {
$table->unsignedInteger('id_users')->unique();
$table->string('handle')->unique();
$table->string('icon')->default('https://i.redd.it/130am13nj6201.png');
$table->string('profile_image')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('user_profiles');
}
}
Keeps throwing these errors, What am I missing? Mind you I am new to this, Trying to learn with youtube and stackoverflow on my off time. Not sure which way to go. I have looked on the forums and tried $table->foreign('id_posts')->references('id')->on('posts'); But it didn't fix the issue.
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table `ci`.`media` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter t
able `media` add constraint `media_id_posts_foreign` foreign key (`id_posts`) references `posts` (`id`))
at C:\xampp6\htdocs\lol\simple_social_network_laravel\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('id_users');
$table->unsignedInteger('subreddit_id');
$table->text('description');
$table->string('title');
$table->text('content');
$table->unsignedInteger('id_posts');
$table->timestamps();
$table->foreign('id_users')->references('id')->on('users');
$table->foreign('subreddit_id')->references('id')->on('id_posts');
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
When using foreign keys types should be exactly the same.
You create:
$table->unsignedBigInteger('id_posts');
so it's unsigned big integer, but probably in posts table instead of bigIncrements you use just increments for id column and that's why you are getting this error.
So quite possible instead of:
$table->unsignedBigInteger('id_posts');
you should use
$table->unsignedInteger('id_posts');
or as alternative solution use
$table->bigIncrements('id');
in posts migration
In your posts migration, you made your id with increments
that is mean that it takes
unsigned integer auto_increment
but in your migration of media file, you create a posts_id with unsignedBigInteger
so there's two way to fix that choose only one
edit your id in posts migration to be bigincrements
edit your posts_id in 'media' migration to unsignedIntegere

Laravel: Migration error when having an index

I am getting the following error when running migrations. The error in my terminal console is:
SQLSTATE[42000]: Syntax error or access violation: 1170 BLOB/TEXT column 'referral_code' used in key specification without a key length (SQL: alter table `users` add index `users_referral_code_index`(`referral_code`))
Below is my actual migration file. I can't see to tell why it's happening, as I've used this pattern before with other migrations.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddReferralInfoToUsersTable extends Migration
{
public function up()
{
Schema::table('shop_users', function (Blueprint $table) {
$table->text('referral_code')->nullable();
$table->integer('referral_uses')->nullable();
$table->integer('referral_revenue')->nullable();
$table->index(['referral_code']);
});
}
}
Try changing the datatype of referral_code to string and set a length.
Schema::table('shop_users', function (Blueprint $table) {
$table->string('referral_code',100)->nullable();
}
You can try this:
Schema::table('shop_users', function (Blueprint $table) {
$table->mediumText('referral_code')->nullable();
}
or
Schema::table('shop_users', function (Blueprint $table) {
$table->string('referral_code',100)->nullable();
}
or
Schema::table('shop_users', function (Blueprint $table) {
$table->longText('referral_code')->nullable();
}

A bug with renaming existing column in Laravel migrations

I added a new migration to rename an old column. Everything seems correct in this code, for me:
public function up()
{
Schema::table('reports', function (Blueprint $table) {
$table->renameColumn('reporter_id', 'created_by');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('reports', function (Blueprint $table) {
$table->renameColumn('created_by', 'reporter_id');
});
}
But then I faced an error:
In Connection.php line 664: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE. (SQL: ALTER TABLE reports CHANGE reporter_id created_b y INT NOT NULL)
In PDOStatement.php line 140: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE.
In PDOStatement.php line 138: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE. `
Could you help me to fix this?
First drop koreign key on up method.
public function up()
{
Schema::table('reports', function (Blueprint $table) {
$table->dropForeign('reports_reporter_id_foreign');
$table->renameColumn('reporter_id', 'created_by');
});
}
Then add foreign key again on down method.
public function down()
{
Schema::table('reports', function (Blueprint $table) {
$table->renameColumn('created_by', 'reporter_id');
$table->foreign('reporter_id')->references('id')->on('your_related_table')->onDelete('cascade');
});
}
I've encountered this too - it makes no sense, because when I use my standard SQL client to rename the same field ... it works. But it just doesn't work as a migration script. Thus, I ended up running the RENAME inside a DB::statement and that worked for me:
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
DB::statement("ALTER TABLE `mydb`.`mytable`
CHANGE `currentfieldname` `newfieldname`
INT(10) UNSIGNED NOT NULL;");
}

Can't Migrate Foreign Key

Here is Vehicles migrate :
public function up()
{
Schema::create('Vehicles', function (Blueprint $table) {
$table->increments('serie');
$table->string('color');
$table->integer('power');
$table->float('capacity');
$table->float('speed');
$table->integer('maker_id')->unsigned();
$table->timestamps();
});
Schema::table('Vehicles', function (Blueprint $table){
$table->foreign('maker_id')->references('id')->on('Makers');
});
}
Here is Makers Migrate :
public function up()
{
Schema::create('Makers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('phone');
$table->timestamps();
});
}
When I run artisan migrate , I got following error messages.
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `api`.`#sql-14b0_71
` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter t
able `Vehicles` add constraint `vehicles_maker_id_foreign` foreign key (`ma
ker_id`) references `Makers` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table `api`.`#sql-14b0_71
` (errno: 150 "Foreign key constraint is incorrectly formed")
I want to create two tables: Vehicles & Makers . In vehicles , maker_id is foreign key . I read the some references for laravel migration from various sources. But I can't find solution.
Pay attention to your migration files order, you have two solutions:
Change order: make Makers Migrate file first then Vehicles Migrate.
If Makers Migrate file comes after Vehicles Migrate file and you don't want to change order, move this:
Schema::table('Vehicles', function (Blueprint $table){
$table->foreign('maker_id')->references('id')->on('Makers');
});
To Makers Migrate file.
Now I delete makers migrate file and I run vehicles migrate file . Below is vehicles migrate file.
public function up()
{
Schema::create('Vehicles', function (Blueprint $table) {
$table->increments('serie');
$table->string('color');
$table->integer('power');
$table->float('capacity');
$table->float('speed');
$table->integer('maker_id')->unsigned();
$table->timestamps();
});
}
But I got the below errors
PHP Fatal error: Cannot redeclare class CreateVehicleTable in C:\xampp\htdocs\m
yownapi\database\migrations\2016_07_05_190215_vehicles_table.php on line 35
[Symfony\Component\Debug\Exception\FatalErrorException]
Cannot redeclare class CreateVehicleTable
Now it is work properly with below codes
Makers Migrate
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class MakersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('Makers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('phone');
$table->timestamps();
});
Schema::table('Vehicles', function(Blueprint $table){
$table->foreign('maker_id')->references('id')->on('makers');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('Makers');
}
}
Vehicles Migrate
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class VehiclesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('Vehicles', function (Blueprint $table) {
$table->increments('serie');
$table->string('color');
$table->float('power');
$table->float('capacity');
$table->integer('maker_id')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('Vehicles');
}
}
There is a simple way to do this. From your Vehicles migration, make the following changes
public function up()
{
Schema::create('Vehicles', function (Blueprint $table) {
$table->increments('serie');
$table->string('color');
$table->integer('power');
$table->float('capacity');
$table->float('speed');
$table->integer('maker_id')
$table->foreign('maker_id')
->references('id')->on('Makers');
$table->timestamps();
});
}
And since you will be adding the values form the id column in Makers, Laravel already has got your back, so there is really no need to add the unsigned() property there. Its still Okay if you add it there.
Hope I have answered your question. For More Details

Categories