Laravel: getting and combining values from radio button - laravel

I'm currently making a sort of 'quiz' to get a user's starter class based on their given answers. A personality test, basically.
Here is an example of my forms
<div class="form-group">
<h4>{{Form::label('title', 'Favourite season?')}}<br></h4>
<div class="container">
<div class="option">
Spring - {{Form::radio('q4', 1, false)}}<br>
Summer - {{Form::radio('q4', 2, false)}}<br>
Autumn - {{Form::radio('q4', 3, false)}}<br>
Winter - {{Form::radio('q4', 4, false)}}
</div>
</div>
</div>
My controller is barren at the moment, seeing as I am not sure how to grab each value, then combine them into a final result
public function store(Request $request)
{
$this->validate($request, [
'q1' => 'required',
'q2' => 'required',
'q3' => 'required',
'q4' => 'required',
'q5' => 'required',
'q6' => 'required',
'q7' => 'required',
'q8' => 'required',
'q9' => 'required',
'q10' => 'required',
]);
return $request;
}
}
My post correctly gets the values from the inputs, I just need to know how I can get these into one final score and store it into the database
I have tried using JavaScript, however I cannot figure out how to get the result into the controller to store in the database.

Well you could try to name your radio inputs as an array so then you can retrieve the values in one shot:
{{ Form::radio('q[3]', 1, false) }}
{{ Form::radio('q[3]', 2, false) }}
...
{{ Form::radio('q[4]', 1, false) }}
{{ Form::radio('q[4]', 2, false) }}
...
Then in your Controller you can get all the values into a single array:
$values = $request->input('q', []);
Then you can get the sum of this pretty easily:
$sum = array_sum($values);
You would probably want to do some validation to make sure you are getting the right amount of inputs within certain value ranges.

Related

Laravel Controller Check Multiple Arrays

I am sending multiple arrays via AJAX to my controller and I'm having trouble with validation.
I have 2 text inputs. Now, the issue is that at times both these inputs are present, but at other times only one might be present.
<input type="text" name="typeDetails[games]" class="form-control input-global"/>
<input type="text" name="typeDetails[art]" class="form-control input-global"/>
My JS is like this.
var data = { 'typeDetails[games]' : [], 'typeDetails[art]' : [] };
$("input[name='typeDetails[games]']").each(function() {
data['typeDetails[games]'].push($(this).val());
});
$("input[name='typeDetails[art]']").each(function() {
data['typeDetails[art]'].push($(this).val());
});
In my controller, I want to (1) make sure that there's a validation of required and (2) if the "games" array is present, perform a particular action and if the "art" array is present, perform a different action.
$typeDetails = Input::get('typeDetails');
if ($request->has('typeDetails.games'))
{
return 'games';
}
if ($request->has('typeDetails.art'))
{
return 'art';
}
What happens here is that in my console it properly returns 'games', but even if the "art" array has values and is sent with the request, it doesn't return 'art'. I must be missing a fundamental understanding with php here.
Thanks!
ANSWER
Here's how I got it to work.
$typeDetails = Input::get('typeDetails');
$this->validate($request, [
'typeDetails.*.*' => 'required|max:50'
],[
'required' => 'You must type in some keywords to continue.',
'max' => 'Your input must be less than 50 characters.'
]);
if ($request->has('typeDetails.games'))
{
$gameInfo = Input::get('typeDetails.games');
foreach ($gameInfo as $key => $value)
{
DB::table('user_type')->insert([
'user_id' => Auth::user()->id,
'type_id' => '1',
'user_type_details' => $value,
'created_at' => Carbon::now()
]);
}
}
if ($request->has('typeDetails.art'))
{
$artInfo = Input::get('typeDetails.art');
foreach ($artInfo as $key => $value)
{
DB::table('user_type')->insert([
'user_id' => Auth::user()->id,
'type_id' => '2',
'user_type_details' => $value,
'created_at' => Carbon::now()
]);
}
}

