How to update 2 table data using query builder - laravel

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.

Related

I am having issue while keeping the same slug if we don't change title while updating

I am having issue while keeping the same slug if we don't change title while updating, slug take the value of title. I have made a function to create slug. But when i update the same function automatically changes slug because it already exists in DB.
public function createSlug($title, $id = 0)
{
$slug = str_slug($title);
$allSlugs = $this->getRelatedSlugs($slug, $id);
if (! $allSlugs->contains('slug', $slug)){
return $slug;
}
$i = 1;
$is_contain = true;
do {
$newSlug = $slug . '-' . $i;
if (!$allSlugs->contains('slug', $newSlug)) {
$is_contain = false;
return $newSlug;
}
$i++;
} while ($is_contain);
}
// slug function
protected function getRelatedSlugs($slug, $id = 0)
{
return Post::select('slug')
->where('slug', 'like', $slug.'%')
->where('id', '<>', $id)
->get();
}
First of all, you don't need to create a function for that. Just validation will be enough.
use Illuminate\Support\Str;
$validator = $request->validate([
'slug' => ['required''unique:post'],
]);
if ($validator->fails()) {
$generate_extension = Str::random(3);;
}
$newSlug = str_slug($request->title).'-'.$generate_extension;
Then assign the slug.
$post->slug = $newSlug;
In order to keep the same slug you can check if title is changed;
if($post->slug != str_slug($request->title)){
$post->slug = str_slug($request->title);
}
or
if($post->title != $request->title){
$post->slug = str_slug($request->title);
}

Multistep form using ajax in Laravel 8

I created a multistep form but I didn't use Ajax in it because I have no idea about Ajax. I have had to code a lot in my controller and routes for the way I created it which is probably not optimized. I'm new to Laravel so I can't find any solution.
How can I do this with ajax?
Controller
public function InitialCreateReport(Request $request){
$request->session()->forget('report');
$data['fiscalyear'] = FiscalYear::all();
$data['month'] = Months::all();
$data['report_type'] = ReportType::all();
$data['report'] = $request->session()->get('report');
return view('adc.reports.create-report', $data);
}
public function PostInitialCreateReport(Request $request){
$validatedData = $request->validate([
'fiscalyear' => 'required',
'month' => 'required',
'report_type' => 'required',
]);
if (empty($request->session()->get('report'))) {
$report = new Report();
$report->fill($validatedData);
$request->session()->put('report', $report);
} else {
$report = $request->session()->get('report');
$report->fill($validatedData);
$report->session()->put('report', $report);
}
return redirect()->route('adc.create.rent.certificate');
}
public function CreateRentCertificateReport(Request $request)
{
$data['report'] = $request->session()->get('report');
$data['reports'] = Report::distric()->status(1)->get();
return view('adc.reports.start-create-report', $data);
}
public function PostCreateRentCertificateReport(Request $request)
{
$report = $request->session()->get('report');
$request->session()->put('report', $report);
return redirect()->route('adc.preview.rent.certificate.report');
}
public function PreviewRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return view('adc.reports.preview-rent-certificate-report', compact('report', $report));
}
public function PostPreviewRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return redirect()->route('adc.save.rent.certificate.report');
}
public function SaveRentCertificateReport(Request $request){
$report = $request->session()->get('report');
return view('adc.reports.save-rent-certificate-report', compact('report', $report));
}
public function PostSaveRentCertificateReport(Request $request)
{
$report = $request->session()->get('report');
$reports = new Report;
$reports->column_one = $report->sum('column_one');
$reports->column_two = $report->sum('column_two');
$reports->fiscal_year = $report->fiscalyear;
$reports->month = $report->month;
$reports->report_type = $report->report_type;
$reports->save();
$notification = array(
'message' => 'Report Created Successfully',
'alert-type' => 'success'
);
return redirect()->route('adc.pending.report')->with($notification);
}
Route
Route::get('/initial/create/report', [AdcController::class,'InitialCreateReport'])->name('inital.create.report');
Route::post('/initial/create/report', [AdcController::class,'PostInitialCreateReport'])->name('inital.create.report.post');
Route::get('/create/rent/certificate/report', [AdcController::class, 'CreateRentCertificateReport'])->name('create.rent.certificate');
Route::post('/create/rent/certificate/report', [AdcController::class, 'PostCreateRentCertificateReport'])->name('create.rent.certificate.report.post');
Route::get('/preview/rent/certificate/report', [AdcController::class, 'PreviewRentCertificateReport'])->name('preview.rent.certificate.report');
Route::post('/preview/rent/certificate/report', [AdcController::class, 'PostPreviewRentCertificateReport'])->name('preview.rent.certificate.report.post');
Route::get('/save/rent/certificate/report', [AdcController::class, 'SaveRentCertificateReport'])->name('save.rent.certificate.report');
Route::post('/save/rent/certificate/report', [AdcController::class, 'PostSaveRentCertificateReport'])->name('save.rent.certificate.report.post');

Single column not being updated in laravel 5

