Seeding a eloquent morphToMany relationship in laravel - laravel

I'm currently working on a laravel application where a user can like/dislike a content.
The migrations for the respective tables look as follows, where user_content_interaction is the relation between users and contents:
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('user');
}
}
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContentTable extends Migration
{
public const URL_LEN = 2083;
public const STR_LEN = 256;
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('content', function (Blueprint $table) {
$table->id();
$table->string('title', self::STR_LEN);
$table->date('release_date');
$table->enum('content_type', ['movie', 'tv_show', 'short_film', 'mini_tv_show']);
$table->json('genre');
$table->json('tags');
$table->integer('runtime');
$table->longText('short_description');
$table->json('cast');
$table->json('directors');
$table->enum('age_restriction', [0, 6, 12, 16, 18]);
$table->string('poster_url', self::URL_LEN);
$table->string('youtube_trailer_url', self::URL_LEN);
$table->string('production_company', self::STR_LEN);
$table->integer('seasons');
$table->integer('average_episode_count');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('content');
}
}
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserContentInteractionTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_content_interaction', function (Blueprint $table) {
$table->foreignId('content_id')->constrained('content');
$table->foreignId('user_id')->constrained('user');
$table->primary([
'content_id',
'user_id'
]);
$table->enum('like_status', ['liked', 'disliked'])->nullable();
$table->integer('dislike_count')->default(0)->nullable(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('user_content_interaction');
}
}
The respective models look like this:
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use Notifiable;
/**
* Name of the associated Table in the Database
*
* #var string
*/
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function contents(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Content::class);
}
}
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Content extends Model
{
use HasFactory;
/**
* Name of the associated Table in the Database
*
* #var string
*/
protected $table = 'content';
/**
*
* The primary key of the table
*
* #var string
*/
protected $primaryKey = 'id';
/**
*
* The columns that are fillable
*
* #var array
*/
protected $fillable = [
'title',
'release_date',
'content_type',
'genre',
'tags',
'runtime',
'short_description',
'cast',
'directors',
'age_restriction',
'poster_url',
'youtube_trailer_url',
'production_company',
'seasons',
'average_episode_count',
'updated_at'
];
protected $casts = [
'varchar' => 'string',
'release_date' => 'string',
'content_type' => 'string',
'genre' => 'string',
'tags' => 'string',
'runtime' => 'int',
'short_description' => 'string',
'cast' => 'string',
'directors' => 'string',
'age_restriction' => 'string',
'seasons' => 'int',
'average_episode_count' => 'int',
];
}
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserContentInteraction extends Pivot
{
use HasFactory;
/**
* Name of the associated Table in the Database
*
* #var string
*/
protected $table = 'user_content_interaction';
protected $primaryKey = 'content_id';
protected $foreignKey = 'user_id';
public function user(): BelongsTo
{
return $this->belongsTo('User');
}
public function content(): BelongsTo
{
return $this->belongsTo('Content');
}
}
And I'm trying to seed the database on my dev env like this:
User::factory()->count(4)
->hasAttached(
Content::factory()->count(10),
[
'like_status' => Arr::random(['liked', 'disliked']),
'created_at' => Carbon::now()
],
)
->create();
Which results in the following error when calling the create() method of the user factory:
Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::attach()
I'm looking for any advice how to fix this problem, maybe I made a design mistake in the first place. Or there is an easier way to construct this relation. Though it would be cool if I could keep the custom name for the relation. I'm very unfamiliar with Eloquent ORM so when there is a much easier and lightweight way of doing this feel free to point that out.
EDIT:
I adjusted the relationship migration to look like this:
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserContentInteractionTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_content_interactions', function (Blueprint $table) {
$table->id('user_content_interaction_id');
$table->foreignId('content_id')->constrained('content');
$table->foreignId('user_id')->constrained('user');
$table->enum('like_status', ['liked', 'disliked'])->nullable();
$table->integer('dislike_count')->default(0)->nullable(false);
$table->string('user_content_interaction_type');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('user_content_interaction');
}
}
fixed some errors and defined the relation in the model like this:
public function contents(): \Illuminate\Database\Eloquent\Relations\MorphToMany
{
return $this->morphToMany(Content::class, 'user_content_interaction');
}
Now I'm facing the problem that when seeding the ids from User and Content aren't taken into the relationship as foreign ids. The error message looks like this:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `user_content_interactions` (`content_id`, `created_at`, `like_status`, `user_content_interaction_id`, `user_content_interaction_type`) values (1, 2022-10-26 16:51:14, disliked, 1, App\Models\User))
I think I have some mistake in the seeder. I feel like I have to do something like this in the seeder:
User::factory()->count(4)
->hasAttached(
Content::factory()->count(10),
[
'user_id' => currentUser->id,
'content_id' => currentContent->id,
'like_status' => Arr::random(['liked', 'disliked']),
'created_at' => Carbon::now()
],
)
->create();

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

