difference between fill() and update() in laravel - ajax

I want to change value in table using ajax in laravel.
But when i use fill(), returning value is "success", but when i use update(), returning value is fail.
My source code is follow.
public function deleteCourse($id){
$test = Course::find($id)->fill(['is_deleted' => 1])->save();
$res = ['res' => 'success'];
return json_encode($res);
}
public function deleteCourse($id){
$test = Course::find($id)->update(['is_deleted'=>1])->save()'
$res = ['res'=>'success'];
return json_encode($res);
}

You can't call ->save() after ->update(), since it returns a boolean 1 or 0 (success or fail). The record is directly updated in the database, so ->save() is not required.
fill() on the other hand doesn't persist anything to the database until you call ->save(), so it is required in that instance.
public function deleteCourse($id){
$test = Course::find($id)->fill(['is_deleted' => 1])->save();
$res = ['res' => 'success'];
return json_encode($res);
}
// OR
public function deleteCourse($id){
$test = Course::find($id)->update(['is_deleted'=>1]);
$res = ['res'=>'success'];
return json_encode($res);
}

Fill will not save into database until you call ->save on the object.
Update will change the value in the database immediately.
In your case line was not terminated correctly. Add a semicolon at the end.
$test = Course::find($id)->update(['is_deleted'=>1]);

Related

Laravel Multiple Edit/Upload File

