Laravel Update or Insert value in null field - php

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

Related

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value Laravel 5.8

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into reports (patient_name, gender, ic, phone, current_location, status, emg_code, updated_at, created_at) values (dfd, female, sdf, sdf, sdf, sdf, sdf, 2022-06-13 05:53:11, 2022-06-13 05:53:11))
May I know how can I solve this? The user_id is the foreign key of the Users Table.
Users Table:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('profile_image');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
User Model:
public function reports()
{
return $this->hasMany(Report::class);
}
Reports Table:
Schema::create('reports', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('patient_name');
$table->string('gender');
$table->string('ic');
$table->string('phone');
$table->string('current_location');
$table->string('status');
$table->string('emg_code');
$table->softDeletes();
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
ReportController Create func.:
public function create()
{
$users = User::select('id', 'name')->get();
$users = $users->pluck('name');
return view('admin.reports.create', compact('users'));
}
ReportController Store func.:
public function store(Request $request)
{
$this->validate($request, [
'patient_name' => 'required|string',
'gender' => ['required', 'in:male,female'],
'ic' => 'required|string',
'phone' => 'required|string',
'current_location' => 'required|string',
'status' => 'required|string',
'emg_code' => 'required|string'
]);
$requestData = $request->all();
$report = Report::create($requestData);
foreach ($request->users as $user) {
$report->assignUser($user);
}
return redirect('admin/reports')->with('flash_message', 'Report added!');
}
HasUser Trait:
public function user()
{
return $this->belongsTo(User::class);
}
public function assignUser($user)
{
return $this->users()->save(
User::whereName($user)->firstOrFail()
);
}
Reports Model:
class Report extends Model
{
use HasUser;
protected $fillable = [
'user_id',
'patient_name',
'gender',
'ic',
'phone',
'current_location',
'status',
'emg_code'
];
}

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 "Method Illuminate\\Database\\Eloquent\\Collection::create does not exist." error while creating post for current login user

I want to insert a record in posts table for current logged in user via Eloquent relationships, But it returns error.
My code
return new PostResource(auth()->user()->posts->create([
'title' => 'lorem',
'body' => 'ipsum',
]));
Error
"message": "Method Illuminate\\Database\\Eloquent\\Collection::create does not exist.",
"exception": "BadMethodCallException",
"file": "C:\\xampp\\htdocs\\laravel\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Traits\\Macroable.php",
"line": 103,
User.php
protected $guarded = [];
public function posts()
{
return $this->hasMany('App\Post');
}
Post.php
protected $guarded = [];
public function user()
{
return $this->belongsTo('App\User');
}
PostResource.php
public function toArray($request)
{
return [
'title' => $this->title,
'body' => $this->body,
'created_at' => Carbon::parse($this->created_at)->format('Y-m-d H:m' ),
'updated_at' => Carbon::parse($this->updated_at)->format('Y-m-d H:m' )
]
}
users table migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->enum('role',['user','admin'])->default('user');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
posts table migration
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->longText('body');
$table->unsignedInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
You may use
$post = Post;
$post->title = 'lorem';
$post->body = 'ipsum';
//...
return new PostResource(auth()->user()->posts->save($post));
//...

Return count of a table's column via pivot table Laravel 5.2

So I have a user table, a role table and an intermediate table for those 2, user_role. It's a many-to-many relationship between the first 2 tables.
I want to return the count of the users which have a specific role but I can't seem to get it right.
My migrations:
user:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('password');
});
role:
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name', 40);
$table->string('description', 255);
});
user_role:
Schema::create('user_role', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id');
$table->integer('role_id');
});
Relationship between them:
public function users(){ //in role model
return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id')->withTimestamps();
}
public function roles(){ //in user model
return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id')->withTimestamps();
}
Role Seeder:
public function run()
{
Role::create([
'id' => 1,
'name' => 'Admin',
'description' => 'Admin User.'
]);
Role::create([
'id' => 2,
'name' => 'Vendor',
'description' => 'Vendor User.'
]);
Role::create([
'id' => 3,
'name' => 'User',
'description' => 'Simple User.'
]);
}
in controller:
public function adminDashboard(){
$users = User::all();
return view('admin.dashboard')->withUsers($users);
}
in view:
{{ $users->count() }}
This obviously, returns the total count of users in user table. Any ideas on how to return the count of users which have a specific role?
use $role->users()->count()
To iterate over the roles and display the count of users, you can use this:
public function adminDashboard(){
$roles = App\Role::all();
return view('admin.dashboard', compact('roles'));
}
In your dashboard view:
#foreach ($roles as $role)
<p>Role {{ $role->name }} has {{ $role->users()->count() }} users</p>
#endforeach

Categories