Как использовать eloquent для команды auth user в laravel - PullRequest
0 голосов
/ 31 октября 2019

Прямо сейчас я сталкиваюсь со странной ошибкой

В моем контроллере, когда я импортирую пользователя класса, как этот

, используйте Illuminate \ Foundation \ Auth \ User;

Это работает, когда я использую eloquent, как

public function index()

    {

        $farms = User::where('role_id', 3)->get();
        $user = Auth::user();
        $animal = Animal::all();
        return view('clinic.index', compact('user', 'animal', 'farms'));
    }

, но отказывается работать, когда дело доходит до табличных отношений, таких как

public function show($id)
    {
        $farms = User::with(['animals'])->findOrFail($id);
        return view('clinic.show',compact('farms'));
    }

, показывая мне эту ошибку

"Call to undefined relationship [animals] on model [Illuminate\Foundation\Auth\User]"

Новсякий раз, когда я импортирую пользовательский класс как App \ User в моем контроллере,

Он работает в отношениях, но отказывается работать с красноречивым сообщением об этой ошибке

"Call to a member function get() on null"

Теперь я немного запутался. Приветствуется любая помощь

Приложение \ Пользователь

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    public static function where(string $string, int $int)
    {
    }

    public static function select(array $array)
    {
    }

    public function role(){
        return $this->belongsTo(Role::class);
    }
    public function animals(){
        return $this->hasMany(Animal::class);
    }

    public function clinics(){
        return $this->hasMany(Clinic::class);
    }

    public function slaughter(){
        return $this->hasMany(Slaughter::class);
    }

    public function address(){
        return $this->belongsTo(Address::class);
    }
    /**
     * 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',
    ];
}

1 Ответ

1 голос
/ 31 октября 2019

Класс Illuminate\Foundation\Auth\User является родителем класса App\User и отношения animals, заданного в классе App\User. Таким образом, вы не можете вызвать animals отношение из Illuminate\Foundation\Auth\User класса.

Вы должны удалить эти функции из App\User Модель:

public static function where(string $string, int $int)
{
}

public static function select(array $array)
{
}
...