Laravel Validate Checkbox Certain Value

I am simply needing to know how to validate my array of checkbox values to be in a certain list of values. So, I am using the "in:" validation rule as shown below, but it's returning the error that the value of the checked box is invalid. Do I need to do something different since it's an array of values sent via AJAX?
Controller:
if ($request->ajax())
{
/*Create record in UserType Model with the values from the Type checkboxes*/
$Type = Input::get('Type');
$this->validate($request, [
'Type' => 'required|in:A,B,C,D',
],[
'required' => 'You must select at least one.',
]);
foreach ($Type as $key => $value)
{
Auth::user()->userType()->create([
'profile_id' => Auth::user()->id,
'type' => $value,
]);
}
}
In my form, I have the following inputs...
<input type="checkbox" name="Type[]" value="A"/>
<input type="checkbox" name="Type[]" value="B"/>
<input type="checkbox" name="Type[]" value="C"/>
UPDATE:
So, I found in the Laravel documentation that you can validate arrays using * to get the key/values in an array. However, in my array it's just Type[] so I've tried the following with no luck.
$this->validate($request,[
'type.*' => 'required|in:A,B,C,D'
// or
'type*' => 'required|in:A,B,C,D'
]);
Just not working. I know I need to retrieve the array value something with the *.
UPDATE:
I was running Laravel 5.1 when this option for validation is only available in Laravel 5.2. Solved.
First: The required isn't necessary when using in because it must be A, B or C. That is like a "multiple" required already.
Second: As shown in the docs just use:
$this->validate($request,[
'Type.*' => 'in:A,B,C,D'
],[
'in' => 'You must select at least one.',
]);
As your Input array is named Type. That would validate all Inputs named Type.
To be clear the asteriks could be replaced by e.g. one to just validate the Input named Type[one]:
'Type.one' => 'in:A,B,C,D'
or if the Input would be named Type[one][name]
'Type.one.name' => 'in:A,B,C,D'
You try this
if($this->has('Type') && is_array($this->get('Type'))){
foreach($this->get('Type') as $key => $Type){
$rules['Type'.$key.'] = 'required|in:A,B,C,D';
}
In laravel 5 ..
$this->validate($request, [
'Type' => 'required|array'
]);
Worked for me for checkboxes

Laravel 5 Validate Birthdate From Select Fields

I have a registration form with 3 select fields (month, day, year) which I want to grab, convert to proper date format, and validate. So, below are the 3 select boxes.
<div class="birthday_selects">
<select name="birthday_month">
....
</select>
<select name="birthday_day">
....
</select>
<select name="birthday_year">
....
</select>
</div>
I've read that I can use the following, but I get the error "...Http\Input not found..."
$birthday = Input::get('birthday_month')."-".Input::get('birthday_day')."-".Input::get('birthday_year')'
Okay, I can dd($birthday) and it comes out in the m-d-y as I've concatenated there. Now, I'm trying to validate that date against a prior date (to see if user is >13 years old). I'm using the following, but no luck.
public function postSignup(Request $request)
{
$birthdate = Input::get('birthday-month')."-".Input::get('birthday-day')."-".Input::get('birthday-year');
$this->validate($request, [
$birthdate => 'required',
]);
dd($birthdate);
}
When just having it be required, it doesn't work.
Your help is appreciated. Thanks!
It's not working because you're doing it wrong. What is wrong with it is the rule.
The rule key must be present in the form field's name.
For your answer, let's assume the $birthday will be 'jul-15-1992'. and you're going to put that variable inside the rule as a key. So, that's not valid because the field will never be present in the form field.
public function formPost(Request $request)
{
$rule = [
'birth_year' => 'required|numeric',
'birth_day' => 'required|numeric',
'birth_month' => 'required|numeric', // may be a string
];
$this->validate($request, $rule);
// check if the day is valid for the month manually.
// then form the DOB now.
}
Create Carbon date and add new [birth_day] input:
$all = $request->all();
$year = $all['birthday_year'];
$month = $all['birthday_month'];
$day = $all['birthday_day'];
// Create Carbon date
$date = Carbon::createFromFormat('Y-m-d', $year.'-'.$month.'-'.$day);
//add new [birth_day] input
$request->request->add(['birth_day' => $date->format('Y-m-d')]);
$validatedData = $request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'password' => 'required|string',
'birth_day' => 'required|date_format:Y-m-d|before:today',// validate birth day
]);
Hope this will help you

