Method update does not exist in Laravel - laravel-5

It is very simple code to update an existing entry. save() is working perfectly. But update is not working. Here is my code:
Route::post('toggleFavourite',function(){
try{
$data = Request::all();
extract($data);
$favourite = \ItScholarBd\Api\Models\Favourite::where(['user_id'=> $user_id,'shop_id'=> $shop_id])->get();
if(empty($favourite)){
$favourite = new \ItScholarBd\Api\Models\Favourite;
$favourite->user_id = $user_id;
$favourite->shop_id = $shop_id;
$favourite->status = $status;
$favourite->save();
}else{
$favourite->status = $status;
$favourite->update();
}
return response()->json(['status' =>1, 'data' => $favourite], 200);
}
catch (Exception $ex) {
return response()->json(['status'=>0, 'status_text' => $ex->getMessage()], 500);
}
});
I am getting the following response:
{"status":0,"status_text":"Method update does not exist."}

the docs say the following for an update
$flight = App\Models\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();

I believe the only thing you have to change to make your code work is replace $favourite->update(); with $favourite->save();, but I tried to make your code a little bit simpler:
use Illuminate\Http\Request;
use ItScholarBd\Api\Models\Favourite;
Route::post('toggleFavourite', function (Request $request) {
try {
$user_id = $request->get('user_id');
$shop_id = $request->get('shop_id');
$status = $request->get('status');
// get the existing favourite or a new instance
$favourite = Favourite::where(['user_id' => $user_id, 'shop_id' => $shop_id])->firstOrNew();
// check if it exists in the database
if (!$favourite->exists()) {
$favourite->user_id = $user_id;
$favourite->shop_id = $shop_id;
}
$favourite->status = $status;
$favourite->save();
return response()->json(['status' => 1, 'data' => $favourite], 200);
} catch (Exception $ex) {
return response()->json(['status' => 0, 'status_text' => $ex->getMessage()], 500);
}
});
PS:
You should add validation to your route, so you don't just accept and store any values that are being sent with the request in the database.

From my observation, I come to a conclusion:
update is only work on an OBJECT of find($id) method. The following code works perfectly:
try {
$data = Request::all();
extract($data);
$favourite = Favourite::where(['user_id' => $user_id, 'shop_id' => $shop_id]);
if (!$favourite->count()) {
$favourite = new Favourite;
$favourite->user_id = $user_id;
$favourite->shop_id = $shop_id;
$favourite->status = $status;
$favourite->save();
}else{
$favourite = $favourite->get()->toArray();
$favourite = Favourite::find($favourite[0]['id']);
$favourite->status = $status;
$favourite->update();
}
return response()->json(['status' => 1, 'data' => $favourite], 200);
} catch (Exception $ex) {
return response()->json(['status' => 0, 'status_text' => $ex->getMessage()], 500);
}

Related

laravel excel import update only if there is a change

i have laravel excel maatwebsite import update function, it works really well but i want to mark record that change by add "correction_flag" variable. the question is, how can i set this "correction_flag" when import.
this is my import function:
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
$tgl_lahir_cell = $this->transformDate($row['tanggal_lahir']);
$tgl_awal_masa_kerja_cell = $this->transformDate($row['tanggal_awal_masa_kerja']);
$tgl_menjadi_permanen_cell = $this->transformDate($row['tanggal_menjadi_permanen']);
$tgl_keluar_cell = $this->transformDate($row['tanggal_keluar']);
if($tgl_lahir_cell == '1970-01-01') {
$formatedDate1 = NULL;
}else{
$formatedDate1 = $tgl_lahir_cell;
}
if($tgl_awal_masa_kerja_cell == '1970-01-01') {
$formatedDate2 = NULL;
}else{
$formatedDate2 = $tgl_awal_masa_kerja_cell;
}
if($tgl_menjadi_permanen_cell == '1970-01-01') {
$formatedDate3 = NULL;
}else{
$formatedDate3 = $tgl_menjadi_permanen_cell;
}
if($tgl_keluar_cell == '1970-01-01') {
$formatedDate4 = NULL;
}else{
$formatedDate4 = $tgl_keluar_cell;
}
Tempdat::where('cc', Auth::user()->ccode)
->where('id_tempdat', $row['id_tempdat'])
->update([
'golongan' => $row['golongan'],
'nama' => $row['nama'],
'jenis_kelamin' => $row['jenis_kelamin'],
'tgl_lahir' => $formatedDate1,
'tgl_awal_masa_kerja' => $formatedDate2,
'tgl_menjadi_permanen' => $formatedDate3,
'status_awal' => $row['status_di_awal_periode'],
'gaji_pokok_awal' => $row['gaji_pokok_di_awal_periode'],
'tunjangan_tetap_awal' => $row['tunjangan_tetap_di_awal_periode'],
'total_upah_awal' => $row['total_upah_di_awal_periode'],
'status_akhir' => $row['status_di_akhir_periode'],
'tgl_keluar' => $formatedDate4,
'status2_akhir' => $row['keterangan_keluar'],
'gaji_pokok_akhir' => $row['gaji_pokok_di_akhir_periode'],
'tunjangan_tetap_akhir' => $row['tunjangan_tetap_di_akhir_periode'],
'total_upah_akhir' => $row['total_upah_di_akhir_periode'],
'jumlah_pesangon_paid_awal' => $row['pesangon_dibayarkan_pada_periode'],
'correction_flag' => 'CORRECTED'
]);
}
}
public function headingRow(): int
{
return 4;
}
public function startRow(): int
{
return 5;
}
i already tried to put correction_flag like the example above but its just make all record uploaded marked CORRECTED eventhou there is no changes happend.
You need to first() the query, because laravel model event listeners won't work if there's mass update/create. So what you need to do is:
$tempdat = Tempdat::where('cc', Auth::user()->ccode)->where('id_tempdat', $row['id_tempdat'])->first();
if($tempdat){
$tempdat->update([
...
]);
}
And add this function to your Temptdat model:
protected static function booted()
{
parent::boot();
self::saving(function ($model) {
if ($model->isDirty()) {
$model->correction_flag = 'CORRECTED';
}
});
}

