How to retrive userID from users table? - php

I have a two table named users and profile . In profile table there is a column named userID.Now i want to this userID column takes value from users table's id.I have done database relationships part.But can not retrieve data with view.I have searched but i have not found any satisfying answer according my issue.
By the way i am new in Laravel.I have tried so far
User Model:
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table ="users";
protected $fillable = [
'userName', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function userProfile(){
return $this->hasOne('App\Profile');
}
}
Profile Model:
class Profile extends Model
{
//
protected $table = "profiles";
public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic"];
public function user(){
return $this->belongsTo('App\User');
}
}
And i am trying to retrieve userID with {{$profile->userID}}.I really don't know where is the problem and how to do this?

you will need to tell laravel to get the relationship model like this
$profile = Profile::find(1);
$userID = $profile->user->id;
edit:
from the docs
model is automatically assumed to have a user_id foreign key.
which in your case is userId so change your hasOne and belongsTo methods to tell laravel the name of foreign_key you are using
public function profile()
{
return $this->hasOne('App\Profile', 'userId');
}
public function user()
{
return $this->belongsTo('App\User', 'userId');
}

Please add userID to the fillable array of profiles.
Please check below sample code to do the same.
public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic","userID"];

Related

laravel model relationships hasOne

I have two table, the first is accounts (User model) which is used for auth and the other is students (t_student model) which contains the students details such student id (S_ID)
I am trying to get the S_ID inside the controller in store function for the logged in user.
$application = new Application;
$application->A_ID= $request-> input('A_ID');
$application->S_ID= Auth()->User()->students()->S_ID;
$application->S_Justification= $request-> input('Justification');
$application->save();
return redirect('/Abstracts')->with ('success', 'application submitted' );
MY User model (accounts table)
class User extends Authenticatable{
protected $table = 'accounts';
protected $primaryKey = 'Account_ID';
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'password', 'Account_Type', 'name'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function abstracts(){
return $this ->hasMany('App\Project' , 'PI_ID');
}
public function academics(){
return $this ->hasOne('App\T_user', 'Account_ID');
}
public function students(){
return $this ->hasOne('App\t_student', 'Account_ID');
}}
my t_student model
class t_student extends Model{
protected $table = 't_student';
protected $primaryKey = 'S_ID';
public function account(){
return $this ->belongsTo('App\User', 'Account_ID');}
and I am getting this error
Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$S_ID
EDIT: The error I am getting is related to my controller
$application->S_ID= Auth()->User()->students()->S_ID;
and the reason is my relationship but I am not sure what is wrong about it
You should modify it:
$application->S_ID= Auth()->User()->students->S_ID;
In User model u must added the foregnkey to second parameter in hasOne func
so replace the Account_ID by S_ID
for ex :
// in user model
public function students()
{
return $this ->hasOne('App\t_student', 'S_ID');
}
// in ur controller romove the parentheses of students propriety

I can not add methods to User Model in Laravel 5.4 ..!

I'm using Laravel 5.4. I have the methods I created in the User model. When I want to create an object from the User model and invoke my own methods, I can not get to the methods I added.
The User Model is derived from the Authenticable class at 5.4, which was derived earlier from the Model class. I think the problem is about it. What I really want to do is to set up the belong_to, has_many structure to relate the user model to the other models.
But with the User model I do not do that. What do you recommend ?
class User extends Authenticatable
{
use Notifiable;
/**
* 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 getMakale()
{
return $this->hasMany(Makale::class, 'user_id', 'id');
}
}
$author = User::first();
return method_exists($author,'getMakale');
//eventually turns false
I believe you are potentially setting an accessor rather than a relationship. In this case I would think you want to name that function something like:
public function haberler()
{
return $this->hasMany(Makale::class, 'user_id', 'id');
}
or public function makales(). Prefixing your function name with get or set will have unintended consequences in Laravel.

Default User model and Relatinship - Laravel 5.4

I use the default User model and I have created a UserStatus model:
User
class User extends Authenticatable
{
use Notifiable;
/**
* 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 status()
{
return $this->belongsTo('App\UserStatus');
}
}
UserStatus
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserStatus extends Model
{
public $timestamps = false;
public function users()
{
return $this->hasMany('App\User');
}
}
I cant access to the related model attribute because the $user->status is NULL:
$users = User::all();
foreach ($users as $user) {
var_dump($user->status->name);
}
What is the best practice/solution?
Thanks!
Your query will cause you the N+1 query problem.
Try this which is efficient
$users = User::with('status')->get();
foreach ($users as $user) {
logger($user->status->name);
}
There are two ways to approach:
Simply add a defense condition:
$users = User::all();
foreach ($users as $user) {
if(!empty($user->status))
var_dump($user->status->name);
}
You define a nullable column as user_status_id in your users table and make it foreign key for id in user_status table and create relationship in your User model : hasOne and give the foreign key and then only take users out which are having some status otherwise dont:
$users = User::whereNotNull('user_status_id')->get();

laravel eloquent belongsTo fetches wrong data

I have two tables. One contains the user and the other contains meetings.
Each meeting belongsTo exact one User.
Meetings
class Meeting extends Model {
protected $table = 'meetings';
protected $primaryKey = 'owner_id';
/**
* A meeting belongs to exact one User
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user(){
return $this->belongsTo(User::class, 'id');
}}
User
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
protected $primaryKey = 'id';
/**
* One User can have many Meetings
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function meetings(){
return $this->hasMany(Meeting::class, 'owner_id');
}
I fetch the data with
$meetings = Meeting::with('user')->get();
But somehow i don't get the related user. It just iterates over all users in the database and breaks if no more user is given.
What the heck am I doing wrong? O.o
Let try to change it:
public function user(){
return $this->belongsTo(User::class, 'id');
}
To
public function user(){
return $this->belongsTo(User::class, 'owner_id', 'id');
}
Looking at your Meeting model there are 2 strange things:
protected $primaryKey = 'owner_id';
Why is that? Shouldn't it be id here?
Second thing:
public function user(){
return $this->belongsTo(User::class, 'id');
}
probably here instead of id you should user owner_id.
So to sum up it seems you set wrong keys for primary key and for relationships and probably that's the reason relationship doesn't work as it should.

How to access other related model data in Laravel?

I am creating a user profile page and I want to retrieve the data from my User model and UserProfile model. But I have a problem in getting the result. Here's what I did:
User model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'username',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/*
public function isAdmin() {
return $this->admin;
}
*/
public function profile() {
return $this->hasOne('App\UserProfile');
}
}
UserProfile model
class UserProfile extends Model
{
protected $table = 'user_profile';
protected $fillable = [
'phone',
'address'
];
public function user() {
return $this->belongsTo('App\User');
}
}
Then I access the relation in my ProfileController
public function getProfile($username) {
$user = User::with('user_profile')->where('username', $username)->get();
dd($user);
}
And I got this error:
Call to undefined relationship [user_profile] on model [App\User].
The user_profile is my table name
Use proper relationship name:
$user = User::with('profile')->where('username', $username)->first();
Also, in this case you should use the first() method to get an user object.

Categories