Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name laravel 5.4 - php

Hi following are my relations
User Model
public function loginlogout()
{
$this->HasMany("App\Models\LoginLogoutLogs");
}
and this is my LoginLogoutLogs Model
public function users()
{
return $this->belongsTo('App\Models\User');
}
I am trying to access name from Users like this
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->users()->name);
}
but i am getting this error
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
EDIT Adding Models
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Session;
use Illuminate\Support\Facades\DB;
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'last_login', 'Address', 'Age', 'DateOfBirth', 'created_by', 'deleted_by'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
static function GetUserNamebyID($id)
{
$name = User::select("name")->where(["id" => $id])->pluck('name');
if (isset($name[0])) {
return $name[0];
} else {
return '';
}
}
public function loginlogout()
{
$this->HasMany("App\Models\LoginLogoutLogs", 'userID');
}
public function company()
{
$this->HasMany("App\Models\Company");
}
}
And now LoginLogouts Model
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Illuminate\Database\Eloquent\Model;
use Session;
use Illuminate\Support\Facades\DB;
class LoginLogoutLogs extends Model
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users_logs';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'userID','is_accpeted','type','addedFrom'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
// change company to hasmany
public function user()
{
return $this->belongsTo('App\Models\User');
}
}

simply change your part of
dd($loginLogoutLog->users()->name);
into
dd($loginLogoutLog->users->name);
remove the bracket on users, its the easy fix.
here we obtain a property, not a function.... (although in the model its defined as function)

Easy fix:
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->users->name);
}
You want to access the relationship entities, as opposed to the relationship model.
By using users(), your code thinks you are trying to call a name() method on the users model, as opposed to your users method on the LoginLogoutLogs class.

You need to change your relationship with user adding the foreign key in LoginLogoutLogs:
public function user()
{
return $this->belongsTo('App\Models\User', 'userID');
}
Also ensure that you call user insted of users
$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->user->name);
}
And if you want to perform use eager loading:
$loginLogoutLogs = LoginLogoutLogs::with('user')->get();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->user->name);
}

Remove () when you are getting the child model and add a second parameter to belongsTo.
Here you are:
Migrations:
// Parent migration (create_clients_table):
Schema::create('clients', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
// Child migration (create_payments_table):
Schema::create('payments', function (Blueprint $table) {
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')
->references('id')
->on('clients')
->onDelete('cascade');
});
Models relationship:
// Child (Client Model)
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
// Parent (User Model)
public function clients()
{
return $this->hasMany(Client::class);
}
Data output:
// Route:
Route::get('/client/{id}/payments', [PaymentController::class, 'paymentsOfClient']);
// In controller (PaymentController):
/**
* Display a listing of the payments of specified Client.
*
* #param string $id
* #return \Illuminate\Http\Response
*/
public function paymentsOfClient($id)
{
$client = Client::find($id);
// check permissions
if (auth()->user()->id !== $client->owner->id) {
return;
}
$payments = $client->payments()->paginate(20);
return response()->json($payments);
}

Related

In which model to put a function that returns all active / inactive venues of the user?

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;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function venues()
{
return $this->hasMany(Venue::class);
}
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Venue Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Venue extends Model
{
use HasFactory;
protected $fillable = ['user_id', 'city_id', 'category_id', 'title', 'address', 'phone', 'email', 'website', 'facebook', 'instagram', 'content_bg', 'content_en', 'cover_image', 'lat', 'lng'];
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function category()
{
return $this->belongsTo(Category::class, 'category_id');
}
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
public function features()
{
return $this->belongsToMany(Feature::class, 'venue_feature');
}
public function images()
{
return $this->hasMany(VenueImage::class);
}
public function reviews()
{
return $this->hasMany(Review::class);
}
}
Everything is fine, but now I want to have two methods where to call active / inactive venues of the user and I'm not sure where to place them in User Model or in Venue Model, generally which is better?
If I put them in Venue model (getUserActiveVenues and getUserInactiveVenues) and pass authenticated user to these methods, or to put them in User model (getActiveVenues and getInactiveVenues).
add relations to the user model
public function venues()
{
return $this->hasMany(Venue::class);
}
public function activeVenues()
{
return $this->hasMany(Venue::class)->where('active',true);
}
public function inActiveVenues()
{
return $this->hasMany(Venue::class)->where('active',false);
}
then you can eager load the relevant type of venue. I had to guess at what you mean be 'active'

ErrorException Trying to get property 'User' of non-object ( laravel )

I am getting the error:
ErrorException Trying to get property 'User' of non-object
from the statements below which don't seem to work:
$user = Mobile::find(3)->User;
dd($user);
rest of the code is as follows:
usercontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Mobile;
use Hash;
class UserController extends Controller
{
public function addUserMobile()
{
$user = new User;
$user->name = "Test Name";
$user->email = "test#mnp.com";
$user->password = Hash::make("12345678");
$user->save();
$mobile = new Mobile;
$mobile->mobile = '123456789';
$user->mobile()->save($mobile);
}
public function index()
{
// get user and mobile data from User model
$user = User::find(3);
// var_dump($user->name);
// var_dump($user->mobile->mobile);
// // get user data from Mobile model
$user = Mobile::find(3)->User;
dd($user);
// // get mobile number from User model
// $mobile = User::find(3)->mobile;
// dd($mobile);
}
}
mobile.php
<?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',
'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',
];
public function mobile()
{
return $this->hasOne(Mobile::class);
// note: we can also inlcude Mobile model like: 'App\Mobile'
}
}
mobile table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateMobilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('mobiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('mobile');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('mobiles');
}
}
mobile database
user database
"3" is user_id btw.
The problem is you are querying the Mobile with id 3 (which does not exist) and then calling the user relation.
$user = Mobile::find(3)->user;
Since Mobile::find with an id that doesn't exist returns null, you are calling ->user on null, and you will get the error you mentioned.
Also, you should add a belongsTo relation in your Mobile model:
public function user()
{
return $this->belongsTo(User::class);
}
Now, after fixing your query to use user_id, you can do:
$user = Mobile::where('user_id', 3)->first()->user;

