How to validate checkboxes with Laravel? - php

I am trying to validate a form in Laravel 5.3. The form has checkboxes. I need at least one checkbox to be selected for the form to be vald. This is my form
Here is my form
<div class="form-group {{ $errors->has('gender') ? 'has-error' : ''}}">
<div class="col-md-2"></div>
<div class="col-md-10">
<label for="gender_" class="checkbox-inline">
{!! Form::checkbox('gender', '', null, ['id' => 'gender_']) !!}
{{ trans('blogs.gender_') }}
</label>
<label for="gender_1" class="checkbox-inline">
{!! Form::checkbox('gender', '1', null, ['id' => 'gender_1']) !!}
{{ trans('blogs.gender_1') }}
</label>
<label for="gender_2" class="checkbox-inline">
{!! Form::checkbox('gender', '2', null, ['id' => 'gender_2']) !!}
Female
</label>
{!! $errors->first('gender', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('name') ? 'has-error' : ''}}">
{!! Form::label('name',trans('blogs.name'),['class' => 'col-md-2 control-label']) !!}
<div class="col-md-10">
{!! Form::text('name',null, ['class' => 'form-control']) !!}
{!! $errors->first('name', '<p class="help-block">:message</p>') !!}
</div>
</div>
I am using FormRequest object. Here is my rules() method
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gender' => 'required'
];
}
However, the validation fails unless I select every checkbox!
How can I correctly ensure that the validation only fails if no checkboxes is selected?

Your rules() looks correct so no require change for it. Try below:
<div class="form-group {{ $errors->has('gender') ? 'has-error' : ''}}">
<div class="col-md-2"></div>
<div class="col-md-10">
<label for="gender_0" class="checkbox-inline">
{!! Form::checkbox('gender[]', 0, null, ['id' => 'gender_0']) !!}
{{ trans('blogs.gender_') }}
</label>
<label for="gender_1" class="checkbox-inline">
{!! Form::checkbox('gender[]', 1, null, ['id' => 'gender_1']) !!}
{{ trans('blogs.gender_1') }}
</label>
<label for="gender_2" class="checkbox-inline">
{!! Form::checkbox('gender[]', 2, null, ['id' => 'gender_2']) !!}
Female
</label>
{!! $errors->first('gender', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('name') ? 'has-error' : ''}}">
{!! Form::label('name',trans('blogs.name'),['class' => 'col-md-2 control-label']) !!}
<div class="col-md-10">
{!! Form::text('name',null, ['class' => 'form-control']) !!}
{!! $errors->first('name', '<p class="help-block">:message</p>') !!}
</div>
</div>
Hope this could help you!

Related

how make modal edit with jquery in laravel?

