简体   繁体   中英

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 App\Http\Controllers\create()

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

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.

you should use the model's create method : create method accepts an array of attributes, creates a model, and inserts it into the database:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM