Laravel returns old model after update - laravel

When i store a new record, Laravel returns the new record. Everything works fine.
When i update a record, Laravel returns the old record. I like to return the updated record.
Controller
public function store(StoreProjectRequest $request)
{
$data = $this->repo->create( $request->all());
return response()->json(new ProjectResource($data));
}
public function update(UpdateProjectRequest $request, Project $project)
{
$data = $this->repo->update($project, $request->all());
return response()->json(new ProjectResource($data));
}
Repository
public function create( $data)
{
$this->model->name = $data['name'];
$this->model->description = $data['description'];
$this->model->sales_order_id = $data['sales_order_id'] ? $data['sales_order_id'] : NULL;
$this->model->project_leader_id = $data['project_leader_id'];
$this->model->project_type_id = $data['project_type_id'];
$this->model->project_status_id = $data['project_status_id'];
$this->model->creator_id = Auth()->id();
$this->model->save();
return $this->model;
}
public function update($model, $data)
{
$model->name = $data['name'];
$model->description = $data['description'];
$model->sales_order_id = $data['sales_order_id'];
$model->project_leader_id = $data['project_leader_id'];
$model->project_type_id = $data['project_type_id'];
$model->project_status_id = $data['project_status_id'];
$model->save();
return $model;
}
When i add $data = Project::find($project->id)i receive the updated model.
But is this the only way?

The reason the $data is returning as the old data is because it still stores the data from when the variable was created. When you call $data->fresh() it will go fetch the new data and return it. Does that make sense?

Related

How do i update image in the repository by upload?

I'm setting up a CRUD, similar to an ecommerce
I uploaded the image, it is stored in the public folder. The name of the image is replaced by the value of an input that the user places. This same value is saved in the database with the image extension.
I was also able to delete the image, but I don't know how to update it. Can someone please give me a light?
project controller:
public function store(Request $request)
{
$nameFile = $request->input('imageName', '');
if($request->file('imageFile')->isValid()){
$nameFile .= '.' . $request->file('imageFile')->getClientOriginalExtension();
$request->file('imageFile')->storeAs('projects', $nameFile);
}
$project = new Project();
$project->name = $request->input('name');
$project->price = $request->input('price');
$project->imageName = $nameFile;
$project->save();
return redirect()->route('ProjectControllerCreate');
}
public function destroy($id)
{
$project = Project::find($id);
// Image
$filePathName = public_path().'/storage/projects/'. $project->imageName;
if( file_exists($filePathName) ){
unlink($filePathName);
}
// Data
if(!$project)
return redirect()->back();
$project->delete();
return redirect()->route('ProjectControllerCreate');
}
public function update(Request $request, $id)
{
$project = Project::find($id);
if(!$project)
return redirect()->back();
$project->update($request->all());
return redirect()->route('ProjectControllerCreate');
}
This is how you can update :
use Illuminate\Support\Facades\Storage;
public function update(Request $request, $id)
{
$project = Project::find($id);
if(!$project)
return redirect()->back();
// Update new image
if($request->file('imageFile')->isValid()){
// Delete old image
$old_image = $project->imageName;
Storage::delete($old_image);
$nameFile = $request->input('imageName', '');
$nameFile .= '.' . $request->file('imageFile')->getClientOriginalExtension();
$request->file('imageFile')->storeAs('projects', $nameFile);
$project->imageName = $nameFile;
}
$project->name = $request->input('name');
$project->price = $request->input('price');
$project->save();
return redirect()->route('ProjectControllerCreate');
}

How to update 2 table data using query builder

I have problem with edit and update with 2 table using query builder.
--->After i press button submit--->the data insert new row---> not update current data.
This is my function edit(only for view old data)
public function edit(Request $request, $id){
$tax_rate = TaxRate::find($id);
$tax_rate_details = TaxRateDetail::where('tax_rate_id', $id)->get();
$country = Country::all();
$geo_zones = GeoZone::all();
//dd($tax_rate);
//dd($tax_rate_details);
//dd($geo_zones);
if(!$tax_rate) {
return redirect('/');
}
return view('tax_management.edit',['country' => $country , 'tax_rate'=>$tax_rate , 'geo_zones'=>$geo_zones, 'tax_rate_details'=>$tax_rate_details]);
}
This is my update(i do validation and the saveTax is the saving part)
public function update(Request $request, $id){
$this->validate($request,[
'country_id'=> 'required',
'tax_type' => 'required',
'name' => 'required|max:100',
'code' => 'required|max:50'
]);
//dd($request->input());
DB::beginTransaction();
try{
$tax_rate = TaxRate::find($id);
$tax_rate_details = TaxRateDetail::where('tax_rate_id', $id)->get();
$this->saveTax($request, $tax_rate);
DB::commit();
return redirect()->route('tax_management.index');
} catch (\Exception $ex){
//dd($ex);
DB::rollback();
return back()->withInput()->withErrors('Fail to save');
}
}
This is my function save()
private function saveTax(Request $request, $tax_rate){
$tax_rate->country_id = $request->input('country_id');
$tax_rate->geo_zone_id = $request->input('geo_zone_id');
$tax_rate->tax_type = $request->input('tax_type');
$tax_rate->name = $request->input('name');
$tax_rate->code = $request->input('code');
$tax_rate->description = $request->input('description');
if(!empty($request->input('active'))){
$tax_rate->active =1;
} else {
$tax_rate->active =0;
}
$tax_rate->save();
if($tax_rate->tax_rate_id) {
TaxRateDetail::where('tax_rate_id', $tax_rate->tax_rate_id)->delete();
}
if($request->input('tax_rate_details')){
foreach ($request->input('tax_rate_details') as $key => $value) {
$tax_rate_detail = new TaxRateDetail();
$tax_rate_detail->tax_rate_id = $tax_rate->tax_rate_id;
$tax_rate_detail->priority = $value['priority'];
$tax_rate_detail->date_from = $value['date_from'];
$tax_rate_detail->date_to = $value['date_to'];
$tax_rate_detail->rate = $value['rate'];
$tax_rate_detail->type = $value['type'];
$tax_rate_detail->active = $value['active'];
//dd($tax_rate_detail);
$tax_rate_detail->save();
}
}
}
I want to save edit update with old(id). not create new. Please help thank you. I don't know where the code gone wrong.

Update all fields except one field

public function update(Request $request, $id)
{
$house = House::find($id);
$house->name = $request->name;
$house->code = $request->code;
$house->description = $request->description;
$house->address = $request->address;
$house->owner_name = $request->owner_name;
$house->manager_name = $request->manager_name;
if($house->update()){
return redirect()->route('houses')
->with('alert.status', 'success')
->with('alert.message', 'Successfully Updated.');
}
else{
return redirect()->route('houses')
->with('alert.status', 'danger')
->with('alert.message', 'Try Again.');
}
}
Here i want to update all my fields except code when the code already exists in the database.How can i do that please give some solution.Thank you in advance.
You can use the null coalescing operator, available in php version 7.
In short, you can do this:
public function update(Request $request, $id)
{
$house = House::find($id);
$house->code = $house->code ?? $request->code;
$house->save();
}
If $house->code is different from null, this will be used if it will not use $request->code.
https://www.tutorialspoint.com/php7/php7_coalescing_operator.htm
do this way with ternary condition :
public function update(Request $request, $id)
{
$house = House::find($id);
$house->code = !empty($house->code) && $house->code!= NULL ? $house->code : $request->code;
}
Use a if :
public function update(Request $request, $id)
{
$house = House::find($id);
$house->name = $request->name;
if($house->code == NULL)
$house->code = $request->code;
$house->description = $request->description;
$house->address = $request->address;
$house->owner_name = $request->owner_name;
$house->manager_name = $request->manager_name;
$house->save();
if($house->update()){
return redirect()->route('houses')
->with('alert.status', 'success')
->with('alert.message', 'Successfully Updated.');
}
else{
return redirect()->route('houses')
->with('alert.status', 'danger')
->with('alert.message', 'Try Again.');
}
}
You should use the save() method after you made all this changes.
You can check for code existence on database by Eloquent: Mutators like below on your House Model
class House extends Model
{
//your codes
public function setCodeAtrribute($value)
{
if ($this->attributes["code"] != null) $this->attributes["code"] = $value
}
}
You can also check here for more information

What to Show some data On my view but there is a Error In Laravel

Here I am trying to add, Add Comment feature and it's causing a problem to show data.
public function store(Request $request)
{
$chatterreply = new Chatterreply;
$chatterreply->reply = $request->body;
$chatterreply->chatter_post_id = $request->chatter_post_id;
$chatterreply->chatter_discussion_id = $request->chatter_discussion_id;
$chatterreply->save();
$chatterreplies = Chatterreply::where('chatter_post_id',$request->chatter_post_id)->get();
$chatter_editor = config('chatter.editor');
if ($chatter_editor == 'simplemde') {
// Dynamically register markdown service provider
\App::register('GrahamCampbell\Markdown\MarkdownServiceProvider');
}
echo "<pre>"; print_r($chatterreplies); die;
return view('chatter::discussion', compact('chatterreplies','chatter_editor'))->with('chatter_alert','Add Comment Successfully');
}
And Here Is Where I am passing the variable
$chatter = session()->pull('chatter');
return view('chatter::discussion', compact('discussion', 'posts', 'chatter_editor'))->with('chatterreplies',$chatter);

laravel Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::save() must be of the type array, object given

I have an entity and each entity has an address.
I have 2 tables with relationship such as:
Entity:
protected $table = 'entities';
public $timestamps = true;
use Searchable;
public function address()
{
return $this->hasOne('App\Address', 'entity_id');
}
Address:
protected $table = 'address';
public $timestamps = true;
public function entity()
{
return $this->belongsTo('App\Entity', 'id');
}
and my controller:
public function update(EntityRequestUpdate $request)
{
$id = $request->input('entity_id');
$entity = Entity::with('address')
->find($id);
$entity->name = $request->input('name');
$entity->type = $request->input('type');
$entity->email = $request->input('email');
$entity->twitter_entity = $request->input('twitter');
$entity->facebook_entity = $request->input('facebook');
$entity->instagram_entity = $request->input('instagram');
$entity->google_places = $request->input('google');
$entity->address->building_name = $request->input('address1');
$entity->address->street = $request->input('address2');
$entity->address->town = $request->input('town');
$entity->address->city = $request->input('city');
$entity->address->postcode = $request->input('postcode');
$entity->address->telephone = $request->input('telephone');
$entity->address->save($entity);
$entity->save();
$result = $entity->save();
if($result){
$message = 'success';
}else{
$message = 'error';
}
return redirect()->back()->withInput()->with('message', $message);
}
An error message is:
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::save() must be of the type array, object given, called in C:\xampp\htdocs\laravel\app\Http\Controllers\EntityController.php on line 146
How can I solve this issue?
I think you just need to use save() method without any parameters. I have try it in php artisan tinker with same structure. And after I get same error, I try to remove the $entity parameter inside save() method:
// After update, you should only use save() not save($entity)
$entity->address->save();
I hope I give correct answer for your problem :-D

Resources