Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 744
noobie-php Avatar asked Oct 30 '17 08:10

noobie-php


4 Answers

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)

like image 100
Toni Tegar Sahidi Avatar answered Nov 06 '22 16:11

Toni Tegar Sahidi


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

like image 21
Oybek Odilov Avatar answered Nov 06 '22 18:11

Oybek Odilov


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.

like image 5
James Avatar answered Nov 06 '22 18:11

James


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);
}
like image 4
Nerea Avatar answered Nov 06 '22 18:11

Nerea