Search code examples
phplaravelvoyager

Declaration of App\Models\User::isNot(App\Models\User $user)


i'm getting this error

Declaration of App\Models\User::isNot(App\Models\User $user) should be compatible with Illuminate\Database\Eloquent\Model::isNot($model)

for my code here i'm using voyager package in laravel any idea how can i solve it

<?php

namespace App\Models;

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

class User extends \TCG\Voyager\Models\User
 {


  public function isNot(User $user){
       return $this->id !== $user->id;
   }

Solution

  • By defining a type hint you are changing the method signature compared to the original code you are overwriting.

    See Eloquent/Model:

    /**
     * Determine if two models are not the same.
     *
     * @param  \Illuminate\Database\Eloquent\Model|null  $model
     * @return bool
     */
    public function isNot($model)
    {
        return ! $this->is($model);
    }
    

    In other words you probably want to have something like:

    public function isNot($user) {
        return $this->id !== $user->id;
    }
    

    or possibly:

    public function isNot($user) {
        if (!$user instanceof User) {
            throw new \InvalidArgumentException('Expected an instance of User');
        }
        return $this->id !== $user->id;
    }
    

    This solution is not ideal, but it ensures that you maintain the original method signature.