SQLSTATE[42804] Error when trying to heroku run php artisan migrate - laravel

I've been trying to heroku run php artisan migrate from AWS Cloud9 without any success. How can I fix this problem? I would appreciate it very much if someone could help me. Thanks a lot!
I get three errors, all of which are saying
SQLSTATE[42804]: Datatype mismatch: 7 ERROR: column "administered" cannot be cast automatically to type smallint
HINT: You might need to specify "USING administered::smallint"
The migration file in question is as follows:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class ChangeFilariasisMedicationsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('filariasis_medications', function (Blueprint $table) {
$table->dropColumn('administered');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('filariasis_medications', function (Blueprint $table) {
$table->smallInteger ('administered');
});
}
}
Here is the related model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
// 追加
use App\AdministeredDate;
use App\User;
use Illuminate\Notifications\Notifiable;
use App\Notifications\ReminderMail;
class FilariasisMedication extends Model
{
protected $fillable = [
'start_date',
'number_of_times',
'counter',
'administered'
];
protected $dates = [
'start_date',
];
use Notifiable;
/**
* この投薬スケジュールを所有するユーザ(Userモデルとの関係を定義)
*/
public function medication_user()
{
return $this->belongsTo(User::class);
}
/**
* この投薬スケジュールに属する投薬確定日(AdministeredDateモデルとの関係を定義)
*/
public function administered_date()
{
return $this->hasMany(AdministeredDate::class);
}
}
Current description of filariasis_medications table:
mysql> describe filariasis_medications;
enter image description here

You put a space before the parenthesis in your migration, remove it.
from $table->smallInteger ('administered');
to $table->smallInteger('administered');

Related

Why "set null" is not working in onDelete in Laravel 9? [duplicate]

This question already has answers here:
How to fix error on Foreign key constraint incorrectly formed in migrating a table in Laravel
(29 answers)
Closed 7 months ago.
I have a Plan model and a User model, the User has one plan, and the plan belongs to many Users;
When I run php artisan migrate:fresh I get this error:
**
SQLSTATE[HY000]: General error: 1005 Can't create table service6_servicelandv1.0.users (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table users add constraint users_plan_id_foreign foreign key (plan_id) references plans (id) on delete set null)
**
here are the migrations:
User migrations
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string("avatar_name")->default("default-male.jpg");
$table->string('username')->unique();
$table->string("email")->unique();
$table->string('password');
$table->string("role")->default('Regular')->nullable();
$table->string("address")->nullable();
$table->bigInteger("reputation")->default(0);
$table->string("phone_number")->nullable();
$table->float("wallet", 10, 2)->default(0);
$table->unsignedBigInteger("plan_id")->nullable();
$table->unsignedBigInteger("option_id")->nullable();
$table->unsignedBigInteger("category_id")->nullable();//fav_category
$table->rememberToken();
$table->timestamp('email_verified_at')->nullable();
$table->timestamp("created_at")->useCurrent();
$table->timestamp("updated_at")->useCurrent();
$table->foreign("plan_id")->references("id")->on("plans")->onDelete('set null');
$table->foreign("option_id")->references("id")->on("options")->onDelete('set null');
$table->foreign("category_id")->references("id")->on("categories")->onDelete('set null');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
And for the Plan migrations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('plans', function (Blueprint $table) {
$table->id("id");
$table->string("name");
$table->integer("ads_number");
$table->decimal('amount_credit', 9, 3, true);
$table->decimal('price', 9, 3, true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('plans');
}
};
User Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
// use Laravel\Sanctum\HasApiTokens; // comment this
use Laravel\Passport\HasApiTokens; // include this
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
"avatar_name",
'username',
'email',
'password',
"address",
"role",
"reputation",
"wallet",
"phone_number",
"plan_id",
"option_id",
"category_id",
'confirmation_password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the image url.
*
* #param string $value
* #return string
*/
public function getAvatarNameAttribute($value){
return asset('storage/avatars/' . $value);
}
public function role(){
return $this->hasOne(Role::class);
}
public function category(){
return $this->hasOne(Category::class);
}
public function plan(){
return $this->hasOne(Plan::class);
}
public function option(){
return $this->hasOne(Option::class);
}
public function postStars(){
return $this->hasManyThrough(PostStar::class, Post::class);
}
}
Plan Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Plan extends Model
{
use HasFactory;
protected $fillable=[
"name",
"ads_number",
"amount_credit",
"price"
];
public function user(){
return $this->belongsTo(User::class);
}
}
Please I am really stuck for like two hours now and I don't understand what's going on??! what's wrong with that set null??
You can simply use this method to assign foreign keys:
$table->foreignId('user_id')
->nullable()
->constrained()
->onUpdate('cascade')
->onDelete('set null');
This is way better than other methods.
Check Documentation
In Laravel you can use nullOnDelete()
$table->foreignId('plan_id')
->nullable()
->constrained('plans')
->nullOnDelete();
Go through the Laravel Foreign Key Constraints to get some idea on Foreign Key declarations

