Laravel 7 - How to display properly the old input/s? - php

I am trying to display the old/previous inputs when its validation failed before submitting the form inputs/values to Controller's validation but it only redirects back to the page with all input fields in form is empty or not showing the previous inputs.
Here's my controller code inside store function (SaleController):
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'invoice_no' => 'required|unique:sales_h|max:255',
]);
if($validator->fails()){
//dd($validator);
Toastr::warning('Invoice No. cannot be repeated or blank.', 'Warning');
return redirect()->back()->withInput($request->all);
}
/* ...... */
}
Here's the snippet source code for my view blade file (create.blade.php):
<form class="form-horizontal" method = "POST" action = "{{ route('sales.store') }}">
#csrf
<div class="card-body">
#if ($errors->any())
<div class="alert alert-danger">
<ul class="mb-0">
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="form-group row">
<div class="col-md-12">
<div class="alert alert-info alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h5><i class="icon fas fa-info" d></i> Info!</h5>
A sales order is a document generated by the seller upon receiving a
purchase order from a <strong>buyer/customer</strong> specifying the details about the product or service
along with price, quantity, buyer details.
</div>
<strong><font color="red">*</font> Indicates required fields.</strong>
</div>
<div class="col-md-4">
<label for="date" class="col-sm-6 col-form-label">Date <font color="red">*</font></label>
<div class="input-group mb-2 {{$errors->has('date') ? 'has-error' : ''}}" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-calendar-alt"></i></span>
</div>
<input type="text"
class="form-control"
id="date"
name = "date"
autocomplete="off"
value="{{ old('date') }}"
required>
</div>
</div>
<div class="col-md-4">
<label for="invoice_no" class="col-sm-6 col-form-label">Invoice No. <font color="red">*</font></label>
<div class="input-group mb-2">
<div class="input-group-prepend {{$errors->has('invoice_no') ? 'has-error' : ''}}">
<span class="input-group-text"><i class="fas fa-hashtag"></i></span>
</div>
<input type="text"
class="form-control"
id="invoice_no"
name = "invoice_no"
maxlength = "15"
value="{{ old('invoice_no') }}"
onkeyup="this.value=this.value.replace(/[^\d]/,'')"
required>
</div>
</div>
<div class="col-md-4">
<label for="shop_name" class="col-sm-6 col-form-label">Customer Name <font color="red">*</font></label>
<div class="input-group mb-2">
<div class="input-group-prepend {{$errors->has('shop_name') ? 'has-error' : ''}}">
<span class="input-group-text"><i class="fas fa-hashtag"></i></span>
</div>
<input type = "text"
class="form-control"
id="shop_name"
name = "shop_name"
placeholder = "Customer Name"
autocomplete = "on"
value="{{ old('shop_name') }}"
required>
</div>
</div>
</div>
</div>
<div class = "form-group row">
<div class="col-md-12">
<label for = "info" class = "col-md-4 col-form-label"><strong><i class="fas fa-info-circle"></i></strong> Sales Order Information</label>
<div class = "col-sm-12 {{$errors->has('product_information') ? 'has-error' : ''}}">
<textarea name = "product_information"
class = "form-control"
rows = "4"
value="{{ old('product_information') }}"
></textarea>
</div>
</div>
</div>
<div class = "col-md-12 field-wrapper">
<div class = "form-group row">
<div class="col-md-12">
<label for="id_raw_product" class="col-sm-4 col-form-label">Product Name <font color="red">*</font></label>
</div>
<div class="col-sm-3">
<input type="hidden" readonly = "true" class="form-control" id="id_raw_product_1" name = "id_raw_product[]" placeholder = "Product Name" required>
<input type="text"
readonly = "true"
class="form-control"
id="name_raw_product_1"
name = "name_raw_product[]"
value="{{ old('id_raw_product_1') }}"
placeholder = "Product Name">
</div>
<div class="col-sm-2">
<a href = "/transaction/sales/product/popup_media/1"
class = "btn btn-info"
title = "Product"
data-toggle = "modal"
data-target = "#modal-default">Product</a>
</div>
<div class="col-sm-3">
<input type="number"
class="form-control"
id="price_1"
name = "price[]"
value="{{ old('price_1') }}"
placeholder = "Price"
onkeyup="this.value=this.value.replace(/[^\d]/,'')" required>
</div>
<div class="col-sm-2">
<input type="number"
class="form-control"
id="total_1"
name = "total[]"
value="{{ old('total_1') }}"
placeholder = "Quantity"
onkeyup="this.value=this.value.replace(/[^\d]/,'')" required>
</div>
<div class = "col-sm-2">
<i class = "fas fa-plus"></i>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-default float-right" name = "submit_create" id = "submit_create">Submit</button>
</div>
<!-- /.card-footer -->
</form>