I am tying to update a single column of a table messages and I have the following code:
public function messageSeen(Request $request){
$data = Message::find($request->id);
$success = Message::where('id', $request->id)->update(array('is_seen' => 1));
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
I am getting the response Data not updated. If you question, does the column is_seen exists? then yes it does. Even I tried fetching the data having id $request->id, it gives the proper data. I wonder why is the data not being updated? Am I doing right thing to update column or is there an way out to update column in different way?
I tried the other way like the following:
public function messageSeen(Request $request){
$id = $request->id;
$result = Message::find($id);
dd($result->message);
$data = array();
$data['is_seen'] = 1;
$data['message'] = $result->message;
$data['user_id'] = $result->user_id;
$data['conversation_id'] = $result->conversation_id;
$this->messages->fill($data);
$success = $this->messages->save();
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
But here I am getting unexpected thing with this method. Here I am being able to do dd($result) and being able to get data like this:
#attributes: array:9 [
"id" => 22
"message" => "How are you?\r\n"
"is_seen" => 0
"deleted_from_sender" => 0
"deleted_from_receiver" => 0
"user_id" => 2
"conversation_id" => 1
"created_at" => "2019-09-29 03:42:39"
"updated_at" => "2019-09-29 03:42:39"
]
however, if I tried to do dd($result->message) then I get null! What am I doing wrong?
I tried the following code:
public function messageSeen(Request $request){
$id = $request->id;
$result = Message::find($id);
$data = array();
$data['is_seen'] = 1;
$data['message'] = $result[0]['message'];
$data['user_id'] = $result[0]['user_id'];
$data['conversation_id'] = $result[0]['conversation_id'];
$this->messages->fill($data);
$success = $this->messages->save();
if($success){
return response()->json(['status'=>'success'], 200);
} else {
return response()->json(['status'=>'Data not updated'], 404);
}
}
and it worked but instead of updating it is adding new column when the message is seen. But first I don't understand why do I have to do $result[0]['key'] in the first place.
You need to specify which fields in your table can be mass assigned, by adding or updating the $fillable property of your model:
protected $fillable = [..., 'is_seen', 'message', ...];
This is required for the create() and update() methods, as those accept "mass" variables in the array you pass in. Whereas with save() you have to manually, explicitly, assign the properties on the model, so there is no risk of accidentally saving something you didn't mean to. And this is exactly the behaviour you are seeing - update() is not working, but save() is.
You should try this
public function messageSeen(Request $request) {
$input = Request::all();
$data = Message::find($input['id']);
if (!empty($data)) {
$update = array();
$update['is_seen'] = 1;
$success = Message::where('id', $input['id'])->update($update);
if ($success) {
return response()->json(['status' => 'success'], 200);
} else {
return response()->json(['status' => 'Something went wrong'], 400);
}
} else {
return response()->json(['status' => 'Data not updated'], 404);
}
}
Value depends on data type of is_seen are string or integer

updateExistingPivot() not working

I'm trying to update a pivot table like this:
public function updatePermission($id, $permissionId)
{
$permissionValue = Input::get('value');
$user = User::find($id);
$perms = ['value' => $permissionValue];
$user->permissions()->updateExistingPivot($permissionId, $perms);
}
This pivot has been previously created with:
public function attachPermission($id)
{
$permissionId = Input::get('id');
$permissionValue = Input::get('value');
$user = User::find($id);
if (!$user->permissions->contains($permissionId)) {
$user->attachPermissionById($permissionId);
$perms = ['value' => $permissionValue];
$user->permissions()->updateExistingPivot($permissionId, $perms);
} else {
return Response::json(array('error' => 'Permission ' . $permissionId . ' is alreay set for user ' . $user->id));
}
return Response::json(array('role' => User::with(['roles.permissions', 'permissions', 'students'])->find($user->id)));
}
When the updatePermission() method is hit, it passes fine, but it doesn't update the pivot table with the new value. What am I doing wrong here?
I won't tell you why it doesn't work, but I suggest you do this:
public function attachPermission($id)
{
$permissionId = Input::get('id');
$value = Input::get('value');
$user = User::find($id);
$sync = $user->permissions()->sync([$permissionId => compact('value')], false);
return (in_array($permissionId, $sync['updated']))
? Response::json(...) // permission updated
: Response::json(...); // permission added
}
It will add or update new permission for you.

Laravel - update one to one field

I have an update post form, where I need to update the name of the post in posts table and the associated text within the text table. I can't seem to get it to work at all.
Model - Post.php
public function text()
{
return $this->hasOne('Text');
}
Model - Text.php
public function post()
{
return $this->belongsTo('Post');
}
Controller - PostController.php
public function updateQuestionForm($id)
{
$post = Post::find($id);
$input = Input::all();
$rules = array(
'text' => 'required',
);
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::back()->withErrors($validation)->withInput();
} else {
$post->title = Input::get('title');
$post->save();
$text = $post->text();
$text->text = Input::get('text');
$post->text()->save($text);
$message = "Post updated";
return Redirect::to('question/'.$post->id.'/'.$post->slug.'/')->with('message', $message);
}
}

Resources