phplaravelundefined-functiontinker

PHP Fatal error: Call to undefined function Laravel tinker


I'm trying to establish a relation between two tables (Roles and Abilities) but when I run the function allowTo() it says is undefined. I tried to clear the cache and config but didn't do anything. If anyone could help that'd be great, thanks!

Model :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    
protected $guarded = [];

    public function abilities(){
        return $this->belongsToMany(Ability::class)->withTimestamps();
    }

   public function allowTo($ability){

        $this->abilities()->save($ability);
   }

Tinker Environment on shell :

>>> $user = App\User::find(7);

=> App\User {#3044
     id: 7,
     name: "Rebeca Tejedor",
     email: "rebtej@gmal.com",
     email_verified_at: null,
     created_at: "2020-08-13 10:29:46",
     updated_at: "2020-08-13 10:29:46",
   }
>>> $role = Role::firstOrCreate(['name'=> 'lender']);

[!] Aliasing 'Role' to 'App\Role' for this Tinker session.
=> App\Role {#3041
     id: 1,
     name: "lender",
     created_at: "2020-08-13 10:41:15",
     updated_at: "2020-08-13 10:41:15",
   }
>>> $ability = Ability::firstOrCreate(['name'=> 'edit_items']);

[!] Aliasing 'Ability' to 'App\Ability' for this Tinker session.
=> App\Ability {#3040
     id: 1,
     name: "edit_items",
     created_at: "2020-08-13 10:43:34",
     updated_at: "2020-08-13 10:43:34",
   }

>>> $role = allowTo($ability)

Error:

PHP Fatal error: Call to undefined function allowTo() in Psy Shell code on line 1

The model

Tinker enviroment


Solution

  • you are using your relation in this way:

    $role = allowTo($ability);
    

    while you should use it like:

    $role->allowTo($ability);
    

    and in your method:

    public function allowTo($ability) {
        $this->abilities()->attach($ability->id);
    }