How to show an old value / query field from database in mysql, and edit value in Laravel. I'm using Laravel 9x and PHP 8x
Controller.php :
public function edit(Business $business)
{
return view('dashboard.bisnis.edit', [
'item' => $business
]);
}
public function update(Request $request, Business $business)
{
$rules = [
'deskripsi' => 'required|max:255',
'pemilik' => 'required|max:255'
];
$validateData = $request->validate($rules);
Business::where('id', $business->id)->update($validateData);
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
}
Blade.php:
@extends('dashboard.index')
@section('container')
<div >
<h1 >Edit Data Bisnis</h1>
</div>
<div >
<form method="post" action="/dashboard/bisnis/{{ $item->id }}" enctype="multipart/form-data">
@method('put')
@csrf
<div >
<label for="deskripsi" >Deskripsi</label>
<input type="text" id="deskripsi" name="deskripsi" required autofocus
value="{{ old('deskripsi', $item->deskripsi) }}">
@error('deskripsi')
<div >
{{ $message }}
</div>
@enderror
</div>
<div >
<label for="pemilik" >Pemilik</label>
<input type="text" id="pemilik" name="pemilik" required autofocus
value="{{ old('pemilik', $item->pemilik) }}">
@error('pemilik')
<div >
{{ $message }}
</div>
@enderror
</div>
<button type="submit" >Simpan Perubahan</button>
</form>
</div>
<script>
const deskripsi = document.querySelector('#deskripsi');
const pemilik = document.querySelector('#pemilik');
</script>
@endsection
Also when navigating through my menu such as Business, the sidebar seems cant to be clicked, nor use. Thank you so much
CodePudding user response:
Please try like this:
{{ old('deskripsi') ? old('deskripsi') :$item->deskripsi }}
Please replace this:
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
to
return redirect()->back()->with('success', 'Item has been updated !');
CodePudding user response:
I assume you use Laravel 9
Referring to Repopulating Forms - Validation
Controller.php:
you should use
$deskripsi = $request->old('deskripsi');
$pemilik = $request->old('pemilik');
before
$validateData = $request->validate($rules);
Blade.php:
you should use this on input
value="{{ old('deskripsi') }}"
value="{{ old('pemilik') }}"
By default old will return null if no input exists so we don't need to use nullcheck like
{{old('deskripsi') ?? ''}}
CodePudding user response:
To repopulate value using old()
in Laravel you need to return a response withInput()
. Not just response.
The return code should
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
change to this
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !')->withInput();