Call to undefined function in Laravel 8

I’m working with Laravel 8 to develop my project, and in this project, I have created a store() method for inserting some items into the database.

public function store(Request $request)
{
    // validate
    $this->validate($request, [
        'subject' => 'required|min:5',
        'thread' => 'required|min:10',
    ]);

    // store
    $thread = create($request->all());

    // redirect
    return back()->withMessage('Thread Created!');
}

But now the problem is, whenever I try it, I get this message:

Error Call to undefined function AppHttpControllerscreate()

What is going wrong here, and how can I fix this issue?

Answer

This is more of a syntax error – not so much Laravel. You need to define the Model class and call the method create while referencing your class.

The solution would be to call your Model class and then call the appropriate method.

$thread = Thread::create($request->all());

This is because there is a create() method for Laravel’s models. If you do not reference the Model, PHP cannot find the proper method you are looking for.

In PHP when you call a function from within a class’ method, it will look for a global or a locally defined function or throw an error as you have above. To call a method within the same class you need to use the $this reference.

For example:

class Foo {
  function bar() {
    $this->foobar();
  }

  function foobar() {
    //
  }
}

Now in your case you are in your controller ThreadsController[??] class, and you are calling a method from, I assume, your Thread model class. To call a method from another class object you must define the class (if non-static) and then you can call it:

class foo {
  function bar() {
    $bar = new bar();
    $bar->foo();
  }
}

class bar {
  function foo() {
    //
  }
}

Checkout their docs for more details on the basics.