I want to make my code more efficient in my Controller. This code is about to update file in the database and then delete the file were chosen, rather than use if-condition i will use switch statement and then call the updateFile function for each case of file name. But i have problem on my switch statement, it supposed to run for each case but doesn't.
private function updateFile($strFileName, $oldFileName){
if($request->file($strFileName)){
if($request->$oldFIleName){
Storage::delete($request->$oldFIleName);
}
$validatedData[$strFileName] = $request->file($strFileName)->store('post-files');
}
}
public function update(Request $request, Task $task)
{
//storing files request
$rules = [
'file_jamlak' => 'mimes:pdf,png,jpg|file|max:4096',
'file_kontrak' => 'mimes:pdf,png,jpg|file|max:4096',
'file_jamuk' => 'mimes:pdf,png,jpg|file|max:4096']
//validate rules in to new variable
$validatedData = $request->validate($rules);
//the switch
$file_name = $request->file();
switch($file_name){
case 'file_jamlak' : $this->updateFile('file_jamlak', 'oldJamlak');
}
//condition
//jamlak
if($request->file('file_jamlak')){
if($request->oldJamlak){
Storage::delete($request->oldJamlak);
// return $request->oldJamlak;
}
$validatedData['file_jamlak'] = $request->file('file_jamlak')->store('post-files');
$validatedData['jamlak'] = 1;
}
//kontrak
if($request->file('file_kontrak')){
if($request->oldKontrak){
Storage::delete($request->oldKontrak);
}
$validatedData['file_kontrak'] = $request->file('file_kontrak')->store('post-files');
$validatedData['kontrak'] = 1;
}
//add user id
$validatedData['user_id'] = auth()->user()->id;
//update eloquent
Task::where('id', $task->id)
->update($validatedData);
//dd($file_name);
return redirect('/admin/tasks')->with('success', 'New post has been updated!');
}
i think i made mistake on the $file_name, that it supposed to store file name but doesn't work. Please help me
Make sure you've file name in your case which you are checking against:
// ...
//the switch
$file_name = $request->file();
switch($file_name){
// make sure this name matches the name of the file you are submitting
// from the form on front end to be able to fall into this case
case 'file_jamlak' : $this->updateFile('file_jamlak', 'oldJamlak');
// ...

Stuck at Error = Method Illuminate\Database\Eloquent\Collection::save does not exist

Trying to save data while open page but stuck at error :
"Method Illuminate\Database\Eloquent\Collection::save does not exist."
I have 2 database :
Buffalodata
Buffalomilkrecord
From 2nd table i need to get the avg of totalmilk and update the same to main database (1). This help me to show updated avgmilk data on dashboard front page.
Route:
Route:: get('buffalo-details', 'App\Http\Controllers\BuffalodataController#buffalodetails');
BuffalodataController Controller :
public function buffalodetails()
{
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')->pluck('buffaloID')->toArray();
foreach ($buffalidforavgmilk as $id )
{
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->sum('totalmilk');
$avgbuffalocount = Buffalomilkrecord::where('buffaloID',$id)->count();
$getavg = $milkperid / $avgbuffalocount;
$data = Buffalodata::find($buffalidforavgmilk);
$data->avgmilk = ($getavg);
$data->save ();
// dump([$milkperid,$avgbuffalocount,$getavg,$data,$id]);
}
return view ('pages.Buffalo.BuffaloDetails',[---------]);
}
Thanks again in Advance
When you pass an Array to ::find(), it returns a Collection, which doesn't have a save() method. This is your code:
// This is an Array of `buffaloID` values
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')->pluck('buffaloID')->toArray();
...
// `$data` is now a `Collection` of `Buffalodata` instances
$data = Buffalodata::find($buffalidforavgmilk);
// This now fails, as `Collection` doesn't have a `save()` method
$data->save();
You can rewrite your code as follows:
Buffalodata::whereIn('buffaloID', $buffalidforavgmilk)->update(['avgmilk' => $getavg]);
This will update all records in a single call. If you want to iterate, that's an option too:
$data = Buffalodata::find($buffalidforavgmilk);
foreach ($data as $record) {
$record->avgmilk = $getavg;
$record->save();
}
Or, since you have $id already:
$record = Buffalodata::find($id);
$record->avgmilk = $getavg;
$record->save();

How to check data exists in the database

I have a function to add new property. But i want to check for duplicate data at column "code" before add new data into database. If data exists will appear a message error.
function addPro(Request $req)
{
$id = $req->type_id;
$type = AssetType::find($id);
if($req->save == 'save'){
$pro = new TypeProperties;
$pro->name = $req->name;
$pro->code = $req->code;
$pro->type = $req->type;
$pro->assettype_id = $req->type_id;
$pro->save();
Schema::table($type->code, function ($table) use ($pro) {
if ($pro->type == "textbox")
$table->string($pro->code )->nullable();
if ($pro->type == "textarea")
$table->text($pro->code )->nullable();
});
return redirect(url($type->id.'/add/property'))->with('message','Save successful');
}
return redirect(url('asset/type/'.$type->id));
}
You can use laravel Request Validation
function addPro(Request $req)
{
$id = $req->type_id;
$type = AssetType::find($id);
if($req->save == 'save'){
$req->validate([
'code' => 'required|unique:tablename'
]);
$pro = new TypeProperties;
$pro->name = $req->name;
$pro->code = $req->code;
$pro->type = $req->type;
$pro->assettype_id = $req->type_id;
$pro->save();
Schema::table($type->code, function ($table) use ($pro) {
if ($pro->type == "textbox")
$table->string($pro->code )->nullable();
if ($pro->type == "textarea")
$table->text($pro->code )->nullable();
});
return redirect(url($type->id.'/add/property'))->with('message','Save successful');
}
return redirect(url('asset/type/'.$type->id));
}
The most simple way to do this is by checking if code is_null :
if (is_null($pro->code)) {
// It does not exist
} else {
// It exists
}
The other way is to make a validation using Laravel's built in ValidateRequest class. The most simple use-case for this validation, is to call it directly in your store() method like this:
$this->validate($req, [
'code' => 'required|unique,
//... and so on
], $this->messages);
With this, you're validating users $req by saying that specified columns are required and that they need to be unique, in order for validation to pass. In your controller, you can also create messages function to display error messages, if the condition isn't met:
private $messages = [
'code.required' => 'Code is required',
'code.unique' => 'Code already exists',
//... and so on
];
You can also achieve this by creating a new custom validation class:
php artisan make:request StorePro
The generated class will be placed in the app/Http/Requests directory. Now, you can add a few validation rules to the rules method:
public function rules()
{
return [
'code' => 'required|unique,
//... and so on
];
}
All you need to do now is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic:
public function store(StorePro $req)
{
// The incoming request is valid...
// Retrieve the validated input data...
$validated = $req->validated();
}
If you have any additional question about this, feel free to ask. Source: Laravel official documentation.
What does your migration look like for AssetType?
I ask because you can do this in the schema with ->unique() added to the column on the creation or make a migration to add the constraint.
You can also check with something like this:
// Search database table for entry
$entry = AssetType::where('code', '=', $pro->code)->first();
// If not found
if ($entry === null) {
// Save method here.
}
Otherwise, you can use the manual validator or create a Request with validation
References:
https://laravel.com/docs/5.8/queries#where-clauses
https://laravel.com/docs/5.8/validation#creating-form-requests
https://laravel.com/docs/5.8/validation#manually-creating-validators

Laravel save new record returns nothing

I'm trying to save new record, all i get is a white page
even dump and dd for $applicant ->save() returns nothing.
public function store(Request $request) {
try {
if (Auth::guest()) {
return redirect()->route('login');
}
$applicant = new Applicant();
$applicant->first_name = $request->get('first_name');
$applicant->middle_name = $request->get('middle_name');
$applicant->last_name = $request->get('last_name');
dump($applicant);
$applicant->save();
dd('Saved');
} catch (Exception $e) {
Log::error("Error during orders creation:" .$e>getTraceAsString());
}
}
I expected the record should be saved
Try this instead
public function store(Request $request){
$applicant = new Applicant;
$applicant->first_name = $request->input('first_name');
$applicant->save();
}
and don't forget to include use App\Applicant model in your Controller class; If it does not solve your problem. please double check your form action post in view section.
I think save function will not return anything.
for data you must use create method.
Used return after save.
$applicant->save();
return response()->json(['success' => 'Data Added successfully.']);
Use create in stead, write less code if you can us always better.
Try this:
Application::create($request->all());
Or change it the way you need by assigning every array key to its value

Call to a member function fill() on array

I am trying to update data from the product table. But, when I try to update laravel, it gives me an error which says call to a member function fill() on array. When I debug $data I got an array of key and values.
I have the following code:
public function update(Request $request,Products $product)
{
$this->products = $this->products->find($product->id);
if(!$this->products){
request()->session()->flash('error','Product not found!');
return redirect()->route('product.index');
}
$rules = $this->products->getRules('update');
$this->products = $request->validate($rules);
$data = $request->all();
$data['added_by'] = $request->user()->id;
$data['image'] = explode(',',$data['related_images'])[0];
$this->products->fill($data); //Getting error here
$status = $this->products->save();
if($status){
$request->session()->flash('success','Product updated successfully.');
} else {
$request->session()->flash('error','Sorry! there was problem updating product.');
}
return redirect()->route('product.index');
}
I want the fill() function to work so that it can update my data on the product table.
The line below is overwriting your products with an array of the keys that passed validation. You can fix it by removing the assignment (if there are errors, a 422 error will still be returned)
$this->products = $request->validate($rules);
// change to
$request->validate($rules);

Resources