Laravel: migrate:refresh deosn't work - php

I learn Laravel from udemy.com and I have a problem with migrate:refresh command. So, when I try use it I'll see information
Array to string conversion
I try solve my problem so propably I made new mistakes so it's my code:
Into UserTableSeeder
public function run()
{
App\User::create([
'name' => 'Kati',
'email' => 'hello#hello.pl',
'password' => bcrypt('password'),
'admin' => 1
]);
App\Profile::create([
'user_id' => $user->id,
'avatar' => 'link to avatar',
'about' => 'Interested description',
'youtube' => 'youtube.com',
'facebook' => 'facebook.com'
]);
}
Into migrations
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->text('about');
$table->string('youtube');
$table->string('facebook');
$table->timestamps();
});
}
And
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->boolean('admin')->default(0);
$table->rememberToken();
$table->timestamps();
});
}
I tryed clone my respository from github and refreshing but I had this some problem.

This should work:
public function run()
{
$user = App\User::create([
'name' => 'Kati',
'email' => 'hello#hello.pl',
'password' => bcrypt('password'),
'admin' => 1
]);
App\Profile::create([
'user_id' => $user->id,
'about' => 'Interested description',
'youtube' => 'youtube.com',
'facebook' => 'facebook.com'
]);
}
In your run statement your referencing in the App\Profile creation process the variable $user->id. However, it is not instantiated yet.
In addition, you are trying to add an avatar to your profile, therefore you should add this to the Profile-table or, like I did it, delete it from your seeder.

I solved it in my seeder:
'user_id' =>\App\User::pluck('id')->random();

Related

Laravel customized subscription updating subscribed_at for all the update

I am using a customized subscription which is not laravel's default cashier.
and the migration looks as below
public function up()
{
Schema::create('subscriptions', function (Blueprint $table) {
$table->id();
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->bigInteger('plan_id')->unsigned();
$table->foreign('plan_id')->references('id')->on('subscription_plans');
$table->bigInteger('transaction_id')->unsigned();
$table->foreign('transaction_id')->references('id')->on('transactions');
$table->timestamp('subscribed_at');
$table->timestamp('expires_at')->nullable();
$table->boolean('is_active')->default(true);
$table->json('benefits');
$table->timestamps();
});
}
and the user relation as below
// subscription
public function subscriptions(): HasMany
{
return $this->hasMany(Subscription::class, 'user_id')->orderBy('subscribed_at', 'asc');
}
on a specific case, I update the is_active flag.
// in user model : User.php
public function createSubscription(Plan $plan): Subscription
{
$transaction = $this->createTransaction($plan);
$data = [
'plan_id' => $plan->id,
'transaction_id' => $transaction->id,
'is_active' => true,
'subscribed_at' => now(),
'expires_at' => now()->addDays($plan->validity),
'is_active' => true,
'benefits' => $plan->benefits
];
$this->subscriptions()->update(['is_active' => false]);
return $this->subscriptions()->create($data);
}
but it's updating all the subscribed_at timestamps.
Please help me to solve this.
Change the subscribed_at column type from timestamp to dateTime (Or make it nullable())
Like:
Schema::create('subscriptions', function (Blueprint $table) {
// ...
$table->dateTime('subscribed_at');
// ...
});

Laravel Update or Insert value in null field

I'm having trouble inserting value in null field.
this is the table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('username')->unique()->nullable();
$table->string('mobile_no')->nullable();
$table->string('address')->nullable();
$table->string('email')->unique();
$table->boolean('role_name')->default(0);
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
this is the UserController
public function update(Request $request, User $user)
{
$request->validate([
'name' => 'required|max:255',
'mobile_no' => 'required|max:11',
'address' => 'required|max:255',
]);
$user->update($request->all());
return redirect()->route('profile')->with('updated', 'Profile successfully updated');
}
I don't get error and the $message always says : "Profile successfully updated" but it is not really updated.
Have you declared that field as fillable in your model?
protected $fillable = [
'name', 'username',.....
];
https://laravel.com/docs/8.x/eloquent#inserting-and-updating-models

Attempt to read property 'avatar' null when register with laravel