Update / post database colum in Laravel

I have a general question.
I have a search form in larvel which returns results form the database.
in these i have an input field to enter a price if price is == 0
what my problem is when i enter price and submit it returns to the search page without my previous search results i.e it doesn't refresh the same page with results and the newly updated field etc.
form in view
{{ Form::open(['action' => 'price_input'])->with($gyms) }}
{{ Form::text('enter_price', null, ['class' => 'form-control', 'size' => '50', 'id' => 'enter_price', 'autocomplete' => 'on', 'runat' => 'server', 'required' => 'required', 'placeholder' => 'enter price!', 'style' => 'margin-bottom: 0px!important;']) }}
{{ Form::submit('Search', ['class' => 'btn btn- primary', 'style' => 'margin-left: 10px;']) }}
{{ Form::close() }}
route
Route::post('/', [ //not used yet
'as' => 'price_input',
'uses' => 'PagesController#priceUpdate'
]);
Model
public function priceUpdate($gyms)
{
if (Input::has('enter_price'))
{
$price = Input::get('enter_price');
Gym::updatePrice($price);
return Redirect::back()->withInput();
}
Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gym);
}
not bothering with model as that works fine.
any ideas guys?
Thanks for your answer,
i have changed my controller to this
public function priceUpdate($gyms)
{
if (Input::has('enter_price'))
{
$price = Input::get('enter_price');
Gym::updatePrice($price);
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
}
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
}
but when i run it i get
Missing argument 1 for PagesController::priceUpdate()
with the $gyms being passed into the method.
if i take out the $gyms that goes away but not sure if its still being passed with session or not, sorry im a novice.
orignally i had a search box which when run returns
return View::make('pages.home')->with($data);
what is the difference between that and
return View::make('pages.home')->with($data);
when i do the above line it returns to the search page with no search options from before update the form, any ideas?
Currently, you are just retrieving an existing session and doing nothing with it. You need to do:
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
Or
return Redirect::to('pages.home')->with('gyms', Session::get('gyms'));
Then you can access the gyms in the view with $gyms.
Alternatively, you could access Session::get('gyms') in the view as well.
Also, not sure if it's just the way you pasted it here, but you have an unnecessary space before the ->with. Just wanted to make sure that's not part of the issue, too!

check if value already exists in db

I have an insert form and a dropdownbox which displays all cars names and when selected one it saves the id in column "car_id" which is unique. What I want is to check if this id already exists and if yes to display a validation message:
create controller
public function create() {
$cars = DB::table('cars')->orderBy('Description', 'asc')->distinct()->lists('Description', 'id');
return View::make('pages.insur_docs_create', array(
'cars' => $cars
));
}
insur_docs_blade.php
<div class="form-group">
{{ Form::label('car', 'Car', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('car', $cars, Input::old('class'), array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid car',
'class' => 'form-control'))
}}
</div>
</div>
You can use Laravel's Validator class for this. These are a few snippits of how it works. This methods works by using your data model. Instead of writing everything out I added a few links that provide you all the information to complete your validation.
$data = Input::all();
$rules = array(
'car_id' => 'unique'
);
$validator = Validator::make($data, $rules);
if ($validator->passes()) {
return 'Data was saved.';
}
http://laravelbook.com/laravel-input-validation
http://laravel.com/docs/validation
http://daylerees.com/codebright/validation
You can use Laravel's "exists" method like this:
if (User::where('email', $email)->exists()) {
// that email already exists in the users table
}

Resources