Laravel MariaDB Syntax Error because String Foreign Key - php

I've use this forum for a long time, but this is my first question. Im working with a friend in a Laravel project, and today I've found a strange situation.
Im creating the database with the Laravel Migration System (php artisan migrate: ...), but at moment Im not able to set a string as foreign key.
My Code look's like:
Vehicles Table
public function up()
{
Schema::create('vehiculos', function (Blueprint $table) {
$table->increments('id');
$table->string('matricula')->unique(); <----------
$table->string('marca');
$table->string('modelo');
$table->string('color');
$table->integer('cliente_id')->length(10)->unsigned();
$table->foreign('cliente_id')->references('id')->on('clientes')->onDelete('restrict');
$table->timestamps();
});
}
Reparations Table
public function up()
{
Schema::create('reparaciones', function (Blueprint $table) {
$table->increments('id');
$table->string('fechaE');
$table->string('fechaS');
$table->string('horas');
$table->string('km');
$table->string('observaciones');
$table->string('matricula')->nullable(); <-----------
$table->foreign('matricula')->references('matricula')->on('vehiculos');
$table->timestamps();
});
}
With the ->nulleable() stop crashing, but I think that is not correct at all. Can someone try to explain me the correct way please?
Glad to be in that forum.

Related

How to make laravel relations to work properly?

I am trying to get a object using the relations in laravel. In my project, 1 instalation belongs to 1 project and 1 project can have many installations. In the migration i have coded like this:
Projects:
Schema::create('projects', function (Blueprint $table) {
$table->id();
$table->bigInteger('user_id')->unsigned();
$table->string('name');
$table->boolean('removed');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
Installations:
Schema::create('installations', function (Blueprint $table) {
$table->id();
$table->bigInteger('country_id')->unsigned();
$table->bigInteger('project_id')->unsigned();
$table->bigInteger('building_admin_id')->unsigned()->nullable();
$table->string('name');
$table->boolean('removed');
$table->timestamps();
$table->foreign('country_id')->references('id')->on('countries');
$table->foreign('project_id')->references('id')->on('projects');
$table->foreign('building_admin_id')->references('id')->on('users');
And in the models...
Installation:
public function project(){
return $this->belongsTo(Project::class);
}
Project:
public function installations(){
return $this->hasMany(Installation::class);
}
The case is that i have a middleware to check that the author of the installation is the authenticated user by using:
if($request->installation->project->user->id != Auth::user()->id){
return back()->with('notAuthor', 'Access denied. You are not the owner of this installation.');
}
return $next($request);
And Laravel give me an error. I have check why, and doing dd($request->installation) i recieve the installation_id instead of the entire object.
The case is that i have used this middleware on the delete and modify installation methods, and it works, why in this case not?
I know that knowing the id of the installation i can get it by a query, but i want to know why this is not working, it have no sense for me..
If you need to see more of the code, text me.
Regards..

Laravel error while trying to migrate

I want to add another column to my database table users. I made a new migration named Modify_users_tablewhich has the code to add the column. There is nothing wrong with the source code because I used it before, but it gives me an error that something is wrong with the table roles? How can I solve this? Here is the error and the code that is related to the error
Here is the migration Roles:
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->string('role_name')->length(55)->unique();
$table->increments('id');
$table->timestamps();
});
}
You've got a number of problems. Your main problem is that you aren't adding a column to a table. Your script is instead trying to create a new table, as seen in this line:
Schema::create('roles', function (Blueprint $table) {
You said you are trying to add a column to the users table, but you aren't even working with the user's table: you are instead creating a table called roles which already exists. The simplest solution is to do what Dhaval suggests: ditch the migration you are added, update the migration that creates the user tables, nuke and start over.
The "right" answer is to create a new migration and put in the instructions to add the column to the users table as well as instructions on removing it. Then you can just do a simple migration instead of nuking your database. That would look something like this:
public function up()
{
Schema::table('users', function ( Blueprint $table ) {
$table->string('last_name')->after( 'first_name' )->default( '' );
});
}
public function down()
{
Schema::table( 'users', function ( Blueprint $table ) {
$table->dropColumn( ['last_name'] );
});
}
You need to run
php artisan migrate:rollback
if that also fails just go in and drop all the tables which you may have to do as it seems your migration table is messed up or your roles table when you ran a previous rollback did not drop the table.
or you can use migrate:reset command will roll back all of your application's migrations:
php artisan migrate:reset
I had the same issue and I tried something like this and it works perfect for me. My Laravel version is 5.5.
public function up()
{
Schema::connection('mysql2')->create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('image');
$table->timestamps();
});
}
public function down()
{
Schema::connection('mysql2')->dropIfExists('images');
}
I had to connections in my project one is mysql and other is mysql2 becuase my project is for database with multiple connections.
So my solution is that to try specifying the connection to your database in the function.
By default connection is mysql if you havent specifed it in the function, Example is given below. Hope this helps!
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email',60)->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
And so when you migrate using php artisan it doesn't show errors,
remove the table from the database ( I did it manually the first time I had this issue)
and make this change in the create_users_table migration as such
$table->string('email', 60)->unique();
and this worked for me..
Hope this helps you as well

Laravel rename column loss all data

I am new to Laravel and I create a users table using php artisan migrate command:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('username');
$table->string('email');
$table->string('password');
$table->rememberToken();
});
After that I just needed to change the username column as first_name then I change the schema as follows:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('first_name');
$table->string('email');
$table->string('password');
$table->rememberToken();
});
If I run the php artisan migrate command again, it says Nothing to migrate, then I used rollback, and I lose all table data.. How can I edit table structure without affecting my data? I hate Laravel doc
Let's start with your schema. Your table name is users. It contains a column named username and you want to change it to first_name without losing existing data. You need to create a new migration for this change.
php artian make:migration rename_columns_to_users_table --table=users
A new migration file will be created in your migrations directory. Open it and change it like this:
Schema::table('users', function ($table) {
$table->renameColumn('username', 'first_name');
});
Save it and then again run
php artisan migrate
You column name will be renamed immediately without losing your old data. Hope you got it now.
You will find more details here: https://laravel.com/docs/5.3/migrations#renaming-columns
You should create and register new migration and use Schema::table() and renameColumn() methods to rename a column:
Schema::table('users', function ($table) {
$table->renameColumn('from', 'to');
});
To rename a column, you may use the renameColumn method on the Schema builder.