Write your controller code like this -
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'invoice_no' => 'required|unique:sales_h|max:255',
]);
if($validator->fails()){
return redirect()->back()->withInput()->withErrors($validator->messages()->all());
}
}
and in blade file add this code -
#if ($errors->any())
<div class="alert alert-danger">
<ul class="mb-0">
#foreach ($errors->all(':message') as $input_error)
<li>{{ $input_error }}</li>
#endforeach
</ul>
</div>
#endif

Related

Laravel 8 - Old inputs and validation error messages are not working

I am trying to display the error div below a certain field if the validation for that input failed along with the previous input on the designated field.
Here's my progress so far:
in my controller file inside the store function (UserController > store):
public function store(Request $request)
{
$validationRules = array(
'first_name' => 'required|min:2|max:150',
'last_name' => 'required|min:2|max:150',
'gender' => 'required',
'birthdate' => 'required',
'user_contact' => 'required|min:10|max:20',
'email' => 'required|unique:users|max:150'
);
$validator = Validator::make($request->all(), $validationRules);
if($validator->fails()){
//dd($validator)
return redirect(route('user.create'))->withInput()->withErrors($validator);
}
.....
When I try to print $validator using dd() it does not have any problem and it contains the validation error messages, all inputs and validation rules.
Here's my snippet code in the create.blade.php (view):
<form class="form-horizontal" method = "POST" action = "{{ route('user.store') }}">
#csrf
<div class="form-group row">
<div class="col-md-12">
<strong><font color="red">*</font> Indicates required fields.</strong>
</div>
<div class="col-md-4">
<label for="u_fname" class="col-sm-6 col-form-label">First Name <font color="red">*</font></label>
<div class="input-group mb-2 {{$errors->has('u_fname') ? 'has-error' : ''}}" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-user" aria-hidden="true"></i></span>
</div>
<input type="text"
class="form-control"
id="first_name"
name = "first_name"
value="{{ old('first_name') }}"
minlength="2"
maxlength="150"
required/>
#error('first_name')
<div class="alert-danger">{{$errors->first('first_name') }} </div>
#enderror
</div>
</div>
<div class="col-md-4">
<label for="u_lname" class="col-sm-6 col-form-label">Last Name <font color="red">*</font></label>
<div class="input-group mb-2 {{$errors->has('u_lname') ? 'has-error' : ''}}" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-user" aria-hidden="true"></i></span>
</div>
<input type="text"
class="form-control"
id="last_name"
name = "last_name"
value="{{ old('last_name') }}"
minlength="2"
maxlength="150"
required/>
#error('last_name')
<div class="alert-danger">{{$errors->first('last_name') }} </div>
#enderror
</div>
</div>
<div class="col-md-4">
<label for="u_gender" class="col-sm-6 col-form-label">Gender <font color="red">*</font></label>
<div class="input-group mb-2 {{$errors->has('u_gender') ? 'has-error' : ''}}" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-venus-mars"></i></span>
</div>
<select class = "form-control" id = "gender" name = "gender" required>
<option value = "M">Male</option>
<option value = "F">Female</option>
</select>
#error('gender')
<div class="alert-danger">{{$errors->first('gender') }} </div>
#enderror
</div>
</div>
<div class="col-md-4">
<label for="u_birthdate" class="col-sm-6 col-form-label">Birth Date <font color="red">*</font></label>
<div class="input-group mb-2 {{$errors->has('u_birthdate') ? 'has-error' : ''}}" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-calendar-alt"></i></span>
</div>
<input type="text"
class="form-control"
id="birthdate"
name = "birthdate"
value="{{ old('birthdate') }}"
required/>
<div class="alert-danger">{{$errors->first('birthdate') }} </div>
</div>
</div>
<div class="col-md-4">
<label for="u_contact" class="col-sm-6 col-form-label">Contact Number <font color="red">*</font></label>
<div class="input-group mb-2 {{$errors->has('u_contact') ? 'has-error' : ''}}" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-phone"></i></span>
</div>
<input type="text"
class="form-control"
id="user_contact"
name = "user_contact"
value="{{ old('user_contact') }}"
onkeyup="this.value=this.value.replace(/[^\d]/,'')"
minlength="10"
maxlength="20"
required/>
#error('user_contact')
<div class="alert-danger">{{$errors->first('user_contact') }} </div>
#enderror
</div>
</div>
<div class="col-md-4">
<label for="u_email" class="col-sm-6 col-form-label">E-Mail Address<font color="red">*</font></label>
<div class="input-group mb-2 {{$errors->has('u_email') ? 'has-error' : ''}}" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-at"></i></span>
</div>
<input type="email"
class="form-control"
id="email"
name = "email"
value="{{ old('email') }}"
minlength="10"
maxlength="150"
required/>
#error('email')
<div class="alert-danger">{{$errors->first('email') }} </div>
#enderror
</div>
</div>
<div class="col-md-4">
<label for="u_utype" class="col-sm-6 col-form-label">User Type <font color="red">*</font></label>
<div class="input-group mb-2 {{$errors->has('u_utype') ? 'has-error' : ''}}" >
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user-cog"></i></span>
</div>
<select class = "form-control" id = "u_type_input" name = "u_type_input" required>
<option value = "E">Employee</option>
<option value = "A">Administrator</option>
</select>
#error('u_type_input')
<div class="alert-danger">{{$errors->first('u_type_input') }} </div>
#enderror
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-default float-right" name = "submit_create" id = "submit_create">Submit</button>
</div>
</form>
Notice that I removed the autocomplete=off because I read some posts that this causes the problem but still doesn't work in my case.
I've been reading all stackoverflow posts related on my problem but most of the scenario problem occured on Laravel 5 and I use the current latest version of Laravel Framework which is Laravel 8.
What seems to be the cause of the problem? and how should I retain the
old/previous inputs and show the error messages after the failed
validation? I suspect that the cause of the problem lies on the blade
file or related to the resources like bootstrap.
you can try this to redirect
if ($validator->fails())
{
return redirect()->back()->withErrors($validator->errors());
}
and while showing into the blade file try this one
#error('user_contact')
<div style="color: red;">{{ $message }}</div>
#enderror

How to display error validation on specific modal for updating data with laravel 7?

I try to update the data of products on modal bootstrap, but every product has its own update form.
But error validation displays on all modals update of others products (same fields).
Can I use named message bags for this problem?
I have one form of updating for all products.
My view:
#foreach($prdCatg as $prd)
<div id="modifier" class="modal fade" role="dialog" tabindex="-1" >
<div class=" modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title titre">Modifier le produit</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST" action="{{ route('com.produit.update') }}" enctype = "multipart/form-data">
#csrf
#method('PATCH')
<div class="modal-body row justify-content-center">
<input type="hidden" id="id_prd" name="id_produit" value="">
<div class="col-lg-6">
<div class="form-group col-lg-12">
<label for="Nom" class="col-form-label">Nom du produit :</label>
<input type="text" name="Nom" id="nom" class="shadow form-control #error ('Nom') is-invalid #enderror" value="{{ old('Nom') }}">
#error('Nom')
<div class="invalid-feedback">
{{$errors->first('Nom')}}
</div>
#enderror
</div>
<div class="form-group col-lg-12">
<label class="col-form-label" for="Catégorie">Le client :</label>
<select name="Client" id="clt" class="shadow custom-select #error ('Client') is-invalid #enderror" style="color:#787878;">
#foreach($clts as $clt)
<option value="{{$clt->id_soc}}" {{$prd->soc_id == $clt->id_soc ? 'selected' : ''}}> {{$clt->nom_soc}} </option>
#endforeach
</select>
#error('Client')
<div class="invalid-feedback">
{{$errors->first('Client')}}
</div>
#enderror
</div>
<div class="form-group col-lg-12">
<label class="col-form-label" for="Catégorie">La catégorie :</label>
<select name="Catégorie" id="catg" class="shadow custom-select #error ('Catégorie') is-invalid #enderror" style="color:#787878;">
#foreach($catgs as $catg)
<option value="{{ $catg->id_catg }}" {{$prd->catg_id == $catg->id_catg ? 'selected' : ''}}> {{ $catg->nom_catg }} </option>
#endforeach
</select>
#error('Catégorie')
<div class="invalid-feedback">
{{$errors->first('Catégorie')}}
</div>
#enderror
</div>
</div>
<div class="col-lg-6">
<div class="form-group col-lg-12">
<label for="Prix" class="col-form-label">Prix unitaire :</label>
<input type="text" name="Prix" id="prix" class="shadow form-control #error ('Prix') is-invalid #enderror" value="{{ old('Prix')}}">
#error('Prix')
<div class="invalid-feedback">
{{$errors->first('Prix')}}
</div>
#enderror
</div>
<div class="form-group col-lg-12">
<label for="Description" class="col-form-label">Description :</label>
<textarea type="text" name="Description" id="descp" class="shadow form-control #error ('Description') is-invalid #enderror" rows="2" value="{{ old('Description')}}">
</textarea>
#error('Description')
<div class="invalid-feedback">
{{$errors->first('Description')}}
</div>
#enderror
</div>
<div class="form-group col-lg-12">
<label for="Logo" class="col-form-label">Logo du produit :</label>
<div class="custom-file shadow">
<input type="file" id="logo" name="Logo" class="custom-file-input #error ('Logo') is-invalid #enderror">
<label class="custom-file-label" for="lm" style="color:#787878">Votre fichier.</label>
<small>Formats acceptés : .jpg,.jpeg,.gif,.png</small>
<small> Tailles acceptées : hauteur_max:200px, largeur_max:200px </small>
#error('Logo')
<div class="invalid-feedback">
{{$errors->first('Logo')}}
</div>
#enderror
</div>
</div>
</div>
<div class="form-group row justify-content-center col-lg-10" style="margin-top:20px;">
<div class="">
<button type="submit" class="btn btn-primary">
Modifier
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
#endforeach
javascript:
<script type="text/javascript">
$('#modifier').on('show.bs.modal', function(event){
var button = $(event.relatedTarget)
var prd_id = button.data('prdid')
var nom = button.data('prdnom')
var clt = button.data('prdclt')
var catg = button.data('prdcatg')
var prix = button.data('prdprix')
var descp = button.data('prddescp')
var modal = $(this)
modal.find('.modal-body #id_prd').val(prd_id);
modal.find('.modal-body #nom').val(nom);
modal.find('.modal-body #clt').val(clt);
modal.find('.modal-body #catg').val(catg);
modal.find('.modal-body #prix').val(prix);
modal.find('.modal-body #descp').val(descp);
})
</script>
#if (count($errors) > 0)
<script type="text/javascript">
$( document ).ready(function() {
$('#modifier').modal('show');
});
</script>
#endif
controller :
public function update(Request $request)
{
$id_prd = $request->input('id_produit');
request()->validate([
'Nom'=>'required',
'Client' => 'required',
'Catégorie' => 'required',
'Prix' => 'required|integer|not_in:0',
'Description' => 'required|between:20,300',
'Logo' => 'sometimes|image|mimes:png,jpg,jpeg|dimensions:max_heigh=200,max_width=200',
]);
$produit = Produit::find($id_prd);
if(request()->has('Logo')){
$upload_logo = request()->file('Logo');
$logo_name = request('Nom').'.'. $upload_logo->getClientOriginalExtension();
$logo_path = public_path('/img/produit/');
$upload_logo->move($logo_path, $logo_name);
$produit ->nom_prd = $request->get('Nom');
$produit ->soc_id = $request->get('Client');
$produit ->soc_id = $request->get('Catégorie');
$produit ->prix_prd = $request->get('Prix');
$produit ->descp_prd = $request->get('Description');
$produit ->logo_prd = '/img/produit/'.$logo_name;
$produit->save();
return redirect()->back()->with('success', 'Le produit a été mis à jour, merci !');
}
$produit ->nom_prd = $request->get('Nom');
$produit ->soc_id = $request->get('Client');
$produit ->soc_id = $request->get('Catégorie');
$produit ->prix_prd = $request->get('Prix');
$produit ->descp_prd = $request->get('Description');
$produit->save();
return redirect()->back()->with('success', 'Le produit a été mis à jour, merci !');
}
public function destroy(Request $request){
$prd_id = $request->input('id_produit');
$prd = Produit::where('id_prd',$prd_id);
$prd -> delete();
return redirect()->back()->with('success', 'Le produit a été supprimé.');
}
I would suggest to use one <form> and use indexed input names. If I'm correct you can use attribute.x (like Client.8) to get the error message.
<form>
#csrf
#foreach ($prdCatg as $prd)
<input name="Client[{{ $prd->id }}]" value="{{ $prd->value }}">
#error('Client.' . $prd->id)
<div class="invalid-feedback">
{{ $message }} <!-- you can use this in L7 or you can still use $errors->first('Client.' . $prd->id) -->
</div>
#enderror
#endforeach
</form>
This would at least solve one problem. But make sure you don't have too much models loaded, because of performance ;)

Laravel - Database store function not working

I am having trouble when inputting data and figuring out why my data is not being stored into the database. I have tried to use the resources route and my custom route code, but it seems still nothing works. Clicking submit just seems to refresh the page with no errors to show
And here is my form :
<div class="container">
<div class="row">
<div class="col-md-12">
<nav class="navbar navbar-expand-sm navbar-dark primary justify-content-between">
<div class="navbar-brand text-dark">Create a Story</div>
</nav>
<hr class="mt-3">
<form action="{{route('story.store')}}" method="post">
#csrf
<div class="row">
<div class="col col-lg-6">
<div class="form-group my-3">
<label for="title">Title</label><br>
<input type="text" name="title" id="title" class="w-100 form-control{{ $errors->has('title') ? ' is-invalid' : '' }}" value="{{ old('title') }}" required>
#if ($errors->has('title'))
<span class="invalid-feedback" role="alert"><strong>{{ $errors->first('title') }}</strong></span>
#endif
</div>
</div>
<div class="col col-lg-6">
<div class="form-group my-3">
<label for="category">Category</label><br>
<select name="category" id="category" class="w-100 form-control{{ $errors->has('category') ? ' is-invalid' : '' }}" value="{{ old('category') }}" required>
<option value="Active" selected>Select Category</option>
#foreach ($category as $item)
<option value="{{$item->id}}">{{$item->nama}}</option>
#endforeach
</select>
#if ($errors->has('category'))
<span class="invalid-feedback" role="alert"><strong>{{ $errors->first('category') }}</strong></span>
#endif
</div>
</div>
<div class="col col-lg-6">
<div class="form-group my-3">
<label for="thumbnail">Story Thumbnail <span class="text-muted">(Recomended size is 650 x 350 pixel)</span></label><br>
<input type="file" name="thumbnail" id="thumbnail">
#if ($errors->has('thumbnail'))
<span class="invalid-feedback" role="alert"><strong>{{ $errors->first('thumbnail') }}</strong></span>
#endif
</div>
</div>
<div class="col col-lg-12">
<div class="form-group mt-4">
<textarea id="text-content" name="content" class="w-100 form-control{{$errors->has('content') ? ' is-invalid' : ''}}" id="content" rows="3" value="{{old('content')}}"></textarea>
#if ($errors->has('content'))
<span class="invalid-feedback" role="alert"><strong>{{ $errors->first('content') }}</strong></span>
#endif
</div>
</div>
</div>
<div class="modal-footer pb-0">
<div class="float-right">
<button type="submit" class="btn btn-outline-primary btn-md">Publish Story</button>
</div>
</div>
</form>
</div>
</div>
The store function in controller :
public function store(Request $request)
{
$user = Auth::user();
$request->validate([
'title' => 'required|string',
'category' => 'required',
'thumbnail' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'content' => 'required',
]);
$thumbnailName = time().'.'.request()->thumbnail->getClientOriginalExtension();
$post = new Post;
$post->title = request('title');
$post->category_id = request('category');
$post->thumbnail = request('thumbnail');
$post->content = request('content');
$post->title = request('title');
$post->date = date('d-m-Y');
$post->author_id = $user->id;
$post->save();
$request->thumbnail->move(asset('storage/uploads'), $thumbnailName);
return redirect('me/stories')->with('Succes', 'Story has been published')->with('thumbnail', $thumbnailName);
}
And this is the routes:
Route::get('me/stories', 'PostController#index')->name('story');
Route::get('me/stories/create', 'PostController#create')->name('story.create');
Route::post('me/stories/store', 'PostController#store')->name('story.store');
Route::post('ck/image_upload', 'PostController#imageUpload')->name('ck.upload');
I'm not getting any error messages at all, it's just that the submission button does nothing. Thanks a lot!
Clicking submit just seems to refresh the page with no errors to show
Your Validator is doing a return to last page with the errors.
Add this snippet of code to your blade
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Also, inspect the page before submitting and go to the network tab (check preserve log at the top) and proceed with the submission, you will get more details of what happened.

How to show error and success message in laravel using version 5.2

I want to display my success and error message on my popup model i have setup session message for success and danger on my view but its redirecting me back to my page as there is condition in my controller but i want to show these success and error messages on my model:
My popup form:
<div class="modal-body">
<form role="form" id="passwordchangeform" class="common_form_style popup_form" method="POST" novalidate action="{{ url('/changepassword') }}">
<div class="row">
<div class="col-md-8 col-md-offset-2">
{{ csrf_field() }}
<div class="form-group">
<label for="password" style="width:100%">Původní heslo </label>
<input id="password" type="password" class="form-control" name="password">
<span toggle="#password-field" class="fa fa-fw fa-eye field-icon toggle-password"></span>
</div>
<div class="form-group">
<label for="new_password" style="width:100%">NovÄ› heslo</label>
<input id="new_password" type="password" class="form-control" name="new_password">
<span toggle="#password-field" class="fa fa-fw fa-eye field-icon toggle-password"></span>
<span class="help-block" style="color:#737373;font-size:14px;float:right;margin-right: 30px;font-weight: 100 !important;">MinimálnÄ› 8 znaků, jedno velké a malé písmeno a Äíslo</span>
</div>
<div class="form-group">
<label for="heslo znovu">Potvrzení heslo</label>
<input id="password_confirmation" type="password" class="form-control" name="password_confirmation">
<span toggle="#password-field" class="fa fa-fw fa-eye field-icon toggle-password"></span>
</div>
<div class="submit-btn text-center">
<button type="submit" class="btn btn-default chci" style="background:#e94549;">Uložit</button>
</div>
<div style="margin-top:10px;" id="success-messages"></div>
</div>
<div class="col-md-12 pull-right"></div>
</div>
</form>
</div>
and my controller:
$current_password = $user->password;
if(md5($request_data['password']) == $current_password) {
$user_id = $user->id;
$obj_user = User::find($user_id);
$obj_user->password = md5($request_data['new_password']);;
$obj_user->save();
$data = array('info_success' => "Password has been changed!", 'tab' => '');
return redirect('mujucet')->with($data);
} else {
$error = array('non-success' => "Heslo, které jste zadali, je neplatné.", 'tab' => '');
return redirect('mujucet')->with($error);
}
I want to show messages on my pop how i can do that
Your help need here!
The problem seems to be that nowhere within your view you're using the variables you're sending from the controller. Add this and it should function as expected:
//Assuming blade & bootstrap in this case:
#if(isset($info_success ))
<div class="col-xs-12">
<div class="alert alert-success">
<b>Success:</b>{{ $info_success }}
</div>
</div>
#elseif(isset($non_success))
<div class="col-xs-12">
<div class="alert alert-danger">
<b>Error:</b>{{ $non_success }}
</div>
</div>
#endif

How to update a database table in laravel 5.2

i created one project in laravel 5.2. In that "myform.blade.php" page , created form for register the user. after registration it will show the current user in table format("index.blade.php"). There i given two dynamic button like the drop inside the table. One for Edit and other for Edit/View. When i click on delete button it will delete the corresponding row from the database by taken Primary key(employeeID) as reference id, it's working properly. if i click on Edit/View button it will redirect to "edit.blade.php". There i created same form as in myform.blade.php. If we want to edit the details we can edit from there. I can able to fetch the data from database to the form that i created in the "edit.blade.php". But i don't know how to update the data from their without inserting the same data again(It is not possible, because it will create Integrity constraint violation by trying to insert duplicate primary key. Can any one please tell me how to do updation. Replies are appreciable.
"myform.blade.php" is
#extends('app')
#section('content')
<div class="templatemo-content-wrapper">
<div class="container">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">Employee Form</li>
</ol>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-success">
<div class="panel-heading">Employee Form</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/myform/') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">Employee ID</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeID" value="{{ old('employeeID') }}" placeholder="Enter employee ID">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E_number</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeNo" value="{{ old('employeeNo') }}" placeholder="Enter employee number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="Cname" value="{{ old('Cname') }}" placeholder="Enter Contact Name">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">DOB</label>
<div class="col-md-6">
<input type="date" class="form-control" name="dob" value="{{ old('dob') }}" placeholder="Enter date of birth">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Contact Phone</label>
<div class="col-md-6">
<input type="text" class="form-control" name="phoneNumber" value="{{ old('phoneNumber') }}" placeholder="Enter Mobile Number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Address</label>
<div class="col-md-6">
<input type="text" class="form-control" name="address" value="{{ old('address') }}" placeholder="Enter Address">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-warning">
Save
</button>
</div>
</div>
view Data
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
"index.blade.php" is
#extends('app')
#section('content')
<div class="templatemo-content-wrapper" xmlns="http://www.w3.org/1999/html">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">user information</li>
</ol>
<div class="templatemo-content">
<h1>View/Edit user information</h1>
<div>
<div>
<div>
<table id="example" class="table table-striped table-hover table-bordered" bgcolor="#fff8dc">
<thead>
<tr>
<th>Employee ID</th>
<th>Employee No</th>
<th>Contact Name</th>
<th>Date of birth</th>
<th>Mobile number</th>
<th>address</th>
</tr>
</thead>
<tbody>
{{--{{ UserController::getIndex() }}--}}
#foreach($employer as $emp)
<tr>
<td>{{ $emp->employeeID }}</td>
<td>{{ $emp->employeeNo }}</td>
<td>{{ $emp->Cname }}</td>
<td>{{ $emp->dob }}</td>
<td>{{ $emp->phoneNumber }}</td>
<td>{{ $emp->address }}</td>
<td>
{{--#if ( in_array($nam->isActive, array('Yes','No')) )--}}
<div class="btn-group">
<button type="button" class="btn btn-info">Action</button>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
{{--#if ($nam->isActive == 'Yes')--}}
<li data-toggle="modal" data-target="#acceptModal" data-bookingid="{{ $emp->employeeID }}">View/ Edit
</li>
{{--#endif--}}
<li>Delete</li>
</ul>
</div>
{{--#endif--}}
</td>
</tr>
#endforeach
</tbody>
</table>
{{$employer->links()}}
</div>
</div>
</div>
</div>
</div>
{{-- <input type="submit" id="add" name="add" value="Edit" class="button">--}}
</br>
<h4>Create a new Employee</h4>
{{--<form class="templatemo-preferences-form" role="form" method="POST" action="{{ action('UserController#save') }}">--}}
{{--<input type="hidden" name="_token" value="{{ csrf_token() }}">--}}
<form role="form" method="POST" action="{{ url('myform/index') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="row">
<div class="col-md-6 margin-bottom-15">
<input type="text" class="form-control" name="employeeID" value="{{ old('employeeID') }}" placeholder="Enter employee ID">
</div>
<div class="row templatemo-form-buttons">
<div class="submit-button">
<button type="submit" class="btn btn-primary">New</button>
</div>
</div>
</div>
</form>
{{--</form>--}}
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
#endsection
"edit.blade.php" is
#extends('app')
#section('content')
<div class="templatemo-content-wrapper">
<div class="container">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">Employee Form</li>
</ol>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-success">
<div class="panel-heading">Employee Form</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/myform/') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
#foreach($user as $use)
<div class="form-group">
<label class="col-md-4 control-label">Employee ID</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeID" value="{{ $use->employeeID }}" placeholder="Enter employee ID">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E_number</label>
<div class="col-md-6">
<input type="text" class="form-control" name="employeeNo" value="{{ $use->employeeNo}}" placeholder="Enter employee number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="Cname" value="{{ $use->Cname }}" placeholder="Enter Contact Name">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">DOB</label>
<div class="col-md-6">
<input type="date" class="form-control" name="dob" value="{{ $use->dob }}" placeholder="Enter date of birth">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Contact Phone</label>
<div class="col-md-6">
<input type="text" class="form-control" name="phoneNumber" value="{{ $use->phoneNumber }}" placeholder="Enter Mobile Number">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Address</label>
<div class="col-md-6">
<input type="text" class="form-control" name="address" value="{{ $use->address }}" placeholder="Enter Address">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-warning"><a href="{{ url('myform/update/'.$use->employeeID) }}">
Update</a>
</button>
</div>
</div>
{{-- <input type="button" id="add" name="add" value="View data" class="button">--}}
#endforeach
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
"myformController.php" is
<?php
namespace App\Http\Controllers;
use App\myform;
use Mail;
use Illuminate\Support\Facades\DB;
use Faker\Provider\DateTime;
use App\User;
use App\Http\Requests\createUserRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Symfony\Component\HttpFoundation\Request;
class myformController extends Controller
{
public $type = 'myform';
public function getIndex()
{
// $user = DB::table('user')->get();
$employer = DB::table('employee')->simplePaginate(5);
return view('myform.index')->with('employer',$employer);
}
public function formInsert()
{
$postform = Input::all();
//insert data into mysql table
$data = array('employeeID'=> $postform['employeeID'],
'employeeNo'=> $postform['employeeNo'],
'Cname'=> $postform['Cname'],
'dob'=> $postform['dob'],
'phoneNumber'=> $postform['phoneNumber'],
'address'=> $postform['address'],
);
// echo print_r($data);
$ck = 0;
$ck = DB::table('employee')->Insert($data);
//echo "Record Added Successfully!";
$employer = DB::table('employee')->simplePaginate(10);
return view('myform.index')->with('employer',$employer);
}
public function delete($id)
{
DB::table('employee')->where('employeeID', '=', $id)->delete();
$employer = DB::table('employee')->simplePaginate(10);
return view('myform.index')->with('employer', $employer);
}
public function formIDinsert()
{
$postform = Input::all();
//insert data into mysql table
$data = array('employeeID'=> $postform['employeeID'],
);
// echo print_r($data);
$ck = 0;
$ck = DB::table('employee')->Insert($data);
//echo "Record Added Successfully!";
$employer = DB::table('employee')->simplePaginate(10);
return view('myform.index')->with('employer',$employer);
}
public function edit($id)
{
try {
//Find the user object from model if it exists
$user=DB::table('employee')->where('employeeID', '=', $id)->get();
//$user = User::findOrFail($id);
//Redirect to edit user form with the user info found above.
return view('myform.edit')->with ('user', $user);
//return view('myform.edit')->with('user', myform::find($id));
} catch (ModelNotFoundException $err) {
//redirect to your error page
}
}
// Update user
public function update(Request $request, $id)
{
try{
//Find the user object from model if it exists
$user= myform::findOrFail($id);
DB::table('employee')
->where('employeeID', $id)
->update(['employeeNo' =>$request['employeeNo'],
'Cname'=>$request['Cname'],
'phoneNumber'=>$request['phoneNumber'],
'address'=>$request['address']
]);
//Set user object attributes
//the $request index should match your form field ids!!!!!
//you can exclude any field you want.
// $user->employeeNo = $request['employeeNo'];
// $user->Cname = $request['Cname'];
// $user->phoneNumber = $request['phoneNumber'];
// $user->address = $request['address'];
//Save/update user.
$user->save();
return view('myform.index')->with('user', $user);
//redirect to somewhere
}
catch(ModelNotFoundException $err){
//Show error page
}
}
}
model "myform.php" is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class myform extends Model
{
protected $table = 'employee';
//protected $primaryKey = 'employeeID';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'employeeID',
'employeeNo',
'Cname',
'dob',
'phoneNumber',
'address',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Routes.php is
Route::any('myform', function()
{
return view('myform/myform');
});
Route::any('myform/myform', 'myformController#formInsert');
Route::any('myform/index', 'myformController#getIndex');
//to show edit form and fetch passed user id info from db
Route::get('myform/edit/{id}', 'myformController#edit');
//to get the edited info and save it to db
Route::get('myform/update/{id}', 'UserController#update');
Route::any('myform/index', 'myformController#formIDinsert');
Route::any('myform/delete/{id}', 'myformController#delete');
You wanna change this in your route:
Route::get('myform/update/{id}', 'UserController#update');
to
//Because the data in your form is transferred/submitted by post request
Route::post('myform/update/{id}', 'UserController#update');
then change your update function to this
// Update user
public function update(Request $request, $id)
{
try{
//Find the user object from model if it exists
$user= myform::findOrFail($id);
//$request contain your post data sent from your edit from
//$user is an object which contains the column names of your table
//Set user object attributes
$user->employeeNo = $request['employeeNo'];
$user->Cname = $request['Cname'];
$user->dob = $request['dob'];
$user->phoneNumber = $request['phoneNumber'];
$user->address = $request['address'];
// Save/update user.
// This will will update your the row in ur db.
$user->save();
return view('myform.index')->with('user', $user);
}
catch(ModelNotFoundException $err){
//Show error page
}
}
If you have any question or need clarification you are most welcome to ask :)
Update in your edit view
change this
<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/myform/') }}">
to
<form class="form-horizontal" role="form" method="POST" action="{{ url('myform/update/').$user->employeeID}}">
change $user->employeeID to whatever is your primary key.
Also change this
<button type="submit" class="btn btn-warning"><a href="{{ url('myform/update/'.$use->employeeID) }}">
Update</a>
</button>
to this
<button type="submit" class="btn btn-warning">Update</button>
Aso you didn't fix your route as I mentioned earlier in this answer.

Categories