Laravel one to many relationship fetch data - laravel

i make a one to many relationship in my project but when i want to fetch data it returns null response.
i have a user Model and Intership Model.
each user has one Intership and each Intership has many users. so , relationship is one to many .
i create this relation but i cant fetch data. i want to show intership information of a user.
MY USER MODEL :
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'last_name',
'email',
'role',
'phone',
'user_code',
'born_date',
'national_code',
'password',
];
protected $primaryKey = 'user_code';
protected $table = 'users';
/**
* 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 intership()
{
return $this->belongsTo(Intership::class,'intership_code','intership_code');
}
}
MY INTERSHIP MODEL :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Intership extends Model
{
use HasFactory;
protected $table = 'interships';
protected $primaryKey = 'intership_code';
protected $fillable = [
'teacher_code',
'user_code',
'school_code',
'work_code',
'intership_term_code',
'intership_code',
'class_code',
'start',
'end',
];
public function users()
{
$this->hasMany(User::class,'user_code','user_code');
}
}
MY CONTROLLER :
public function index()
{
$user = User::where('user_code',32132)->first();
$interships = $user->intership;
return $interships;
}
Notes :
1- i dont have "id" field in my tables so instead of "id" i have user_code for users and intership_code for interships that are foreignkey
2- user with user_code => 32132 already exists.
3- i want to show a user intership information

Ok so first things first, since you use your User model the relationship that you want to build is in the User model, the one in Internship model is irrelevant (at least for this question).
public function intership()
{
return $this->belongsTo(Intership::class,'user_code','user_code');
}
Your foreign key in your Internships table that connects it with the Users table is the user_code which links to the user_code of the user in Users table.

Related

Attempt to read property "name" on null (View: C:\xampp\htdocs\Moja_OTT\resources\views\premium\profile.blade.php)

I want a simple program that shows the user profile after login. I used session and middleware. But it is saying that the name property is null. Please help me solve this error. I have used User model. The value of the properties are not retrieving from the database.
Blade code:
<h1>Profile</h1>
<h2>Welcome Mr/Ms {{$user->name}}</h2>
Logout
Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\PremiumModel;
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $timestamp = false;
protected $fillable = [
'name',
'email',
'password',
'type',
'email_verified_at',
'pro_pic',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
function admin()
{
return $this->hasOne('App\Models\admin', 'user_id', 'admin_id');
}
function premium()
{
return $this->hasMany(PremiumModel::class, 'user_id', 'user_id');
}
}
Controller code:
function profile()
{
$user = User::where('user_id',session()->get('logged'))->first();
return view('premium.profile')->with('user',$user);
}
Here, logged is the middleware.
You can try hasOne in the User model:
public function premium()
{
return $this->hasOne(PremiumModel::class, 'user_id', 'user_id');
}
Because hasMany returned an array, but hasOne returned just a single Object

Getting the value of another table and summing it up

I have a table user and table payment which are connected to eachother using one to many relationship,
In my user's table, i have a column name client_type which values are {residential, commercial, medical and industrial), if any of this clientType make payment, his user_id is stored in payment along with the amount paid..Now, i want to sum all the amount paid by any of this clientType from my payment_table .
These are my codes below
Users Model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'address',
'phone',
'email',
'lga',
'ogwema_ref',
'password',
'role',
'client_type'
];
/**
* 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 payments()
{
return $this->hasMany(Payment::class);
}
}
// Payment Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Payment extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'amount',
'bank_charges',
'ref',
'paystack_ref',
'status',
];
public function user()
{
return $this->belongsTo(User::class);
}
}
This is the code am trying to solve it
Route::get('/chart', function () {
$residential = DB::select('select id from users where client_type = ?', ['residential']);
return $residential->payments;
});
my output
ErrorException
Trying to get property 'payments' of non-object
How can i solve this, thanks in advance,
This select command $residential = DB::select('select id from users where client_type = ?', ['residential']); returns array of results (not object) so that this line $residential->payments throws ErrorException.
The logic of select command should be like this:
$totalMoney = DB::select('select sum(amount) from users INNER JOIN payments ON users.id=payments.user_id where users.client_type = ?', ['residential']);
you get this error because you write a native query so it hasn't accessed to eloquent model so to fix that you could write it by eloquent query
$residential = User::where('client_type', 'residential')->with('payments')->get();
and if you want to get the total payment for each user you could just add withSum method
$residential = User::where('client_type', 'residential')->withSum('payments', 'amount')->get();

Why I'm getting a null value when querying a model in eloquent?

I have a problem where I'm getting a null value when querying a model in eloquent, I have a two models User.php and Project.php, When I use tinker and use User.php to check if the data has a relation to Project.php model I got what I want, but when I use the Project.php to check if it has a relation to User.php I'm getting a null value.
This is my code for Project.php :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public $table = "project";
protected $guarded = [];
public function owner(){
return $this->belongsTo(User::class);
}
}
And this is my code for User.php:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
public function projects(){
return $this->hasMany(Project::class);
}
/**
* 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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
This is my result in Tinker:
This is the result when I use tinker and query, as you can see my User.php has a relation to Project.php, But when I use Project.php I'm getting null value.
Have you tried with:
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
Because (quote from the docs):
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the primary key column.
You should use eager loading to load parent relationship like this :
Project::with('owner')->first()->owner
And confirm that the foreign keys is correct

Returning null Value for User from Model

I'm getting a null value for the user at http://localhost:8000/messages. I am trying to get the user table values within the Message model. It also gives a null value in the console.
Route
Route::get('/messages', function () {
return App\Message::with('user')-> get();
})-> middleware('auth');
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
User Model code:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
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 messages()
{
return $this-> hasMany(Message::class);
}
}
Snapshot
messages table must have user_id with proper user ID to make belongsTo relationship work.
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse

How do I read database data from default User class in Laravel?

When I use the following code in my routes/web.php file, I keep getting the error of 'Trying to get property of non-object' each time I visit the /user/{id}/post url.
routes/web.php
use App\Post;
use App\User;
Route::get('/user/{id}/post', function($id) {
return User::find($id)->name;
});
App/User.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
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 posts() {
return $this->hasOne('Post');
}
}
App/Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
// protected $table = 'posts';
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [''];
}
How do I view data stored in the table users? I put some dummy data in there to try and retrieve it.
If user hasOne relation with Post,it is better to make relation post() rather than posts() and post belongsTo user.
User Model:
public function post() {
return $this->hasOne('App\Post');
}
Post Model:
public function user()
{
return $this->belongsTo('App\User');
}
then, this gives all user's post along with user name.
$users=User::with('post')->get();
foreach($users as $user)
{
print_r($user->name);
print_r($user->post);
}

Resources