I am using Laravel 8 and have an error,
If I register a user using Laravel it says:
Attempt to read property "avatar" on null in views at user index and another one did work properly...
and if login using Laravel from creating the user in admin pages, it says:
These credentials do not match our records.
UsersController.php:
public function index() {
return view ('admin.users.index', ['users'=>User::all()]);
}
public function store(Request $request) {
//
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'password' => 'required'
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt('password')
]);
$profile = Profile::create([
'user_id' => $user->id,
'avatar' => 'uploads/avatars/1.png'
]);
session()->flash('success', 'User berhasil ditambah');
return redirect()->route('users');
}
I have using <img src="{{asset(auth()->user()->profile->avatar)}}
or <img src="{{asset($user->profile->avatar)}} in the views and didn't work too.
This is user table:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->boolean('admin')->default(0);
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
This profile table:
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->string('avatar')->nullable();
$table->integer('user_id');
$table->text('about')->nullable();
$table->string('facebook')->nullable();
$table->string('youtube')->nullable();
$table->timestamps();
});
User Model
public function profile() {
return $this->hasOne(Profile::class);
}
Profile Model
public function user() {
return $this->belongsTo(User::class);
}
This error
Attempt to read property "avatar" on null
indicates that there are some users with no profile and that is why $user->profile returns null so you can make it optional using if condition like this:
{{$user->profile !== null ? asset($user->profile->avatar) : asset('path-to-default-image')}}

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0430142821' for key 'users_melli_unique'

I know this question asked before but i want to know how can i stop to showing this error and instead of this i want to show custom error message to user in blade.
This is user migration :
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('image')->nullable();
$table->string('email')->unique();
$table->boolean('is_superuser')->default(0);
$table->boolean('is_staff')->default(0);
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('phone_number')->nullable()->unique();
$table->enum('two_factor_type', ['off', 'sms']);
$table->string('melli')->nullable()->unique();
$table->rememberToken();
$table->timestamps();
});
}
UPDATE:
This is my insert function :
$user = User::find(auth()->user()->id);
$request->validate([
'melli' => 'min:10|max:10',
'cart' => 'min:16|max:16'
]);;
$user->update([
'name' => $request['name'],
'cart' => $request['cart'],
'melli' => $request['melli'],
'gender' => $request['gender']
]);
return redirect(route('profile.index'));
This error happens when i have a melli in my database like 1234567890 and i try to write 1234567890 again, because the melli field is unique.
You need unique validation rule and ignore that id in the update.
You can do like this:
$request->validate([
'melli' => 'min:10|max:10|unique:users,melli,' .$user->id,
]);
Or
$request->validate([
'melli' => [
'min:10',
'max:10',
Rule::unique('users')->ignore($user->id, 'id')
],
'cart' => 'min:16|max:16'
]);
I think that's what you need.
Also, some helpful answer.

Foreign Key missing when using relationship

Hi i'm trying to seed my database with fake data.
For that i've 2 models User and Patient.
in User.php
public function patients()
{
return $this->hasMany(Patient::class);
}
in Patient.php
public function user()
{
return $this->belongsTo(User::class);
}
My DatabaseSeeder.php
$users = factory(User::class, 10)->create();
$users->each(function ($user) {
$user
->patients()
->saveMany(factory(Patient::class, 10)
->create());
});
When i'm trying to seed with relationship I got the error
general error: 1364 Field 'user_id' doesn't have a default value
isn't the relationship supposed to fill the foreign key ?
// Edit more information
Patient Migration
if (Schema::hasTable($this->setSchemaTable)) return;
Schema::create($this->setSchemaTable, function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('firstname', 191);
$table->string('lastname', 191);
$table->date('birth_date');
$table->nullableTimestamps();
$table->softDeletes();
$table->foreign('user_id')->references('id')->on('users');
});
PAtientFactory
$factory->define(Patient::class, function (Faker $faker) {
return [
'firstname' => $faker->firstname,
'lastname' => $faker->lastname,
'birth_date' => $faker->date,
];
});
user Migration
if (Schema::hasTable($this->setSchemaTable)) return;
Schema::create($this->setSchemaTable, function (Blueprint $table) {
$table->increments('id');
$table->string('firstname', 191);
$table->string('lastname', 191);
$table->string('email', 191)->unique();
$table->string('password', 191);
$table->rememberToken();
$table->string('lang')->default('en');
$table->tinyInteger('change_password')->default('1');
$table->softDeletes();
$table->nullableTimestamps();
});
UserFactory
$factory->define(App\Models\User::class, function (Faker $faker) {
return [
'firstname' => $faker->firstname,
'lastname' => $faker->lastname,
'email' => $faker->unique()->safeEmail,
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => Str::random(10),
'lang' => $faker->randomElement(['fr', 'en']),
'change_password' => 0,
];
});
Try following, it's working in my project. You can not use relationship to create multiple records the way you are doing. Following will achieve the same.
factory(User::class, 10)->create()->each(function($u) {
factory(Patient::class, 10)->create(['user_id' => $u->id]);
});

Categories