Laravel customized subscription updating subscribed_at for all the update - php

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');
// ...
});

Related

Backpack for Laravel (select2_multiple)

I need to select multiple users and display the names as developers. But I get this error.
Exception
Property [name] does not exist on this collection instance. (View: D:\Laravel\BoomTech\bug-tracker\resources\views\project_issues.blade.php)
Code that should show the name/s of users:
{{ $issue->developer->name }}
Issues table:
public function up()
{
Schema::create('issues', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreignId('project_id');
$table->foreignId('submitted_by_id');
$table->foreignId('developer_id');
$table->string('title', 255);
$table->string('comment', 255)->nullable();
$table->mediumText('description');
$table->text('status');
$table->text('type');
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
$table->timestamp('deleted_at')->nullable();
});
}
Issue User (pivot table):
Schema::create('issue_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreignId('user_id');
$table->foreignId('issue_id')->nullable();
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
});
Issue Model:
public function developer()
{
return $this->belongsToMany('App\Models\User', 'issue_user', 'issue_id', 'user_id');
}
IssueCRUDController:
CRUD::addField([ // Select2Multiple = n-n relationship (with pivot table)
'label' => "Developer",
'type' => 'select2_multiple',
'name' => 'developer', // the method that defines the relationship in your Model
// optional
'entity' => 'developer', // the method that defines the relationship in your Model
'model' => "App\Models\User", // foreign key model
'attribute' => 'name', // foreign key attribute that is shown to user
'pivot' => false, // on create&update, do you need to add/delete pivot table entries?
]);
This is many to many relationships so you need to do like this:
public function developers()
{
return $this->belongsToMany('App\Models\User', 'issue_user', 'issue_id', 'user_id');
}
#foreach($issue->developers() as $developer)
{{ $developer->name }}
#endforeach

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')}}

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]);
});

Laravel: migrate:refresh deosn't work

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();

Categories