Laravel 8 Invalid Date time while seeding

I am new to laravel , I receive error while trying to seed data, I have done it successfully in two different tables but I am stuck at this one :
Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable = [
'Pmid',
'Ministry',
'P_name',
'Budget',
];
protected $casts = [
'Registered_at' => 'datetime',
];
}
Factory
<?php
namespace Database\Factories;
use App\Models\Project;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProjectFactory extends Factory
{
protected $model = Project::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'Pmid' => $this->faker->unique()->name(),
'Ministry' => $this->faker->name(),
'P_name' => $this->faker->name(),
'Budget' => $this->faker->name(),
'Registered_at' => now(),
];
}
}
Seeder
<?php
namespace Database\Seeders;
use App\Models\Project;
use Illuminate\Database\Seeder;
class ProjectTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Project::factory()->count(20)->create();
}
}
Migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProjectsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('Pmid')->unique();
$table->string('Ministry');
$table->string('P_name');
$table->integer('Budget');
$table->timestamp('Registered_at');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('projects');
}
}
error
Illuminate\Database\QueryException
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'Mathias Kuhlman' for column laravel.projects.Budget at row 1 (SQL: insert into projects (Pmid, Ministry, P_name, Budget, Registered_at) values (Nicholas Mayer, Ms. Donna Strosin, Hermann Bins, Mathias Kuhlman, 2021-12-05 08:36:39))
You're using
'Budget' => $this->faker->name(),
to create the data, but your migration shows that that column should be an integer :
$table->integer('Budget');
I suspect you've just copied and pasted the faker rows without changing the type of value being faked.

Encrypted Laravel model feilds do not update

I'm having trouble updating the github_oauth_token and github_oauth_refresh_token fields in my User model that have the encrypted cast. All other fields update fine and the casting is working as expected however the fields will not save to the database.
User model
namespace App\Models;
use App\Mail\EmailVerification;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'email_verification_token',
'password',
'github_oauth_token',
'github_oauth_refresh_token',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'github_oauth_token' => 'encrypted',
'github_oauth_refresh_token' => 'encrypted',
];
/**
* Set the user's github oauth token.
*
* #param string $value
* #return void
*/
public function setGithubOauthTokenAttribute($value)
{
$this->github_oauth_token = Crypt::encryptString($value);
}
/**
* Set the user's github oauth refresh token.
*
* #param string $value
* #return void
*/
public function setGithubOauthRefreshTokenAttribute($value)
{
$this->github_oauth_refresh_token = Crypt::encryptString($value);
}
}
User migration
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('first_name', 45);
$table->string('last_name', 45);
$table->string('email')->unique();
$table->string('email_verification_token', 30)->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('github_oauth_token')->nullable();
$table->string('github_oauth_refresh_token')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Controller method
public function handleGitHubCallback()
{
$gitHubUser = Socialite::driver('github')->user();
$user = Auth::user();
$user->github_oauth_token = $gitHubUser->token; // does not update
$user->github_oauth_refresh_token = $gitHubUser->refreshToken; // does not update
$user->first_name = 'Johnathan'; // updates fine
$user->save();
return redirect()->route('space.list.get')->with('success', Lang::get('messages.success_github_linked'));
}
The issue is in User Model.You are casting both fields in $cast property
protected $casts = [
'email_verified_at' => 'datetime',
'github_oauth_token' => 'encrypted',
'github_oauth_refresh_token' => 'encrypted',
];
So no need to add Mutators so remove both below Mutators.
public function setGithubOauthTokenAttribute($value)
{
$this->github_oauth_token = Crypt::encryptString($value);
}
public function setGithubOauthRefreshTokenAttribute($value)
{
$this->github_oauth_refresh_token = Crypt::encryptString($value);
}
Also if you want to use mutators then you have an error it should b like below
public function setGithubOauthTokenAttribute($value)
{
$this->attributes['github_oauth_token ']= Crypt::encryptString($value);
}
public function setGithubOauthRefreshTokenAttribute($value)
{
$this->attributes['github_oauth_refresh_token ']= Crypt::encryptString($value);
}

