Cannot update using findOrFail method in Laravel - php

I am a newbie in Laravel. So I am trying to update my form but it kept returning fail because I used the findOrFail method on the Controller.
But when I tried to dump the Id, the Id does exists.
Only when I call it using the method, it returns null.
Route for update
Route::post('/alumni/updateProfile','AlumniController#update');
Update method
public function update(Request $request, User $user, Profile $profile)
{
$user->roles()->sync($request->roles);
$profile = Profile::findOrFail(Auth::user()->id);
$profile->name = $request->name;
$profile->matric_no = $request->matric_no;
$profile->contact_no = $request->contact_no;
$profile->address = $request->address;
$profile->batch_year = $request->batch_year;
$profile->graduation_year = $request->graduation_year;
$profile->date_of_birth = $request->date_of_birth;
$profile->area_of_interest = $request->area_of_interest;
$profile->start_date = $request->start_date;
$profile->company_name = $request->company_name;
$profile->job_title = $request->job_title;
$profile->social_network = $request->social_network;
$profile->save();
return view('/home', compact('profile'));
}
Profile model
class Profile extends Model
{
// protected $guarded = [];
protected $fillable = ['alumni_id'];
protected $table = 'profiles';
public $timestamps = false;
public function users()
{
return $this->belongsTo('App\User');
}
}
User model
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function profiles()
{
return $this->belongsTo('App\Profile');
}
public function hasAnyRoles($roles)
{
if($this->roles()->whereIn('name', $roles)->first()){
return true;
}
return false;
}
public function hasRole($role)
{
if($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
Glad if any of you noticed anything, thank you.

You can write findOrFail() in try catch blog and get the exception in catch blog to understand the error.
OR
you can write below code instead of findOrFail().
$profile = Profile::where('id', '=', Auth::user()->id);
if( $profile->count() ){
# Assignment of values to database columns fields and then save.
$profile->save();
} else {
# Print No Record Found.
}

Related

Codeigniter 4 ignoring model insert callback

Running model->insert() from my controller does not trigger the beforeInsert function, below is my model and the function from my conntroller
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model {
protected $table = 'admin_users';
protected $useAutoIncrement = true;
protected $primaryKey = 'row_uid';
protected $returnType = 'object';
protected $beforeInsert = ['passwordHash'];
protected $allowCallbacks = true;
protected $allowedFields = ['id', 'row_uid', 'username', 'email', 'password', 'active', 'deleted_at'];
public function __construct() {
return $this;
}
protected function passwordHash($data) {
$data['data']['row_uid'] = uniqid('',true);
$data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
if(isset($data['data']['password_c'])) unset($data['data']['password_c']);
return $data;
}
}
And here is the controller function
public function postRegister() {
$request = \Config\Services::request();
if($post = $request->getPost()) {
$valid = $this->validate([
'username' => 'is_unique[admin_users.username]', // Change table name to be dynamic
'email' => 'required|valid_email|is_unique[admin_users.email]', // Change table name to be dynamic
'password' => 'required|min_length[10]|max_length[100]',
'password_c' => 'required|matches[password]',
]);
if(!$valid) {
$this->data['errors'] = $this->validator->getErrors();
foreach($post as $key => $e) {
if(isset($this->data['errors'][$key])) {
$this->data['invalid_fields'][$key] = ' is-invalid';
} else $this->data['invalid_fields'][$key] = '';
}
return $this->getRegister();
}
$l = $this->userModel->insert($post);
echo '<pre>',var_dump($l),'</pre>';exit;
}
}
I determine that the callback is not running because the password is not hashed, the uid is not generated and running die or exit does nothing.
Thank you
EDIT:
I got it working by adding allowCallback() but i shouldn't need this?
$this->userModel->allowCallbacks(true)->insert($post);
1 - Delete the constructor method in the model; you don't need that .
2- set protected $allowCallbacks = true; before $beforeInsert = ['passwordHash'];
The above approach is standard coding in the Codeigniter framework. If those steps didnt resolve the problem, the solution is to check the database for the row_uid and password types.

Sending notification toDatabase Laravel 5.7

I'm trying to send notification to database but having some trouble. In my notifications table, DATA row is null {"estate":null}. it should retrieve title and body though.
my controller is:
use Illuminate\Http\Request;
use App\Notifications\NewEstateNotification;
use App\Estate;
use App\User;
public function __construct()
{
$this->middleware('auth');
}
public function newEstate()
{
$estate = new Estate;
$estate->user_id = auth()->user()->id;
$estate->title = 'Laravel Notification';
$estate->body = 'This is the new Estate';
$estate->save;
$user = User::where('id', '!=', auth()->user()->id)->get();
if (\Notification::send($user, new NewEstateNotification(Estate::latest('id')->first())))
{
return back();
}
}
NewEstateNotification class:
use Queueable;
protected $estate;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($estate)
{
$this->estate = $estate;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'estate' => $this->estate,
];
}
Any idea where am I doing wrong?
try to used like that
public function newEstate()
{
$estate = new Estate();
$estate->user_id = auth()->user()->id;
$estate->title = 'Laravel Notification';
$estate->body = 'This is the new Estate';
$estate->save();
$users = User::where('id', '!=', auth()->user()->id)->get();
//used like that
foreach($users as $user) {
$user->notify(new NewEstateNotification($estate));
}
return back();
}
in NewEstateNotification add toArray() method
public function toDatabase($notifiable)
{
return [
'estate' => $this->estate->toArray(),
];
}
it's also working fine if you want to used
\Notification::send($user, new NewEstateNotification($estate))

Laravel call to a member function addEagerConstraints() on boolean

I'm getting the following error whenever i go on to a users page, its supposed to show if the authenticated user is already following the user that the profile is on.
Could this be a problem with the relationship setup, it hasMany
Stack trace
local.ERROR: Call to a member function addEagerConstraints() on
boolean {"userId":1,"email":"fakeemail#aol.com","exception":"[object]
(Symfony\Component\Debug\Exception\FatalThrowableError(code: 0):
Call to a member function addEagerConstraints() on boolean at
/Applications/MAMP/htdocs/elipost/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:522)"}
[]
UserController.php
public function getProfile($user)
{
$users = User::with([
'posts.likes' => function($query) {
$query->whereNull('deleted_at');
$query->where('user_id', auth()->user()->id);
},
'follow',
'follow.follower'
])->with(['followers' => function($query) {
$query->with('follow.followedByMe');
$query->where('user_id', auth()->user()->id);
}])->where('name','=', $user)->get();
$user = $users->map(function(User $myuser){
return ['followedByMe' => $myuser->followers->count() == 0];
});
if (!$user) {
return redirect('404');
}
return view ('profile')->with('user', $user);
}
MyFollow(model)
<?php
class MyFollow extends Model
{
use SoftDeletes, CanFollow, CanBeFollowed;
protected $fillable = [
'user_id',
'followable_id'
];
public $timestamps = false;
protected $table = 'followables';
public function follower()
{
return $this->belongsTo('App\User', 'followable_id');
}
public function followedByMe()
{
return $this->follower->getKey() === auth()->id();
}
}
MyFollow
use Overtrue\LaravelFollow\Traits\CanFollow;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;
class MyFollow extends Model
{
use SoftDeletes, CanFollow, CanBeFollowed;
protected $fillable = [
'user_id',
'followable_id'
];
public $timestamps = false;
protected $table = 'followables';
public function follower()
{
return $this->belongsTo('App\User', 'followable_id');
}
public function followedByMe()
{
return $this->follower->getKey() === auth()->id();
}
}
Post
class Post extends Authenticatable
{
protected $fillable = [
'title',
'body',
'user_id',
'created_at',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public function likes()
{
return $this->hasMany('App\Like');
}
public function likedByMe()
{
foreach($this->likes as $like) {
if ($like->user_id == auth()->id()){
return true;
}
}
return false;
}
}
Likes
<?php
namespace App;
use App\Post;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Like extends Model
{
use SoftDeletes;
protected $fillable = [
'user_id',
'post_id'
];
}
User(model)
class User extends Authenticatable
{
use Notifiable,CanFollow, CanBeFollowed;
/**
* 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',
];
public function posts()
{
return $this->hasMany(Post::class);
}
public function images()
{
return $this->hasMany(GalleryImage::class, 'user_id');
}
public function likes()
{
return $this->hasMany('App\Like');
}
public function follow()
{
return $this->hasMany('App\MyFollow');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}
As Jonas Staudenmeir stated, followedByMe isn't a relationship, it's a regular function and what it does is returning a boolean. I'm confused at why you've got a follow on your user model and trying to get information from the follow's follower? Just simplify, I see too much unneeded eager loading here.
Searching by indexed elements (id) > searching by name, any day of the week
Edit:
UserController
public function getProfile(Request $request, $id)
{
//$request->user() will get you the authenticated user
$user = User::with(['posts.likes','followers','follows','followers.follows'])
->findOrFail($request->user()->id);
//This returns the authenticated user's information posts, likes, followers, follows and who follows the followers
//If you wish to get someone else's information, you just switch
//the $request->user()->id to the $id if you're working with id's, if you're
//working with names, you need to replace findOrFail($id) with ->where('name',$name')->get() and this will give you
//a collection, not a single user as the findOrFail. You will need to add a ->first() to get the first user it finds in the collection it results of
//If you're planning on getting an attribute (is_following = true) to know if
//the authenticated user is following, you can use an accessor in the User model and write this after you've fetched the instance of the User
//$user->append('is_following');
return view ('profile')->with('user', $user);
}
User Model
//Accessor
//People who this user follows
public function getIsFollowingAttribute()
{
return MyFollow::where('followable_id',$this->attributes['id'])->where('user_id',Auth()->user()->id)->count() > 0 ? true : false;
}
//Relationships
//People who this user follows
public function follow()
{
return $this->hasMany('App\MyFollow','user_id','id');
}
//People who follows this user
public function followers()
{
return $this->hasMany('App\MyFollow','followable_id','id');
}
//Posts of this user
public function posts()
{
return $this->hasMany('App\Post','user_id','id');
}
//Likes of this user, not sure about this one tho, we're not using this for now but it could come in handy for you in the future
public function likes()
{
return $this->hasManyThrough('App\Likes','App\Post','user_id','user_id','id');
}
Post Model
//Who like this post
public function likes()
{
return $this->hasMany('App\Post','user_id','id');
}
MyFollow Model
//Relationships
//People who follow this user
public function followers()
{
return $this->hasMany('App\MyFollow','followable_id','user_id');
}
//Relationships
//People who this user follows
public function follow()
{
return $this->hasMany('App\MyFollow','user_id','followable_id');
}
With the help of #abr i found a simple fix, simple solution.
MyFollow.php(model)
public function followers()
{
return $this->hasMany('App\MyFollow','followable_id','user_id');
}
//Relationships
//People who this user follows
public function follow()
{
return $this->hasMany('App\MyFollow','user_id','followable_id');
}
User.php(model)
public function getIsFollowingAttribute()
{
return MyFollow::where('followable_id',$this->attributes['id'])->where('user_id',Auth()->user()->id)->count() > 0 ? true : false;
}
public function follow()
{
return $this->hasMany('App\MyFollow');
}
UserController.php
public function getProfile($user)
{
$users = User::with(['posts.likes' => function($query) {
$query->whereNull('deleted_at');
$query->where('user_id', auth()->user()->id);
}, 'followers','follow.followers'])
->with(['followers' => function($query) {
}])->where('name','=', $user)->get();
$user = $users->map(function(User $myuser){
$myuser['followedByMe'] = $myuser->getIsFollowingAttribute();
return $myuser;
});
if(!$user){
return redirect('404');
}
return view ('profile')->with('user', $user);
}
it works now. :)

how to get id of table in relationship to use in other table in this relation?

i have relation between Service and Services_Gallery one to many, and i want to use id of Service when i insert new image to Services_Gallery, and this is my Controller:
public function save(Request $request)
{
$this->validate($request,[
'image' => 'required|image|mimes:jpeg,jpg,png,svg|max:1024'
]);
$services_Gallery = new Services_Gallery();
$services_Gallery->image = $request->image->move('Uploads', str_random('6') . time() . $request->image->getClientOriginalName());
$services_Gallery->Service::all(id) = $request->service_id; //The problem here
$services_Gallery->save();
return back();
}
this is my Models:
class Service extends Model
{
protected $table = 'services';
protected $fillable = [
'en_main_title',
'ar_main_title',
'en_sub_title',
'ar_sub_title',
'en_content_title',
'ar_content_title',
'en_content',
'ar_content',
'priority',
];
public function gallery()
{
return $this->hasMany('App\Services_Gallery','service_id');
}
}
class Services_Gallery extends Model
{
protected $table = 'services_galleries';
protected $fillable = [
'image',
'service_id',
];
public function gallery(){
return $this->belongsTo('App\Service','service_id');
}
}
Exapmle:
$modelOfService = Service::where('param_x', $request->service_id)->first();
$id = $modelOfService->id;
Is that you need?

Save object with foreign keys in laravel

I use PHP, Laravel 5.2 and MySQL.
During user registration, I need to create a new Patient. But, Patient has user id, contact id and guardian id(foreign keys).
When I try to save() the patient, I get the following exception:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'patient_id' in
'field list' (SQL: update users set patient_id = 0, updated_at =
2016-06-07 12:59:35 where id = 6)
The problem is that I DO NOT have patient_id column. Instead I have patientId.
I don't know how to fix this issue. Any help will be appreciated. I can include the migration files if this is important.
UserController.php
public function postSignUp(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:100',
'password' => 'required|min:6'
]);
$guardian = new Guardian();
$guardian->guardianId = Uuid::generate();;
$guardian->save();
$contact = new Contact();
$contact->contactId = Uuid::generate();
$contact->save();
$user = new User();
$user->email = $request['email'];
$user->name = $request['name'];
$user->password = bcrypt($request['password']);
$user->save();
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
$patient->contact()->save($contact);
$patient->guardian()->save(guardian);
$patient->save();
Auth::login($user);
// return redirect()->route('dashboard');
}
Patient.php
class Patient extends Model
{
protected $primaryKey='patientId';
public $incrementing = 'false';
public $timestamps = true;
public function user()
{
return $this->hasOne('App\User');
}
public function contact()
{
return $this->hasOne('App\Contact');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
public function allergies()
{
return $this->belongsToMany('App\PatientToAllergyAlert');
}
public function medicalAlerts()
{
return $this->belongsToMany('App\PatientToMedicalAlert');
}
}
User.php
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function patient()
{
return $this->belongsTo('App\Patient');
}
}
Contact.php
class Contact extends Model
{
protected $table = 'contacts';
protected $primaryKey = 'contactId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
Guardian.php
class Guardian extends Model
{
protected $table = 'guardians';
protected $primaryKey = 'guardianId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
You have not defined relationships correctly. First of all, fill in table fields into $fillable array in Patient, Contact, Guardian classes (just like in User class).
If you want to use hasOne relationship between Patient and User, you're gonna need user_id field on patients table. You can alternatively use belongsTo relationship.
If you want to use custom column names, just specify them in relationship methods:
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
// alternatively
return $this->belongsTo('App\User', 'user_id', 'id');
}
Just go through documentation without skipping paragraphs and you will get going in a few minutes :)
https://laravel.com/docs/5.1/eloquent-relationships#defining-relationships
Also, this will not work:
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
new Patient() only creates the object, but does not store it in DB, so you will not be able to save relationships. You need to create the object and store it to DB to avoid this problem:
$patient = Patient::create(['patientId' => (string)Uuid::generate()]);
$patient->user()->save($user);
...
// or
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->save();
$patient->user()->save($user);
...
When you're setting up your relationship, you can to specify the name of the primary key in the other model. Look here.
I'm not sure, but I think you relationships are not defined properly.

Categories