Reputation: 1206
I'm trying to save into the database but I constantly get this error
Call to undefined method stdClass::save()
my controller
$c = DB::table('subject_user')->where('user_id', $value)->first();
$c->auth_teacher = '1';
$c->save();
Upvotes: 15
Views: 35218
Reputation: 413
In case you started using DB:: instead of Model:: because you needed dynamic table name call, it is possible to use dynamic interface call instead, but I wonder if it is a good practice, anybody willing to explain if the following is wrong (since it works fine):
$model = 'User'; //Use the name of the model, not the table name
$interface_model = '\App\Models\\' . $model; //Needed to avoid the manual import of each model
$entry = $interface_model::where('id', $id)->first();
//$entry now support save()
Upvotes: 2
Reputation: 1217
In some situations, Laravel Controller doesn't accept find method. Maybe you have tried on your controller.
Solution-1)
Try to use find method in the model.
Solution-2)
Try to use Where clause in Controller instead of find.
Upvotes: 0
Reputation: 306
As you can read here there are two ways of saving/updating records. In your case you would need to do the following: https://laravel.com/docs/6.x/queries#updates
$affected = DB::table('users')
->where('id', 1)
->update(['votes' => 1]);
Upvotes: 0
Reputation: 24083
I just ran into the same problem and figured out the real Laravel answer.
The answer you've accepted here (https://stackoverflow.com/a/41051946/470749) doesn't follow the truest Laravel way.
When I re-read the docs at https://laravel.com/docs/5.4/eloquent#retrieving-models, I noticed that ->save()
will work only if the way that I retrieved the object(s) was via the model like this:
$flights = App\Flight::where('active', 1)
->orderBy('name', 'desc')
->take(10)
->get();
There is no need to use DB::table()
anywhere, and using it doesn't seem to be the recommended way.
So, you could change DB::table('subject_user')->where
to App\Subject_user::where
(or whatever is appropriate for you).
Upvotes: 13
Reputation: 2126
Try this approach
I haven't try save
method with where
condition. Hopefully, this approach may solve your problem.
DB::table('subject_user')->where('user_id', $value)->update(['auth_teacher' => 1]);
Upvotes: 22
Reputation: 1206
DB::table('subject_user')->where('user_id', $value)->update(['auth_teacher' => 1]);
I have been able to succeed with this.
Upvotes: 1