Why won't artisan allow me to create data from my model?

I'm rather new to Laravel and am currently running Laravel 8.x on Windows 10. I've created a database table, model, factory and seeder for generating articles for an imaginary blog. (I'm imitating a tutorial on Laravel and Vue that I like on YouTube and also this article).
The article suggests verifying that everything works by going into php artisan tinker and executing the command:
Article::factory()->create();
When I do that, I get this message:
PHP Fatal Error: Class 'Article' not found in Psy Shell code on line 1
I have no idea what that's supposed to mean but I assume it's not happy with my code in some respect. I've looked at it as thoroughly as I can but don't see anything wrong based on the examples in the article. Could someone more knowledgeable in Laravel kindly eyeball this and tell me what I've done wrong? (For what it's worth, I tried User::factory()->create(); and it worked fine.)
Article.php is stored in app/Models and contains:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
protected $fillable = [
'title', 'body',
];
}
ArticleFactory.php is stored at database/factories and contains:
<?php
namespace Database\Factories;
use App\Models\Article;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class ArticleFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Article::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'title' => $this->faker->text(50),
'body' => $this->faker->text(200)
];
}
}
2020_11_30_034856_create_articles_table is stored at database/migrations and contains:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
Lastly, ArticlesTableSeeder.php is stored at database/seeders and contains:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class ArticlesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Article::factory()
->times(30)
->create();
}
}
Can anyone see why this code isn't working?
EDIT:
I tried Patricus' suggestion and it worked fine in tinker. However, when I tried php artisan db:seed, it failed. I got this error:
Seeding: Database\Seeders\ArticlesTableSeeder
Error
Class 'Database\Seeders\Article' not found
at C:\Laravel\larticles\database\seeders\ArticlesTableSeeder.php:16
12▕ * #return void
13▕ */
14▕ public function run()
15▕ {
➜ 16▕ Article::factory()
17▕ ->times(30)
18▕ ->create();
19▕ }
20▕ }
1 C:\Laravel\larticles\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:36
Database\Seeders\ArticlesTableSeeder::run()
2 C:\Laravel\larticles\vendor\laravel\framework\src\Illuminate\Container\Util.php:40
Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
Tinker doesn't run in a namespace. While it tries to help you out with some things related to models, it can't autocorrect namespaces on static method calls.
Your model is \App\Models\Article. In tinker, you need to call:
\App\Models\Article::factory()->create();

MorphMany laravel relation does not work for some reason