do not show the success message if the data hasnt been updated n a form laravel

i have a form whereby on updating the data and storing it to the database it shows a success message.if one of the inputs isn't filled it shows an error.am getting a bug whereby when i want to re-update the data and i open the form with the existing inputs when i click save the data should just redirect back to the previous page and not show the success message as the data hasnt being updated.how can i achieve this,am looking for a logic here fellow devs..here is my update function code
public function update(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'systemid' => 'required',
'category' => 'required',
'subcategory' => 'required',
'prdcategory' => 'required',
'prdbrand' => 'required'
]);
Log::debug('Request: '.json_encode($request->file()));
if ($validation->fails()) {
throw new \Exception("validation_error", 19);
}
$systemid = $request->systemid;
$product_details = product::where('systemid', $systemid)->first();
$changed = false;
if ($request->has('product_name')) {
if ($product_details->name != $request->product_name) {
$product_details->name = $request->product_name;
$changed = true;
}
}
if ($request->has('category')) {
if ($product_details->prdcategory_id != $request->category) {
$product_details->prdcategory_id = $request->category;
$changed = true;
}
}
if ($request->has('subcategory')) {
if ($product_details->prdsubcategory_id != $request->subcategory) {
$product_details->prdsubcategory_id = $request->subcategory;
$changed = true;
}
if ($product_details->ptype == 'voucher') {
$voucher = voucher::where('product_id', $product_details->id)->first();
if($voucher->subcategory_id != $request->subcategory){
$voucher->subcategory_id = $request->subcategory;
$voucher->save();
$changed = true;
}
}
}
if ($request->has('prdcategory')) {
if ($product_details->prdprdcategory_id != $request->prdcategory) {
$product_details->prdprdcategory_id = $request->prdcategory;
$changed = true;
}
}
if ($request->has('prdbrand')) {
if ($product_details->brand_id != $request->prdbrand) {
$product_details->brand_id = $request->prdbrand;
$changed = true;
}
}
if ($request->has('description')) {
if ($product_details->description != $request->description) {
$product_details->description = $request->description;
$changed = true;
}
}
if ($changed == true || true) {
$product_details->save();
$msg = "Product information updated successfully";
$data = view('layouts.dialog', compact('msg'));
//i have added this code but it doesnt work
} else if($changed == false) {
return back();
$data = '';
}
}
return $data;
}
my laravel project version is 5.8
The following line will always evaluate to True
$changed == true || true
And you have a catch statement missing at the end so I had to add it.
And I advise you to simply get the dirty version of $product_details.
You can use $product_details->isDirty() // boolean.
Or even better way is to use $product_details->wasChanged() // boolean
Here is the code after some tweaks:
public function update(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'systemid' => 'required',
'category' => 'required',
'subcategory' => 'required',
'prdcategory' => 'required',
'prdbrand' => 'required'
]);
Log::debug('Request: '.json_encode($request->file()));
if ($validation->fails()) {
throw new \Exception('validation_error', 19);
}
$systemid = $request->systemid;
$product_details = Product::where('systemid', $systemid)->first();
$changed = false;
// Looping for all inputs:
$fieldsToCheck = [
'name' => 'product_name',
'prdcategory_id' => 'category',
'prdsubcategory_id' => 'subcategory',
'prdprdcategory_id' => 'prdcategory',
'brand_id' => 'prdbrand',
'description' => 'description',
];
foreach ($fieldsToCheck as $productColumnName => $requestFieldName) {
$requestInput = $request->{$requestFieldName};
if ($request->has($requestFieldName)) {
if ($product_details->$productColumnName != $requestInput) {
$product_details->$productColumnName = $requestInput;
$changed = true;
}
}
// Exception for Sub Category to check for the voucher.
if ($requestFieldName == 'subcategory') {
$this->handleVoucher($requestInput);
}
}
// here I advise you to simply get the dirty version of $product_details
// you can use $product_details->isDirty() // boolean
// or even better use $product_details->wasChanged() // boolean
if ($changed) {
$product_details->save();
$msg = 'Product information updated successfully';
$data = view('layouts.dialog', compact('msg'));
} else {
return back();
// Todo Mo: No need for this line so I commented it out.
//$data = '';
}
} catch (\Exception $e) {
dd($e->getMessage(), 'Oops, error occurred');
}
return $data;
}
private function handleVoucher($product_details, $subcategory)
{
if ($product_details->ptype == 'voucher') {
$voucher = voucher::where('product_id', $product_details->id)->first();
if ($voucher->subcategory_id != $subcategory) {
$voucher->subcategory_id = $subcategory;
$voucher->save();
}
}
}

