Call to undefined method Illuminate\Database\Query\Builder::save()

前端 未结 3 1489
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 06:53

I am trying to call Eloquent\'s save() method on an existing record but getting an error from Illuminate\'s Query Builder.

Following the documentation on Laravel\'s web

相关标签:
3条回答
  • 2021-02-07 07:03

    you have to fetch your model after given an ->where

    $this->employee = Employee::where('login', $login)->get();
    

    or

    $this->employee = Employee::where('login', $login)->first();
    

    if you don't do that your Object $this->employee would't be one and you could not use ->save()

    0 讨论(0)
  • Maybe more details for better understanding

    With your Employee model :

    if you make

    Employee::find(1)
    

    This will return a Eloquent model object (Instance of Employee Class)

    if you make

    Employee::where('field',op,value)
    

    This will return a Builder object (Instance of Laravel Builder class)

    if you make

    Employee::where('field',op,value)->get()
    

    This will return a Collection of your object (List of Employee instance)

    if you make

    Employee::where('field',op,value)->first()
    

    This first() execute the get() function and then return the first element of the collection.

    Laravel models extends Model class, and in this Model class is the save() function. so to be able to call it you have to have an instance of your model and not something else.

    RM : be aware of the first() function, if there is 2 elements returned this result behave like there is only one result and its not true. in your case the login is declared as unique in the db so it should not be a problem, but be aware for another situations.

    0 讨论(0)
  • 2021-02-07 07:12

    Apparently the ->get() method will not work with Eloquent's ->save() method and you must use ->first() instead.

    Correct: $this->employee = Employee::where('login', $login)->first();

    Incorrect: $this->employee = Employee::where('login', $login)->get();

    See http://laravel.io/forum/06-04-2014-symfony-component-debug-exception-fatalerrorexception-call-to-undefined-method-illuminatedatabaseeloquentcollectionsave for additional reference.

    0 讨论(0)
提交回复
热议问题