laravel model relationships hasOne - php

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

Related

how can i handle this error : Undefined offset: 0

I'm producing an online school platform and in part of it student can see it's classes with their informations..but the related function return this error : Undefined offset: 0 (View: C:\xampp\htdocs\OnlineSchool\resources\views\admin\student\ClassReport.blade.php)
there are some relations between models
My Models:
USER(students and teachers) ، LEVEL(level of classes) ، Classroom.
=> there is a many to many relation between student and classroom (pivot table)
please save me from this stupid error
user:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','image','level','code_meli',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function classroom(){
return $this->hasMany (classroom::class);
}
public function ClassRoomStudent(){
return $this->belongsToMany (classroom::class ,'classroom_user','user_id','classroom_id');
}
}
classroom:
class classroom extends Model
{
protected $fillable = [
'title', 'teacher_id', 'level_id','day','time','price',
];
public function Student(){
return $this->belongsToMany (user::class ,'classroom_user','classroom_id','user_id');
}
public function level(){
return $this->belongsTo (level::class );
}
public function teacher(){
return $this->belongsTo (user::class );
}
}
level :
class level extends Model
{
protected $fillable = [
'title',
];
public function classroom(){
return $this->hasMany (classroom::class);
}
public function exam(){
return $this->hasMany (exam::class);
}
}
and my function in controller:
public function MyClasses(){
$student_id=auth ()->user ()->id;
$classrooms=classroom::with ('level','teacher','factor')->wherehas('student',function ($q) use($student_id){
$q->where('id',$student_id);
})->get();
return view ('admin.student.ClassReport',compact ('classrooms','student_id'));
}
at the end .. my blade:
#foreach($classrooms as $class)
<tr>
<td>{{$i++}}</td>
<td>{{$class->title}}</td>
<td>{{$class->teacher[0]->name}}</td>
.
.
.
.
</tr>
#endforeach
The Classroom belongs to only one teacher, no need to use de zero index, just type $class->teacher->name

Laravel - makeVisible doesn't make hidden attribute visible

I have the following code:
$model = new coretable;
log::info($model->all());
$model = $model->makeVisible('id_coretable');
log::info($model->all());
In my lumen log, I get the following result:
[2020-02-26 10:14:19] local.INFO: [{"Internal_key":"TESTKEY_1"},{"Internal_key":"TESTKEY_2"},{"Internal_key":"TESTKEY_3"},{"Internal_key":"TESTKEY_4"},{"Internal_key":"TESTKEY_5"}]
[2020-02-26 10:14:19] local.INFO: [{"Internal_key":"TESTKEY_1"},{"Internal_key":"TESTKEY_2"},{"Internal_key":"TESTKEY_3"},{"Internal_key":"TESTKEY_4"},{"Internal_key":"TESTKEY_5"}]
I would expect the "id_coretable" attribute to be present in the second output from log::info(), but it isnt.
Why is that?
Here is the model of coretable:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CoreTable extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'coretable';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'Internal_key'
];
protected $hidden = [
'id_coretable',
'created_at',
'updated_at'
];
protected $primaryKey = 'id_coretable';
/**
* Many-To-Many relationship with User-Model.
*/
public function extensiontable_itc()
{
return $this->hasOne('App\extensiontable_itc', 'coretable_id');
}
public function extensiontable_sysops()
{
return $this->hasOne('App\extensiontable_sysops', 'coretable_id');
}
public function inaccessibletable()
{
return $this->hasOne('App\inaccessibletable', 'coretable_id');
}
}
I have no clue why makeVisible() doesnt have any effect on the effect.
The initial model you created does not have any influence on the models received from the all() function. This is a collection of new models with the initial $hidden array.
To change what values are shown, you will have to call makeVisible on the collection you receive:
$model = new coretable;
log::info($model->all());
log::info($model->all()->makeVisible('id_coretable'));
It is also recommended to call the query functions staticaly, this way you don't need to create an initial model:
log::info(coretable::all()->makeVisible('id_coretable'));

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.

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.

How to retrive userID from users table?

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"];

Categories