Add extra table using Laravel Migration

I am using Laravel 5.2. I have created basic tables using migration method. But now I need to add another extra table. After creating my schema, I have given php artisan migrate command. But it shows error like base table or view already exists Table:Users. I know why this happen. The migration command trying to recreate the table which already have. But I need to add another extra table in Laravel via Migration. I have gone through this https://laravel.com/docs/5.2/migrations But I can't get any solution.
If you want to create another table, just create new migration and run it.
If you're trying to add columns into existinng table, use Schema::table instad of Schema::create.
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
}
Schema::table('articles', function (Blueprint $table) {
$table->string('description');
}
If you already executed php artisan migrate then next time it will give you error saying "Table already exists.".
So if you want to execute only a particular migration then either you can temporarily move all migration's php file which are executed, out of database/migrations folder and then execute
php artisan migrate
or
you can execute migration from tinker i.e. first execute php artisan tinker and then execute content of up method from the migration but without parameter type Blueprint.
Eg.
If following is your migration up method content
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
});
then you will have to execute
Schema::create('users', function ($table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
});

Laravel migration blows up on foreign key. Already using unsigned int and referencing created tables

I am racking my brain trying to figure this out, but to no avail. Please help.
I have the following code:
Schema::create('inventory_category_relations', function(Blueprint $table)
{
$table->increments('id');
$table->integer('inventory_category_id')->unsigned()->nullable()->default(null);
$table->foreign('inventory_category_id')->references('id')->on('inventory_categories');
$table->integer('inventory_id')->unsigned()->nullable()->default(null);
$table->foreign('inventory_id')->references('id')->on('inventory');
$table->timestamps();
$table->softDeletes();
});
The above code references an 'inventory' and 'inventory_categories' table, which tables are already created and referenced by other tables, which work perfectly. However, every time I try to run "php artisan migrate" with the above code, my terminal blows up.
Edit
Here are my original 'inventory' and 'inventory_categories' create statements:
Schema::create('inventory_categories', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
$table->softDeletes();
});
Schema::create('inventory', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->mediumText('basic_description');
$table->unsignedInteger('inventory_type_id');
$table->foreign('inventory_type_id')->references('id')->on('inventory_types')->onDelete('cascade');
$table->unsignedInteger('vendor_id');
$table->foreign('vendor_id')->references('id')->on('vendors')->onDelete('cascade');
$table->unsignedInteger('inventory_category_id');
$table->foreign('inventory_category_id')->references('id')->on('inventory_categories')->onDelete('cascade');
$table->decimal('price',10,2);
$table->decimal('compare_price',10,2);
$table->integer('quantity');
$table->string('sku');
$table->string('barcode');
$table->boolean('no_stock_purchase')->default(0);
$table->boolean('shipping_address')->default(0);
$table->decimal('shipping_weight')->default(0);
$table->boolean('free_shipping')->default(0);
$table->boolean('taxes')->default(1);
$table->boolean('multiple_options')->default(0);
$table->boolean('custom_variants')->default(0);
$table->boolean('active')->default(1);
$table->boolean('has_publish_date')->default(0);
$table->dateTime('start_date');
$table->dateTime('end_date');
$table->string('url');
$table->string('meta_title');
$table->mediumText('meta_description');
$table->boolean('has_commission')->default(0);
$table->unsignedInteger('created_by');
$table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
I am using laravel 4.2 on a wamp server
Update:
Ok I used "php artisan migrate > migrate_error.log" and posted the results to pastebin. The file was too large, but I posted what would fit:
http://pastebin.com/J8KZn7R5
What you've got there is a stack trace due to a failed SQL statement. It's saying that it can't add the foreign key constraint of inventory_category_relations.inventory_category_id to reference inventory_categories.id.
My thought would be to remove the following portion
->nullable()->default(null)
from the two column creation statements in your inventory_category_relations migration. The columns they both reference are auto-incremented primary key IDs; those should never resolve to NULL anyway.
I solved it:
It turns out my database configurations were wrong. My tables were configured to MyISAM, when they should have been InnoDB.

Categories