I have a Blade file accessed through a URL with a variable parameter. I want to check whether the input is blank with input validation and return to the same URL with a success/error message.
My blade file:
URL: http://localhost:8000/mypage?view=3
//3 is the ID used in the form below
<div>
@if(Session::has('error'))
<div class="error">
{{ Session::get('error') }}
</div>
elseif(Session::has('success'))
<div class="success">
{{ Session::get('success') }}
</div>
@endif
</div>
<form action="{{route('action')}}" method="post">
@csrf
@foreach($data as $ldata)
<label>ID
<input type="text" name="id" readonly value="{{$ldata->id}}">
<label>Status
<select id="status" name="status">
<option value='Pending'>Pending</option>
<option value='Approved'>Approved</option>
<option value='Cancelled'>Cancelled</option>
</select>
<label>Remarks
<input type="text" name="remarks">
<button>Submit</button>
</form>
Controller:
public function take_action(Request $request ){
$full_name = Auth::user()->full_name;
$id = $request->input('id');
$status = $request->input('status');
$remarks = $request->validate(['remarks' => 'required']);
}
What I want to do is check for the validation, and if it’s a success, the controller should perform an update query followed by a redirect to the same URL (URL: http://localhost:8000/mypage?view=3) with a success message or if it fails, then with the error message.
2
Answers
To achieve what you want, you can perform the validation in the controller, and then redirect back to the original URL with the appropriate success or error message. Here’s how you can modify your controller code:
This code first validates the request using the validate method, and if the validation is successful, it performs the update query. After the update query, it redirects back to the original URL with a success message.
If the validation fails, Laravel will automatically redirect back to the previous page with the validation errors. You don’t need to handle this part explicitly unless you want to customize the error messages or the behavior. The default Laravel behavior is to redirect back with the old input and error messages.