does every use of capital, have to use a validator in the store controller? and if you don't use a validator, what's the problem?
Index.blade.php
<td>
<a href="" class="edit_real" data-toggle="modal" data-target="#edit_real-{{$spent_time->plan_id}}">
{{$spent_time->plan->user_story}}
</a>
#include('reals._form')
</td>
_form.blade.php (modal)
<div class="modal fade" id="edit_real-{{$spent_time->plan_id}}" role="dialog" >
<div class="modal-dialog modal-sm-8">
<div class="modal-content">
<div class="nav-tabs-custom">
<ul class="nav nav-tabs pull-left">
<li class="">Plan</li>
<li class="active">Real</li>
</ul>
<div class="tab-content">
<div class="chart tab-pane active" id="revenue-chart">
{!! Form::open([$spent_time, 'url' => route('real.update', $spent_time->id), 'method' => 'POST', 'role'=>'form']) !!}
{{ csrf_field() }} {{ method_field('PUT') }}
<div class="box-body">
<div class="form-group">
{!! Form::label('user_story','Today Plan *', ['class' => 'control-label', 'name'=>'user_story']) !!}</label>
{!! Form::text('user_story', old('plan_id', is_null($spent_time->plan->user_story) ? null : $spent_time->plan->user_story), ['class'=>'form-control', 'readonly' => 'true']) !!}
</div>
<div class="form-group">
{!! Form::label('daily_spent_time','Spent Time *', ['class' => 'control-label', 'name'=>'daily_spent_time']) !!}</label>
{!! Form::text('daily_spent_time', old('daily_spent_time', $spent_time->daily_spent_time ?: null), ['class'=>'form-control', 'id'=>'daily_spent_time']) !!}
</div>
<div class="form-group">
{!! Form::label('daily_percentage','% Done *', ['class' => 'control-label', 'name' => 'daily_percentage']) !!}</label>
{!! Form::text('daily_percentage', old('daily_percentage', $spent_time->daily_percentage ?: null), ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('reason','Reason', ['class' => 'control-label', 'name'=>'reason']) !!}</label>
{!! Form::textarea('reason', old('reason', $spent_time->reason ?: null), ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Save', ['class' => 'btn btn-block btn-primary btn-flat']) !!}
</div>
</div>
</div>
</div>
</div>
</div>
<script>
// jquery
$('.edit_real').on('click', function (event) {
event.preventDefault();
$('#edit_real').modal();
});
</script>
this is the resulting display
the problem faced is that it cannot save data after editing. what should be repaired?
_form.blade.php (Modal)
<div class="form-group">
{!! Form::submit('Save', ['class' => 'btn btn-block btn-primary btn-flat', 'type'=>'submit']) !!}
</div>

Insert Cart::content() into multiple Row From View Using Eloquent Laravel 5

How can I insert Multiple Row of Cart:: content() in Laravel 5.
I'm using Crinsane/LaravelShoppingcart for my cart, however, when you click on proceed to payment, I want the user to fill Customer details like (Terminal ID, sale date, and customer name. But I'm having issue with inserting Cart::(Content) into my database (I dont want to insert instance. I like to break the cart down to my database column. example, if someone pick like 2-5 items, I want it to be inserted to my db, with each item in each row. I've break the Cart::content down in my view, but I need to be able to use Laravel to insert multiple row based on the number of Items selected.
PLEASE NOTE: IF I ONLY ADD ONLY ONE ITEM TO CART, I'M ABLE TO INSERT TO DATABASE, IT'S ONLY WHEN THE ITEM IN CART IS MORE THAN ONE THAT I HAVE ISSUE WITH.
Below is my proceed.blade.php
<div class="panel-heading">Customer Detail</div>
<div class="panel-body">
#if (sizeof(Cart::content()) > 0)
{!! Form::open(['method'=>'POST', 'action'=> 'SalesController#store','files'=>true]) !!}
{!! Form::text('counter', $counter=Cart::content()->groupBy('id')->count(), ['class'=>'form-control'])!!}
#foreach (Cart::content() as $item)
<div class="form-group">
{!! Form::label('product_name', 'Product Name:') !!}
{!! Form::text('product_name', $item->name, ['class'=>'form-control'])!!} </div>
<div class="form-group">
{!! Form::label('quantity', 'Quantity:') !!}
{!! Form::text('quantity', $item->qty, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('unit_price', 'Unit Price:') !!}
{!! Form::text('unit_price', $item->price, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('rowId', 'Row ID:') !!}
{!! Form::text('rowId', $item->rowId, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('tax', 'Tax:') !!}
{!! Form::text('tax', $item->tax, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('total_price', 'Sub Total:') !!}
{!! Form::text('total_price', $item->subtotal, ['class'=>'form-control'])!!}
</div>
#endforeach
#endif
<div class="form-group">
{!! Form::label('terminal_id', 'Terminal ID:') !!}
{!! Form::text('terminal_id', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('customer_name', 'Customer Name:') !!}
{!! Form::text('customer_name', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('sale_date', 'Sale Date:') !!}
{!! Form::text('sale_date', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::submit('Check Out', ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
`
MY CONTROLLER
$counter= $request['counter'];
for ($i = 0; $i < count($counter); $i++) {
Sale::create([
'terminal_id' => $request['terminal_id'],
'customer_name' => $request['customer_name'],
'unit_price' => $request['unit_price'],
'total_price' => $request['total_price'],
'tax' => $request['tax'],
'quantity' => $request['quantity'],
'product_name' => $request['product_name'],
'sale_date' => $request['sale_date'],
'rowId' => $request['rowId']
]);
}
return redirect('shop');
}
First your fields are not arrays so with each #foreach in your view, the old value overrides.
Make your inputs to Array inputs by changing your view this way:
<div class="panel-heading">Customer Detail</div>
<div class="panel-body">
#if (sizeof(Cart::content()) > 0)
{!! Form::open(['method'=>'POST', 'action'=> 'SalesController#store','files'=>true]) !!}
{!! Form::text('counter', $counter=Cart::content()->groupBy('id')->count(), ['class'=>'form-control'])!!}
<?php $idx = 0; ?>
#foreach (Cart::content() as $item)
<div class="form-group">
{!! Form::label("product_name[$idx]", 'Product Name:') !!}
{!! Form::text("product_name[$idx]", $item->name, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("quantity[$idx]", 'Quantity:') !!}
{!! Form::text("quantity[$idx]", $item->qty, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("unit_price[idx]", 'Unit Price:') !!}
{!! Form::text("unit_price[idx]", $item->price, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("rowId[$idx]", 'Row ID:') !!}
{!! Form::text("rowId[$idx]", $item->rowId, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("tax[$idx]", 'Tax:') !!}
{!! Form::text("tax[$idx]", $item->tax, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("total_price[$idx]", 'Sub Total:') !!}
{!! Form::text("total_price[$idx]", $item->subtotal, ['class'=>'form-control'])!!}
</div>
<?php $idx++; ?>
#endforeach
#endif
<div class="form-group">
{!! Form::label('terminal_id', 'Terminal ID:') !!}
{!! Form::text('terminal_id', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('customer_name', 'Customer Name:') !!}
{!! Form::text('customer_name', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('sale_date', 'Sale Date:') !!}
{!! Form::text('sale_date', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::submit('Check Out', ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
I suggest you also putting your for loop in a transaction in order to improve it's safety.
Like this:
public function store(SalesCreateRequest $request) {
$counter = Input::get('counter');
\DB::transaction(function() use ($counter){
for ($i=0; $i < $counter; $i++){
Sale::create([
'terminal_id' => Input::get("terminal_id")[$i],
'customer_name'=> Input::get("customer_name")[$i],
'unit_price'=> Input::get("unit_price")[$i],
'total_price'=> Input::get("total_price")[$i],
'tax'=> Input::get("tax")[$i],
'quantity'=> Input::get("quantity")[$i],
'product_name'=> Input::get("product_name")[$i],
'sale_date'=> Input::get("sale_date")[$i],
'rowId'=> Input::get("rowId")[$i]
]);
}
});
return "working";
}
Note that you could simply add a [] suffix instead of [$idx] in your input names to make your inputs arrays, but usually indexing your inputs explicitly is safer.
Edit the $idx key from Cart::content() was returning a weird number, that was why simple numerical numbers threw Out of range exception.
Change your view code as I did above, I hope fixing it this way.
Hope it helps
Just modify your controller
$counter = $request['counter'];
\DB::transaction(function() use ($counter, $request) {
for ($i = 0; $i < count($counter); $i++) {
Sale::create([
'terminal_id' => $request["terminal_id"],
'customer_name' => $request["customer_name"],
'unit_price' => $request["unit_price"][$i],
'total_price' => $request["total_price"][$i],
'tax' => $request["tax"][$i],
'quantity' => $request["quantity"][$i],
'product_name' => $request["product_name"][$i],
'sale_date' => $request["sale_date"],
'rowId' => $request["rowId"][$i]
]);
}
});
NOTE
Not all input fields are array (terminal_id, sale_date...)

Laravel 4 error when changing password

My Controller
public function update($id)
{
if (!is_numeric($id)) {
// #codeCoverageIgnoreStart
return \App::abort(404);
// #codeCoverageIgnoreEnd
}
$temp = Input::all();
$temp['password'] = Hash::make($temp['password']);
//form Processing
$result = $this->userForm->update($temp);
//$result = $this->userForm->update(Input::all());
if ($result['success']) {
// Success!
Session::flash('success', $result['message']);
return Redirect::action('UserController#index', array($id));
} else {
Session::flash('error', $result['message']);
return Redirect::action('UserController#edit', array($id))
->withInput()
->withErrors($this->userForm->errors());
}
}
My View
<div class="form-group {{ ($errors->has('firstName')) ? 'has-error' : '' }}" for="firstName">
{{ Form::label('edit_firstName', 'First Name', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-10">
{{ Form::text('firstName', $user->first_name, array('class' => 'form-control', 'placeholder' => 'First
Name', 'id' => 'edit_firstName'))}}
</div>
{{ ($errors->has('firstName') ? $errors->first('firstName') : '') }}
</div>
<div class="form-group {{ ($errors->has('lastName')) ? 'has-error' : '' }}" for="lastName">
{{ Form::label('edit_lastName', 'Last Name', array('class' => 'col-sm-2 control-label')) }}
<div class="col-sm-10">
{{ Form::text('lastName', $user->last_name, array('class' => 'form-control', 'placeholder' => 'Last Name',
'id' => 'edit_lastName'))}}
</div>
{{ ($errors->has('lastName') ? $errors->first('lastName') : '') }}
</div>
#if (Sentry::getUser()->hasAccess('admin'))
<div class="form-group">
{{ Form::label('edit_memberships', 'Group Memberships', array('class' => 'col-sm-2 control-label'))}}
<div class="col-sm-10">
#foreach ($allGroups as $group)
<label class="checkbox-inline">
<input type="checkbox" name="groups[{{ $group->id }}]" value='1'
{{ (in_array($group->name, $userGroups) ? 'checked="checked"' : '') }} > {{ $group->name }}
</label>
#endforeach
</div>
</div>
<div class="form-group {{ ($errors->has('password')) ? 'has-error' : '' }}">
{{ Form::password('password', array('class' => 'form-control', 'placeholder' => 'Password')) }}
{{ ($errors->has('password') ? $errors->first('password') : '') }}
</div>
#endif
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
{{ Form::hidden('id', $user->id) }}
{{ Form::submit('Submit Changes', array('class' => 'btn btn-primary'))}}
</div>
</div>
{{ Form::close()}}</div>
I'm trying to update data profile like; first name, last name, member and password.
I cannot update this password, my encryption password like:
$2y$10$mjkd5MRgUEn2JSK52xrrQ.bpDz5WZwAaHje6gd0TbmH7h4H3.7BBO

Update user on the same page laravel 5

I am new to the framework and I have a question.
I made a login authentication to access and when I go to my profile page I can view my data and change all on the same page.
I need to go get my ID to be able to do the update or not needed?
What do I need to do?
The way I'm doing okay? I only need to create a route::post?
my profile page:
#if(Session::has('message'))
<div class="alert alert-danger">
<h5>{{ Session::get('message') }}</h5>
</div>
#endif
{!! Form::open(array('url' => 'backend/perfil', 'name' => 'updateProfile', 'role' => 'form'))!!}
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-3 col-lg-3"></div>
<div class="col-md-2 col-lg-2">
{!! Form::label('name', 'Utilizador', ['class' => 'label_perfil']) !!}
</div>
<div class="col-md-5 col-lg-5">
{!! Form::text('name', null, ['class' => 'form-control input-md', 'placeholder' => 'Utilizador']) !!}
</div>
</div>
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-3 col-lg-3"></div>
<div class="col-md-2 col-lg-2">
{!! Form::label('nascimento', 'Data de nascimento', ['class' => 'label_perfil']) !!}
</div>
<div class="col-md-5 col-lg-5">
{!! Form::date('nascimento', null, ['class' => 'form-control input-md']) !!}
{{ $errors->first('nascimento', '<span class=error>:message</span>') }}
</div>
</div>
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-3 col-lg-3"></div>
<div class="col-md-2 col-lg-2">
{!! Form::label('sexo', 'Sexo', ['class' => 'label_perfil']) !!}
</div>
<div class="col-md-5 col-lg-5">
{!! Form::select('sexo', ['Masculino', 'Feminino'], null, ['class' => 'form-control input-md']) !!}
</div>
</div>
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-3 col-lg-3"></div>
<div class="col-md-2 col-lg-2">
{!! Form::label('email', 'Email', ['class' => 'label_perfil']) !!}
</div>
<div class="col-md-5 col-lg-5">
{!! Form::text('email', null, ['class' => 'form-control input-md', 'placeholder' => 'Email']) !!}
</div>
</div>
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-3 col-lg-3"></div>
<div class="col-md-2 col-lg-2">
{!! Form::label('password', 'Password', ['class' => 'label_perfil']) !!}
</div>
<div class="col-md-5 col-lg-5">
{!! Form::password('password', ['class' => 'form-control input-md', 'placeholder' => 'Password']) !!}
</div>
</div>
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-3 col-lg-3"></div>
<div class="col-md-2 col-lg-2">
{!! Form::label('rpassword', 'Confirmar password', ['class' => 'label_perfil']) !!}
</div>
<div class="col-md-5 col-lg-5">
{!! Form::password('rpassword', ['class' => 'form-control input-md', 'placeholder' => 'Confirmar password']) !!}
</div>
</div>
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-3 col-lg-3"></div>
<div class="col-md-2 col-lg-2">
{!! Form::label('imagem', 'Imagem', ['class' => 'label_perfil']) !!}
</div>
<div class="col-md-5 col-lg-5">
{!! Form::file('imagem', ['class' => 'input-file']) !!}
</div>
</div>
<div class="row" style="margin-bottom: 20px; margin-top: 30px;">
<div class="col-md-3 col-lg-3"></div>
<div class="col-md-9 col-lg-9">
{!! Form::submit('Enviar', ['class' => 'btn btn-primary']) !!}
</div>
</div>
{!! Form::close() !!}
My controller:
public function perfil() {
return view('backend/perfil.index');
}
public function updateProfile() {
$profileData = Input::except('_token');
$validation = Validator::make($profileData, User::$profileData);
if ($validation->passes()) {
User::where('id', Input::get('id'))->update($profileData);
return view('backend/perfil.index')->with('message', 'Updated Succesfully');
} else {
return view('backend/perfil.index')->with('message', $validation->messages());
}
}
My route:
Route::get('backend/perfil','BackendControlador#perfil');
Route::post('backend/perfil', 'BackendControlador#updateProfile');
My app User:
public static $profileData = array(
'email' => 'required|email',
'name' => 'required',
);
Here is the Detailed one what you wanted to do.
Step 1 : Open the Form
{!! Form::open(array('url' => 'updateProfile', 'name' => 'updateProfile', 'role' => 'form'))!!}
Note : Your form method action is empty. You shall view your source to see it
Step 2 : Write a route
Route::post('updateProfile', 'homeController#updateProfile');
It will call the homeController's updateProfile function
Step 3 : Define the Controller, validate the input and make your action done via model
Here's the simple/sample function for you
public function updateProfile()
{
$profileData = Input::except('_token');
$validation = Validator::make($profileData, User::$profileData);
if ($validation->passes()) {
User::where('id', Input::get('id'))->update($profileData);
return view('profile')->with('message', 'Updated Succesfully');
} else {
return view('profile')->with('message', $validation->messages());
}
}
What it does is it will get all the inputs except _token and store it in $profileData, then it will make a validation that is defined inside $profileData inside the User Model
Here is the Validator, you shall modify it
public static $profileData = array(
'email' => 'required|email',
'name' => 'required',
);
Step 4 : Return the Result
If the validation is passed, then it will update in the table to where the user whose id is passed i.e., Input::get('id') , and we will return the page with return view('profile')->with('message', 'Updated Succesfully');
I consider your page name as profile.blade.php and you shall change it according to your blade,
If the validation is failed, then we will return the page with error messages
return view('profile')->with('message', $validation->messages());
You should have this in your blade to display your error messages
#if(Session::has('message'))
<div class="alert alert-danger">
<h5>{{ Session::get('message') }}</h5>
</div>
#endif
Note :
If you don't want to refresh the page, then you shall just do an Ajax call to pass the variables and show/hide the results that is return by the Controller
Hope this helps you

How do I populate Laravel/Blade checkboxes from json in a db

Laravel is great that it auto populates the fields for you on an edit form. However i seem to be having bother getting this to work for checkboxes.
I have a list of disciplines that get stored as a json array in the database like so ["FULL_CONTACT","K1"]
How do I get these to display as checked in the form?
{!! Form::model($official, array('method' => 'put', 'route' => ['officials.update', $official->id], 'class' => 'form-horizontal')) !!}
<div class="form-group">
<label for="" class="col-lg-3 control-label">First Name:</label>
<div class="col-lg-9 controls">
{!! Form::text('first_name', null, array('class' => 'form-control', 'max-length' => '50', 'required')) !!}
</div>
</div>
<label class="checkbox">
{!! Form::checkbox('disciplines[]', null) !!} Full Contact
</label>
<label class="checkbox">
{!! Form::checkbox('disciplines[]', null) !!} Low Kick
</label>
<label class="checkbox">
{!! Form::checkbox('disciplines[]', null) !!} K1
</label>
{!! Form::close() !!}
{{ Form::checkbox('disciplines[]', 'Low Kick', true) }}
this will generate following html
<input checked="checked" name="disciplines[]" type="checkbox" value="Low Kick">
Form::checkbox's arguments are
Form::checkbox($name, $value, $checked, $options)
You can use #foreach loop to display all the checkboxs, for example:
#foreach($disciplines as $discipline)
{!! Form::checkbox('disciplines[]', $discipline, null) !!} label
#endforeach`

Categories