Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fahaddsheikh's avatar

Laravel says an existing method does not exist.

I have a class named Course and a method on that course by the name addCourse. I've also set guarded to []. Here is the class

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

    /**
     * Add a course
     *
     * @return void
     * @author 
     **/

    public function addCourse($course)
    {
        $this->create($course);
    }

}

On the store method I am calling the following

    public function store(Request $request)
    {
        $request->addCourse([
            'user_id'       => request('user_id'),
            'title'         => request('title'),
            'body'          => request('body'),
            'country'       => request('country'),
            'city'          => request('city'),
            'address'       => request('address')
            ]);
        return back();
    }

But the following test

    /**
     * A user may create courses
     *
     * @return void
     * @author 
     **/
    function test_an_authenticated_user_may_create_courses()
    {
        $this->mockUser();

        $course   = factory('App\Course')->make();

        $this->post('/courses', $course->toArray());
        
        $this->assertCount(1, $this->course);
        
    }

returns the following

BadMethodCallException: Method addCourse does not exist.

0 likes
3 replies
Agelios's avatar
Agelios
Best Answer
Level 4

Because your $request doesnt have addCource. If you want to use this method you need to create model. $newModel=new Course(); and then use $newModel->addCourse();

1 like
spekkionu's avatar

As a second note the create method on Eloquent models is static and you are calling it using $this->create(). You need to call static methods statically like static::create(), self::create(), or Course::create().

I'm assuming you have more in your addCourse method also as if you don't you may as just call Course::create() directly in your controller rather than create a useless method.

fahaddsheikh's avatar

Thankyou very much this worked for me.

    public function store(Course $course, Request $request)
    {

        $course->addCourse([
            'user_id'       => request('user_id'),
            'title'         => request('title'),
            'body'          => request('body'),
            'country'       => request('country'),
            'city'          => request('city'),
            'address'       => request('address')
            ]);
        return back();
    }

Please or to participate in this conversation.