Eloquent save method not working when the data comes from Vue frontend

I have this code in a Vue Component:
sendUserData(){
axios.post('/api/saveUser', {
data: {
id: this.id,
name: this.name,
email: this.email,
password: this.password
}
},
{
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
}
).then(response => {
if(response.data == 'success'){
this.$emit('userSaveSuccess')
} else {
this.$emit('userSaveError')
}
});
}
and I have this in a Laravel Controller:
public function saveUser($name = '', $email = '', $password = ''){
$id = request('data.id', 0);
$name = request('data.name', $name);
$email = request('data.email', $email);
$password = request('data.pswrd', $password);
Log::info(request());
if($id == 0){
$saveUser = new User;
} else {
$saveUser = User::find($id);
if($name == ''){
$name = $saveUser -> name;
}
if($email == ''){
$email = $saveUser -> email;
}
}
$saveUser -> name = $name;
$saveUser -> email = $email;
if($password != ''){
$saveUser -> password = bcrypt($password);
}
if($saveUser->save()){
return 'success';
} else {
return 'error';
}
}
My problem is, that it's output is success, but in the MySQL DB nothing has changed.
In the Log's I got this:
[2019-09-08 12:32:08] local.INFO: array (
'data' =>
array (
'id' => 2,
'name' => 'AdminTest',
'email' => 'admin#test.com',
),
)
(The original name is Admin -> the Laravel function got the request)
I tested it with Postman, too, and that time the save method worked.
What's the problem?
Edit:
Images
Edit2:
console.log(response) image
Replace your saveUser() method with the following and it will work.
/**
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function saveUser(Request $request){
// validate request data
$validator = \Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'pswrd' => 'required' // add your custom validation rule
]);
// throw an validation error with message
if ($validator->fails())
return response()->json(['message' => 'The given data was invalid.', 'errors' => $validator->errors()], 422);
// best way to get request input values ( laravel docs )
$id = $request->get('id') ?? 0;
$name = $request->name;
$email = $request->email;
$password = $request->psswrd;
// TODO: you can replace the logic with ( updateOrCreate($saveUser) )
if($id == 0){
$saveUser = new User;
} else {
$saveUser = User::find($id);
}
$saveUser -> name = $name;
$saveUser -> email = $email;
if($password != ''){
$saveUser -> password = bcrypt($password);
}
try{
$saveUser->save();
return response()->json(['message' => 'Success.', 'data' => $saveUser], 200);
}catch (\Exception $exception){
return response()->json(['message' => 'Error.', 'data' => $exception->getMessage()], 200);
}
}

Dropdownlist selected value not showing while updating the form

Here i like to explain my problem
i have dropdownlist called companytype, it contains value 1+1, 1+2, 1+3, 1+4, 1+5, 1+6, 1+7
while creating form i have a select a value eg:1+4 and store, but the same while updating the value getting change as select companytype [prompt]
<?= $form->field($model, 'companytype')->dropDownList([ '1' => '1+1', '2' => '1+2', '3' => '1+3', '4' => '1+4', '5' => '1+5', '6' => '1+6', '7' => '1+7', ], ['prompt' => 'Select Company Type', ]) ?>
here i have added two images you can easily understand my question
gridview of created form
updating the same form
updated:
mycontroller code:
public function actionCreate()
{
if(Yii::$app->user->can( 'create-company' ) )
{
$model = new Company();
if ($model->load(Yii::$app->request->post()) ) {
$model->createdat = date('Y-m-d');
$ro = $model->relationoption;
if($ro == 'fixed')
{
$commaList = implode(', ', $model->relation);
$model->relation = $commaList;
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
else
{
throw new ForbiddenHttpException;
}
}
controller code for update
public function actionUpdate($id)
{
if(Yii::$app->user->can('update-company'))
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) )
{
$model->updatedat = date('Y-m-d h:m:s');
$ro = $model->relationoption;
if($ro == 'fixed')
{
$commaList = implode(', ', $model->relation);
$model->relation = $commaList;
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
]);
}
else
{
throw new ForbiddenHttpException;
}
}
Is there anyone to answer, pls answer me
I dont see $model->companytype = 4 in your update action. Can you add it to your update action and check. So your update action should look like:
public function actionUpdate($id)
{
if(Yii::$app->user->can('update-company'))
{
$model = $this->findModel($id);
$model->companytype = 4;
if ($model->load(Yii::$app->request->post()) )
{
$model->updatedat = date('Y-m-d h:m:s');
$ro = $model->relationoption;
if($ro == 'fixed')
{
$commaList = implode(', ', $model->relation);
$model->relation = $commaList;
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
]);
}
else
{
throw new ForbiddenHttpException;
}
}

Laravel: How to insert multiple records

I want to insert multiple records in my database using Laravel, however when i insert it, it only gives me one record in the database
Here's my Controller
public function postCreateAttendance()
{
$validate = Validator::make(Input::all(), array(
'status' => 'required'
));
if ($validate->fails())
{
return Redirect::route('viewStudent')->withErrors($validate)->withInput();
}
else
{
foreach(User::all() as $user):
foreach(User::whereRaw('isTeacher = "0" and isAdmin = "0"')->get() as $student)
foreach(User::whereRaw('isTeacher = "1" and isAdmin = "0"')->get() as $teacher)
//$users[$user->id]=$user->firstname;
$attendance = new Attendance();
$attendance->status = Input::get('status');
$attendance->comment = Input::get('comment');
$attendance->student_id = $student->id=$student->id;
$attendance->student_firstname = $student->id=$student->firstname;
$attendance->student_lastname = $student->id=$student->lastname;
$attendance->teacher_id = $teacher->id=$teacher->id;
$attendance->teacher_firstname = $teacher->id=$teacher->firstname;
$attendance->teacher_lastname = $teacher->id=$teacher->lastname;
if($attendance->save())
{
return Redirect::route('viewStudent')->with('success', 'ATTENDANCE HAS BEEN RECORDED!');
}
else
{
return Redirect::route('viewStudent')->with('fail', 'An error occured while creating the attendance.');
}
endforeach;
}
}
How can i save multiple records? Please help Thank You ^_^
The issue is that you are returning during the foreach loop - so only one record is processed. You need to process all the records, then return the route.
Here is some refactoring of your code
public function postCreateAttendance()
{
$validate = Validator::make(Input::all(), array(
'status' => 'required'
));
if ($validate->fails()) {
return Redirect::route('viewStudent')->withErrors($validate)->withInput();
}
foreach(User::where('isTeacher', '0')->where('isAdmin', '0')->get() as $student) {
foreach(User::where('isTeacher', '1')->where('isAdmin', '0')->get() as $teacher) {
$attendance = new Attendance();
$attendance->status = Input::get('status');
$attendance->comment = Input::get('comment');
$attendance->student_id = $student->id;
$attendance->student_firstname = $student->firstname;
$attendance->student_lastname = $student->lastname;
$attendance->teacher_id = $teacher->id;
$attendance->teacher_firstname = $teacher->firstname;
$attendance->teacher_lastname = $teacher->lastname;
$attendance->save();
}
}
return Redirect::route('viewStudent')->with('success', 'ATTENDANCE HAS BEEN RECORDED!');
}
Edit: I've removed the first foreach(User::all() as $user): - because at the moment, in your code, it does nothing...?

Resources