I am using laravel 5.6 version, here is my Test model file
<?php
namespace App\Model\data\Models;
use Illuminate\database\Eloquent\Model;
class Test extends Model
{
protected $guarded = ['id'];
protected $table = 'tests';
/*
* Test - TestTranslation relation
* Test has many translations
*/
public function translations()
{
return $this->hasMany('App\Model\Data\Models\TestTranslation');
}
/*
* Test - Image relation
* Test can have an thumbnail
*/
public function thumbnails()
{
return $this->morphMany('App\Model\Data\Models\Image', 'type');
}
}
Here is my Image model
<?php
namespace App\Model\Data\Models;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
protected $guarded = ['id'];
protected $table = 'images';
/*
* Image belongs to Post, Account, Comment
*/
public function type()
{
return $this->morphTo();
}
}
Here is my Database scheme for Images table:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('path');
$table->enum('type', ['avatar', 'thumbnail', 'generic'])->default('generic');
$table->integer('type_id')->unsigned()->nullable();
$table->enum('type_type',[
"Account",
"Comment",
"Post",
"Skill",
"Test"
])->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
In AppServiceProvider I linked 'Test' to my model file:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\DuskServiceProvider;
use Illuminate\Database\Eloquent\Relations\Relation;
use App\Model\Data\Models\Account;
use App\Model\Data\Models\EmailChangeConfirmation;
use App\Model\Observers\Common\AccountObserver;
use App\Model\Observers\Common\EmailChangeConfirmationObserver;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Schema::defaultStringLength(191);
Relation::morphMap([
'Account' => 'App\Model\Data\Models\Account',
'Comment' => 'App\Model\Data\Models\Comment',
'Post' => 'App\Model\Data\Models\Post',
'Skill' => 'App\Model\Data\Models\Skill',
'Test' => 'App\Model\Data\Models\Test'
]);
if(env('APP_ENV') != 'testing') {
Account::observe(AccountObserver::class);
EmailChangeConfirmation::observe(EmailChangeConfirmationObserver::class);
}
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
if ($this->app->environment('local', 'testing')) {
$this->app->register(DuskServiceProvider::class);
}
}
}
As you can see, I have more morhpMany types, and all of them works fine. But for some reason, this Test relation that I added recently always returns an empty collection, even tough I am sure that test has thumbnails. Cause:
in this screenshot, I have records in database that each test has two images. Their ID matches ids of created tests and type is "Test". I tried to clear all caches, run composer dump-autoload but none of them helped.
Maybe someone can help identify what is wrong here? Because as I said before other types as Post, Account works fine.

BadMethodCallException with message 'Method Illuminate\Database\Query\Builder::messages does not exist.'

I am trying to make a chatbox using Laravel and Vue.js. I am following this online tutorial. I have followed almost every step to a tee and I cannot tell why I am not getting the desired result. Here is what I have done thus far:
I have created a User model and a Message model with the correct table columns and migrations. In the User model I established a hasMany relationship with the Message model. In the Message model, I established a belongsTo relationship with User.
When I go into tinker, I can do:
factory(App\User::class)->create()
just fine, like the guy in the tutorial can do. However when I try to do:
App\User::find(4)->messages()->created(['message'=> "Hello from Sharon"])
I get this error:
BadMethodCallException with message 'Method Illuminate\Database\Query\Builder::messages does not exist.'
Here is my code:
User Model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','api_token',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function messages()
{
return $this->hasMany(Message::class);
}
}
Message Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
Message Migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->text('message');
$table->integer('user_id')->unsigned();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('messages');
}
}
If you could let me know what I am doing wrong, I would really appreciate it. Thanks.
Restart the php artisan tinker and re-run your code. It works:)
Seems you are getting this error:
BadMethodCallException with message 'Method Illuminate\Database\Query\Builder::created does not exist.'
To save models to relationships, use create method, but not created method, for example:
App\User::find(4)->messages()->create(['message'=>'Hello from Sharon']);
instead of App\User::find(4)->messages()->created(['message'=> "Hello from Sharon"])
try to use
App\User::find(4)->messages()->create(['message'=> "Hello from Sharon"])
or
App\User::find(4)->messages()->save(['message'=> "Hello from Sharon"])

How to save One to Many Relationship to database

Below is my LevelOneModel. I can't seem to figure out what I have not included. Please I need assistance.
What I want to achieve is to have all the users id in the levelone table
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class LevelOneModel extends Model
{
public function users(){
return $this->hasMany('App\User');
}
}
Below is my User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'phone',
'bank_name',
'acct_name',
'acct_number',
'profile_pix',
'sme',
'other_sme',
'password',
];
public function levelone()
{
return $this->belongsTo('App\LevelOneModel');
}
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
And below is my level one migration file
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLevelOneTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('level_one', function (Blueprint $table) {
$table->increments('id');
$table->integer('users_id')->unsigned();
$table->integer('upline_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('level_one');
}
}
Thanks
I notice some things in your code....
Looking at your classes, I understand the relationship is like this
a user belongs to one LevelOne only.
a LevelOne can have multiple users
If that is correct, the relationship is incorrectly build in the migration. Because you are adding a user_id to the level_one table.
It should be the other way around: the user tabel must contain a level_one_id.
And you should add it in the User migration, something like:
$table->int('level_one_id');
$table->foreign('level_one_id')->references('id')->on('level_one');
Now you have (in the database) a connection between User and LevelOne.
Now, if you query a user in your code, you should be able to get the LevelOne stuff as well. Make sure to really read the official Laravel documentation on relationships! It will really help you with examples.

Resources