laravel belongsTo on User Model not working - php

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 ?

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'

How in Laravel 7 resources show only some fields of a creator?

In my Laravel 7.6 app I use resource collection with creator retrieved
and I want in some cases show not all creator fields, but only some of them. I have in my control:
$activeVotes = Vote
::getByStatus('A')
->where('votes.id', 1)
->with('voteCategory')
->with('creator')
return (new VoteCollection($activeVotes));
In app/Http/Resources/VoteCollection.php I have :
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class VoteCollection extends ResourceCollection
{
public static $wrap = 'votes';
public function toArray($request)
{
$this->collection->transform(function ($votes) {
return new VoteResource($votes);
});
return parent::toArray($request);
}
}
and in app/Http/Resources/VoteResource.php :
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class VoteResource extends JsonResource
{
public static $wrap = 'votes';
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'creator' => $this->whenLoaded('creator'),
...
How to defined if I need to show only some fields of creator above ?
EDITED:
My app/User.php has :
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use DB;
...
class User extends Authenticatable implements MustVerifyEmail
{
use Billable;
use HasApiTokens, Notifiable;
use funcsTrait;
protected $table = 'users';
protected $primaryKey = 'id';
public $timestamps = false;
protected $userAvatarPropsArray = [];
protected $avatar_filename_max_length = 255;
protected $full_photo_filename_max_length = 255;
protected static $password_length = 8;
protected $fillable = [ 'username', 'email', 'status', 'provider_name', 'template_id', 'provider_id', 'first_name', 'last_name', 'phone', 'website', 'password',
'activated_at', 'avatar', 'full_photo', 'updated_at', 'verified' ];
protected $hidden = [ 'password', 'remember_token' ];
...
public function votes()
{
return $this->hasMany('App\Vote', 'creator_id', 'id');
}
...
and app/Vote.php :
<?php
namespace App;
use DB;
use App\MyAppModel;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use App\Http\Traits\funcsTrait;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Validation\Rule;
class Vote extends MyAppModel
{
use funcsTrait;
use Sluggable;
use HasTags;
protected $table = 'votes';
protected $primaryKey = 'id';
public $timestamps = false;
protected $casts = [
'meta_keywords' => 'array'
];
protected $fillable = ['name', 'slug', 'description', 'creator_id', 'vote_category_id', 'is_quiz', 'status', 'image'];
protected static $logAttributes = ['*'];
...
public function creator(){
return $this->belongsTo('App\User', 'creator_id','id');
}
In Vote and user models there are referenced to other model.
Otherwize
->with('creator')
does not work.
Are there some options I missed?
Thanks!
I think you have two options.
Use hidden on your user model
By using hidden, see the Laravel docs, you specify which fields are shown in the JSON or Arrray representation of your model.
Select the fields in your with statement
$activeVotes = Vote::getByStatus('A')->where('votes.id', 1)
->with('voteCategory')
->with(['creator' => function ($query) {
$query->select('id', 'first_name');
}]);
return (new VoteCollection($activeVotes));
Your need to include the field id, as this is responsible to join these two.

laravel belongsTo not working with one to one relation

i have two tables:
**plans:**
planId, plan_name
**Users:**
userId, user_name, password, planId
i tried to get the name of the plan where i select all users.
this is the users model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Users extends Authenticatable {
public $timestamps = false;
protected $table = 'users';
protected $primaryKey = 'userId';
protected $fillable = [
'user_name',
'password',
];
protected $hidden = [
'_token',
];
public function plan()
{
return $this->belongsTo('App\Plans', 'planId');
}
public function validateCredentials( MyUserInterface $user, array $credentials ) {
$plain = $credentials["password"] . $user->getAuthPasswordSalt();
return $this->hasher->check( $plain, $user->getAuthPassword() );
}
}
and this is the plan model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Plans extends Model {
public $timestamps = false;
protected $table = 'plans';
protected $primaryKey = 'planId';
protected $fillable = [
'plan_name'
];
protected $hidden = [
'_token',
];
public function users()
{
return $this->hasMany('App\Users', 'planId');
}
}
when i used:
\App\Users::get();
there is no relations in the output... there is only the users.
what can i do?
i tried to used hasOne and the same issue...
tnx a lot
You can eager load the relationships like this:
\App\Users::with('plan')->get();
Or add a $with property to always eager load it when you fetch an user:
class Users extends Authenticatable
{
protected $with = [
'plan'
];
}
If you don't want to eager load it, you can access the plan of each user's instance like this:
$users = \App\Users::get();
foreach ($users as $user) {
dd($user->plan);
}

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

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);
}

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