How can I create DB table in Trait?

I have created a trait that creates a table in the database if it doesn't exist.
the table is created perfectly in the DB but I get an error. The error is throw by Illuminate\Database\Eloquent\Concerns\HasAttributes.php
TRAIT:
namespace App\Traits;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
trait Translatable{
//CREATE LANGUAGES TABLE IF DOES NOT EXIST
public function createTranslationTable()
{
//ADD LANGUAGES TABLE IF DOES NOT EXIST
if(Schema::hasTable('languages') === false){
Schema::create('languages', function (Blueprint $table) {
$table->increments('id');
$table->string('language');
$table->string('slug');
});
}
//CREATE TRANSLATION TABLE IF DOES NOT EXIST
if(Schema::hasTable('translations') === false){
Schema::create('translations', function (Blueprint $table) {
$table->increments('id');
$table->string('model');
$table->string('language_id');
$table->foreign('language_id')->references('id')->on('languages')->onDelete('cascade');
$table->string('field_name');
$table->string('field_translation');
});
}
}
public function translateMe()
{
$this->createTranslationTable;
}
}
ERROR:
App\User::createTranslationTable must return a relationship instance.
I am using a trait because I want it to be able to use it with any model like so for eaxample:
class User extends Authenticatable
{
use Notifiable;
use Translatable;
/**
* Call Translatable.
*
* #return void
*/
public function __construct()
{
$this->translateMe();
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that are translatable.
*
* #var array
*/
protected $translatableItems = [
'name'
];
}
I found the solution and it was one simple one.
In the Translatable trait I was calling createTranslationTable method as a property instead then a method. so just adding the two parentesis fixed it.
BEFORE:
public function translateMe()
{
$this->createTranslationTable;
}
NOW:
public function translateMe()
{
$this->createTranslationTable();
}

Laravel 5 - Steam Auth not creating users

I'm trying to install this https://github.com/invisnik/laravel-steam-auth (with some of my own custom fields)
It works fine and all except for that it doesn't create the users (it creates the table) when I log in and I don't know why.
AuthController.php
namespace App\Http\Controllers;
use Invisnik\LaravelSteamAuth\SteamAuth;
use App\User;
use Auth;
class AuthController extends Controller
{
/**
* #var SteamAuth
*/
private $steam;
public function __construct(SteamAuth $steam)
{
$this->steam = $steam;
}
public function login()
{
if ($this->steam->validate()) {
$info = $this->steam->getUserInfo();
if (!is_null($info)) {
$user = User::where('steamid', $info->steamID64)->first();
if (is_null($user)) {
$user = User::create([
'username' => $info->personaname,
'avatar' => $info->avatarfull,
'steamid' => $info->steamID64
]);
}
Auth::login($user, true);
return redirect('/'); // redirect to site
}
}
return $this->steam->redirect(); // redirect to Steam login page
}
}
create_users_table.php
use Illuminate\Support\Facades\Schema;
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 (Blueprint $table) {
$table->increments('id');
$table->string('nickname');
$table->string('avatar');
$table->string('steamid')->unique();
$table->string('name');
$table->string('rank');
$table->string('community_id');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
web.php
Route::get('login', 'AuthController#login')->name('login');
Route::post('logout', 'Auth\LoginController#logout')->name('logout');
steam-auth.php
return [
/*
* Redirect URL after login
*/
'redirect_url' => '/',
/*
* API Key (http://steamcommunity.com/dev/apikey)
*/
'api_key' => 'xxx',
/*
* Is using https ?
*/
'https' => false
];
User.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 = ['nickname', 'avatar', 'steamid', 'name', 'rank', 'community_id', 'email', 'password'];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Any ideas?
UPDATE:
$info seems to return null and I have no clue why.

Resources