Неопределенное свойство: Illuminate \ Database \ Eloquent \ Relations \ BelongsTo :: $ name laravel 5.4

Привет, следующие мои отношения

Модель пользователя

   public function loginlogout()
{
$this->HasMany("App\Models\LoginLogoutLogs");
}

а это мой LoginLogoutLogs Модель

  public function users()
{
return $this->belongsTo('App\Models\User');
}

Я пытаюсь получить доступ к имени от таких пользователей

 $loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->users()->name);
}

но я получаю эту ошибку

Неопределенное свойство: Illuminate \ Database \ Eloquent \ Relations \ BelongsTo :: $ name

РЕДАКТИРОВАТЬ Добавление моделей

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

А теперь модель LoginLogouts

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

}

1

Решение

Легко исправить:

$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->users->name);
}

Вы хотите получить доступ к объектам отношений, в отличие от модели отношений.

Используя users(), ваш код думает, что вы пытаетесь вызвать name() метод на users модель, в отличие от вашего users метод на LoginLogoutLogs учебный класс.

3

Другие решения

Вы должны изменить свои отношения с пользователем, добавив внешний ключ в LoginLogoutLogs:

public function user()
{
return $this->belongsTo('App\Models\User', 'userID');
}

Также убедитесь, что вы называете пользователя insted пользователей

$loginLogoutLogs = LoginLogoutLogs::all();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->user->name);
}

И если вы хотите выполнить загрузку:

$loginLogoutLogs = LoginLogoutLogs::with('user')->get();
foreach($loginLogoutLogs as $loginLogoutLog){
dd($loginLogoutLog->user->name);
}
1

просто измени свою часть

dd($loginLogoutLog->users()->name);

в

dd($loginLogoutLog->users->name);

снять скобку на пользователях, это легко исправить.
здесь мы получаем свойство, а не функцию …. (хотя в модели это определяется как функция)

1