How can i get data using Eloquent Relationships in laravel

I need to get data from the teaching_subjects table to my Vue file according to teacher table data. I have created the relationship with the TeachingSubject model and Teacher model.
This is my Teacher Model,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Teacher extends Model
{
protected $table = 'teacher';
protected $fillable = [
'firstName',
'lastName',
'teacherUserName',
'contactNo',
'teacherEmail',
'gender',
'teaching_expirence',
'Qualifications',
'description',
'speakEnglish',
'speakJapan',
'password',
'status',
];
public function approvalStatus(){
return $this->belongsTo(ApprovalStatus::class);
}
public function teachingSubject(){
return $this->hasMany(Teacher::class);
}
}
And this is my TeachingSubject Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TeachingSubject extends Model
{
protected $table = 'teaching_subjects';
protected $fillable = [
'teacher_id',
'subject_id',
'lesson_fee'
];
public function teacher(){
return $this->hasMany(Teacher::class);
}
public function subject(){
return hasMany(Subject::class);
}
}
This is my Subject model,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subject extends Model
{
protected $table = 'subject';
protected $fillable = [
'subject',
'grade_id',
'no_of_teachers',
'status'
];
public function teachingSubject(){
return belongsTo(TeachingSubject::class);
}
}
This is my Teching_subjects migration file
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTeachingSubjectsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('teaching_subjects', function (Blueprint $table) {
$table->integer('id')->unsigned()->autoIncrement();
$table->integer('teacher_id')->unsigned();
$table->integer("subject_id")->unsigned();
$table->float("lesson_fee")->nullable();
$table->timestamps();
$table->foreign('teacher_id')
->references('id')->on('teacher');
$table->foreign('subject_id')
->references('id')->on('subject');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('teaching_subjects');
}
}
I need to get the date(created_at), teacher_name, lesson and lesson_fee using TeachingSubjectController.
for example if You want to get user that made the comment, so get that user from the comment object.
Try this
$user = User::find(1);
$posts = $user->posts;
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
echo $comment->commentcontent;
echo $comment->users;
}
}

laravel belongsTo on User Model not working

Following are my relations in laravel , I am unable to access company using User's Object, but i am getting null when i try to access it, please see my code below to get the picture
following are my models
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use Session;
use Illuminate\Support\Facades\DB;
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
protected $table = 'tbl_users';
protected $primaryKey = 'id';
protected $guarded = ['id'];
const API = 'api';
const WEB = 'web';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'last_login', 'Address', 'Age', 'DateOfBirth', 'created_by', 'deleted_by'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'is_admin' => 'boolean',
];
public function isAdmin()
{
return $this->is_admin;
}
static function GetUserNamebyID($id)
{
$name = User::select("name")->where(["id" => $id])->pluck('name');
if (isset($name[0])) {
return $name[0];
} else {
return '';
}
}
public function loginlogout()
{
$this->hasMany("App\Models\LoginLogoutLogs", 'userID');
}
public function company()
{
$this->hasMany("App\Models\Company", "company_id");
}
}
And following is my companies Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
use App\Models\CarePlanData;
use Session;
class Company extends Model
{
protected $table = 'companies';
protected $primaryKey = 'id';
protected $guarded = ['id'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'phone_no', 'address', 'password', 'description', 'city', 'company_logo', 'country', 'email'
];
static public function fetchAllActiveCompanies()
{
return DB::table("companies")->where(['is_active' => 1])->pluck('name', 'id');
}
// change company to hasmany
public function users()
{
return $this->hasmany('App\Models\User');
}
}
and this is how i am trying to access the Company , but i am getting null.
public function fetchCompany(){
$User = User::find($user->id);
dd($User->company());
}
First of all if a user belongs to 1 company then it should be:
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
then fetchCompany() should be
public function fetchCompany(){
$User = User::with('company')->find($user->id);
dd($User->company);
}
You need to use with to load the relations. You pass the name of the function which defines the relation in your User model to with like this with('function_name').
Your actual question is:
You have belongTo Relation between User and Company but when you trying to access the Company via user object, you get null
In your User.php Model put the following function but if you already have then leave it:
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
Then
Replace this function:
public function fetchCompany(){
$User = User::find($user->id);
dd($User->company());
}
To is one:
public function fetchCompany(){
$User = User::find($user->id);
if($User){
dd($User->company()->get());
}
}
or to this one:
public function fetchCompany(){
$User = User::find($user->id);
if($User){
dd($User->company);
}
}
actually if your company_id field is on user model, then your relation should be
public function company()
{
$this->belongsTo("App\Models\Company", "company_id");
}
unless a user can have many companies ?

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