Why if part not executed in laravel 5 controller method? - laravel-5

public function index1()
{
$g = Request::Input('grade');
$s = Request::Input('subject');
if(strcmp($g,'Select A Grade')==0 || strcmp($s,'Select A Subject')==0) {
if (strcmp($s, 'Select A Subject') == 0) {
// Session::flash('msg', 'Please select the Subject.');
return redirect()->back()->withInput();
} else if (strcmp($g, 'Select A Grade') == 0) {
// Session::flash('msg', 'Please select the Grade.');
return redirect()->back()->withInput();
}
}
else{
$u = DB::table('upldtbls')->where('grade',$g)->where('subject',$s)->get();
return view('2Eng',compact('u'));
}
}
Above is the controller method. Main else part executed correctly. But main if part not executed as I wanted. In main if condition I want to stay on the same page if drop box values are equal to that which means when they haven't select an option from drop box. Can any one figure out this mess?
{!! Form::select('Select A Grade', array('' => 'Select A Grade','2' => '2', '3' => '3','4' => '4'), 'Select A Grade', ['class' => 'form-control'])
{!! Form::select('Select A Subject', array('' => 'Select A Subject','English' => 'English', 'Mathematics' => 'Mathematics','Environmental Studies' => 'Environmental Studies'), 'Select A Subject', ['class' => 'form-control']) !!}

The if part is probably not being executed because the condition is not being met. Check that $g or $s is equal to 0 as per you check. If you are simply trying to see if these Input parameters are empty / blank, amend your if statement to:
if(!$g || !$s){
...
}
Also, you should really use Request::Input instead of $_GET, but you need to fix it to one of the below:
# Laravel 5.1.x or earlier
$g = Request::Input('grade');
$s = Request::Input('subject');
or
# Laravel 5.2.x or later
$g = $request->input('grade');
$s = $request->input('subject');
UPDATE
The issue is with your select boxes. You have incorrectly named them, and you would have noticed this if you carried out some basic debugging. Update them as follows:
{!! Form::select('grade', array('' => 'Select A Grade','2' => '2', '3' => '3','4' => '4'), null, ['class' => 'form-control'])
{!! Form::select('subject', array('' => 'Select A Subject','English' => 'English', 'Mathematics' => 'Mathematics','Environmental Studies' => 'Environmental Studies'), null, ['class' => 'form-control']) !!}
i.e. the first parameter should be the name of the field, which gets passed to $_GET. After updating the form, please update the if statement to my suggestion above.

Related

Laravel 8 #extends with parameters not null condition

i have a laravel blade template and i need to extends a layous with different values depending on parameter status.
I've tried the follow solution but it does not work.
It seems that always to be considered the first #extends but $patient is null so I expect the second #extends statement to be considered.
Is the following statement correct?
#if(isset($patient->id))
#extends('layouts.app', [
'class' => '',
'elementActive' => 'patients'
])
#else
#extends('layouts.app', [
'class' => '',
'elementActive' => 'diets'
])
#endif
Do you have some suggestions?
Thank you.
Solved with:
#extends('layouts.app', [
'class' => '',
'elementActive' => $patient ? 'patients': 'diets']
)

Checkbox in foreach loop in Laravel

I have a foreach loop that has a checkbox in it. I am not sure how to properly get that from the checkbox in the form over to the validation in the controller. I have the following in my view:
<table class="table">
<thead>
<tr>
<th scope="col">Select</th>
</tr>
</thead>
<tbody>
#foreach($plans as $plan)
<tr>
<td>
<input type='checkbox' name='Plan {{$plan->{'Plan ID'} }}' class='form-check-input' value='true'
#if(old($plan->{'Plan ID'},$plan->{'Plan ID'})=="true") checked #endif>
</td>
<td> {{$plan->{'Plan ID'} }}</td>
#endforeach
</tr>
</tbody>
</table>
I have the following in my controller:
$data = request()->validate ([
'current' => '',
'instructions' => '',
'Plan 1' => '',
'Plan 2' => '',
'Plan 3' => '',
'Plan 4' => '',
'Plan 5' => '',
'Plan 6' => '',
'Plan 7' => '',
'Plan 8' => '',
'Plan 9' => '',
'Plan 10' => '',
'Plan 11' => '',
'Plan 12' => '',
'Plan 13' => '',
'Plan 14' => '',
'Plan 15' => '',
]);
$plansubmission = PlanSubmission::find($id);
//$plansubmission->update($data);
$designs = MedicalDesignsToQuote::find($id);
if($designs==null){
$design = MedicalDesignsToQuote::create(['id'=>$id]);
$design->update($data);
}
else{
$designs->update($data);
I do not want to use an array for the 'name' attribute
Added this to controller:
$validator = Validator::make($request->all(), [
"list.*.id" => '', // Object exist validation
"list.*.value" => '',
'current' => '',
'instructions' => '',
]);
$bodyContent = $request->getContent($validator);
$plansubmission = PlanSubmission::find($id);
// $plansubmission->update($data);
$designs = MedicalDesignsToQuote::find($id);
if($designs==null){
$design = MedicalDesignsToQuote::create(['id'=>$id]);
// $design->update($data);
$design->update($validator);
}
else{
$designs->update($validator);
}
I have the following columns in my table:
id
current
instructions
Plan 1
Plan 2
Plan 3
Plan 4
Plan 5
.....
Plan 50
The user can select any or all of the 50 plan options with a checkbox. If, for example, Plan 5 is selected, the value for this given row within the table will be 'True' for plan 5.
So, to persist the data, I would expect I need to do something like this:
$formData = $request->all();
foreach ($formData['list'] as $planData) {
MedicalPlanDesignToQuote::updateOrCreate(
[$planData['id']] => $planData['value']],
);
}
If I had two columns called id and value, I suppose I could do this:
foreach ($formData['list'] as $planData) {
MedicalPlanDesignToQuote::updateOrCreate(
['id' => $planData['id']],
['value' => $planData['value']]
);
}
Is there anyway I can do this with my table structure?
First things first:
You have an error in your example. The #endforeach needs to be moved one column down.
Second:
You need to understand, what you are exactly doing here. You deal with an 1-n relationship between some kind of list and the list items. Ergo, you need to build your post/get body accordingly.
An example for a single table row could be:
<tr>
<td>
<Input type="hidden" value="{{$plan->{'Plan ID'} }}" name="list[][id]">
<Input type="checkbox" value="true" name="list[][value]">
</td>
<td>
{{$plan->{'Plan ID'} }}
</td>
</tr>
Now you are able to iterate over items accordingly, independent from their id.
Now you are able to use request validation as stated here: https://laravel.com/docs/master/validation#validating-arrays
In our case:
"list.*.id" => "...", // Object exist validation
"list.*.value" => "..."
Now how to pass everything to objects and persist them:
You need to be aware, you can't just pass anything into your objects. Right now you pass a validator. Instead use the validation only vor validation. Laravel will take care of returning a response.
$this->validate($request, [
'current' => required'',
'instructions' => 'required',
"list.*.id" => "required", // Object exist validation
"list.*.value" => "required"
]);
Afterwards you get your data from your request object:
$formData = $request->all();
We stored our information in the key 'list' (see html). So you will find it in your request object. There are multiple "plans" stored in our list. Now you need to iterate:
foreach ($formData['list'] as $planData) {
Plan::updateOrCreate(
['id' => $planData['id']],
['value' => $planData['value']]
);
}
Of course you need to also save other objects/create relationships if there are any.
If you want to stay with your table structure (you may should rework it: keyword BCNF), you are still able/need to iterate:
$dataArray = [];
foreach ($formData['list'] as $planData) {
$dataArray['Plan ' . $planData['id']] = $planData['value'];
}
$dataArray['current'] = $formData['current'];
$dataArray['instructions'] = $formData['instructions'];
// This way do not need to use create
$designs = MedicalDesignsToQuote::updateOrCreate(
['id' => $id],
$dataArray
);
You need to create an Option Group and Option tables to handle all your lists.
For example, you need a Location List and a Restaurant List.
Add a parent of Location List in Option Group and the child in Option and join them in Option.php to handle all your list in the future.
public static function getOfficeLocationList(){
return Option::where('group_id', config('constants.OPT_GROUP_OFFICE_LOC'))->orderBy('name','ASC')->get();
}
In my example, group_id is the ID of the parent list, in that way you can get all the location option you stored.
In your controller:
$locationList = Option::getOfficeLocationList();
In your blade:
#foreach($locationList as $item)
your input checkbox with $item->name and $item->id
#endforeach
That's it: Throw the formData in your validation :)

Laravel 5.1, optional parameter causing blank page

The concerning route:
Route::patch('admin/track/practice/{practice_id}/close-practice-session/{session_id}/{new?}', array(
'as' => 'close-practice-session',
'uses' => 'AdminController#closePracticeSession'
));
new is an optional route parameter.
The Controller method:
public function closePracticeSession($club, $practice_id, $session_id, $new = null)
{
$clubDetails = new ClubDetails();
$club_id = $clubDetails->getClubID($club);
date_default_timezone_set(config('app.timezone'));
$CurrentTime = date("Y-m-d H:i:s");
try
{
DB::table('practice_sessions')
->where('id', $session_id)
->where('club_id', $club_id)
->update(['is_current' => 0, 'updated_at' => $CurrentTime]);
if ($new == 'Y')
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id]);
}
else
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id, $session_id])
->with(array('success'=>'Practice was successfully closed.'));
}
}
catch(\Exception $e)
{
return view('errors.500')->with(self::getRequiredData($club))->with('error', $e->getMessage());
}
}
I have two forms on my view, one has the optional parameter, one doesn't.
When I click on the button on the form which has the optional parameter, I am getting a BLANK screen.
Here are some strange things:
No error message. Checked the laravel.log
Even if I remove all the logic from the controller method and do a
simple var_dump, I still get a blank screen
When I click on the button without the optional parameter, it
behaves as expected
I have been trying for the last two days to resolve this without any luck. I have even tried to make the {new} parameter mandatory. Anytime I am passing the last parameter, I am getting a blank screen.
Any idea? I am sure I am doing something silly. Just can't see it.
Update (the two forms on the view) - the csrf token is in the header.
{!! Form::open([
'method' => 'PATCH',
'route' => ['close-practice-session', $alias, $practiceDetails[0]->practice_id, $practiceDetails[0]->id]
]) !!}
{!! Form::submit('Close Session', ['class' => 'btn btn-primary btn-sm', 'style' => 'width: 160px;margin-left: 0px!important']) !!}
{!! Form::close() !!}
<!-- #2 -->
{!! Form::open([
'method' => 'PATCH',
'route' => ['close-practice-session', $alias, $practiceDetails[0]->practice_id, $practiceDetails[0]->id, "Y"]
]) !!}
{!! Form::submit('Close + Create New', ['class' => 'btn btn-secondary btn-sm', 'style' => 'width: 160px;margin-left: 0px!important']) !!}
{!! Form::close() !!}
As per your route
Route::patch('admin/track/practice/{practice_id}/close-practice-session/{session_id}/{new?}', array(
'as' => 'close-practice-session',
'uses' => 'AdminController#closePracticeSession'
));
Your controller function should be like this
public function closePracticeSession(Request $request, $practice_id, $session_id, $new = null)
{
$clubDetails = new ClubDetails();
$club_id = $clubDetails->getClubID($club);
date_default_timezone_set(config('app.timezone'));
$CurrentTime = date("Y-m-d H:i:s");
try
{
DB::table('practice_sessions')
->where('id', $session_id)
->where('club_id', $club_id)
->update(['is_current' => 0, 'updated_at' => $CurrentTime]);
if ($new == 'Y')
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id]);
}
else
{
return redirect()->action('AdminController#getTrackPracticeSession', [$club, $practice_id, $session_id])
->with(array('success'=>'Practice was successfully closed.'));
}
}
catch(\Exception $e)
{
return view('errors.500')->with(self::getRequiredData($club))->with('error', $e->getMessage());
}
}
Please take a look at this SO post. This gave me a hint to solve my problem. I had an identical GET route in my routes.php file. Once I modified my PATCH route to the following, everything is working as expected.
Route::patch('admin/close-practice-session/{practice_id}/{session_id}/{new?}', array(
'as' => 'close-practice-session',
'uses' => 'AdminController#closePracticeSession'
));

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!

Why aren't validation errors being displayed in CakePHP?

I'm trying to perform validation in the login page for the name,email and password fields. If the input fails validation,the error message should be displayed.
But here,when I fill in the details and submit, it is redirected to the next page. Only the value is not saved in the database.
Why is the message not displayed?
This is my model:
class User extends AppModel {
var $name = 'User';
var $validate = array(
'name' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
),
'password' => array(
'rule' => array('minLength', '8'),
'message' => 'Mimimum 8 characters long'
),
'email_id' => 'email'
);
function loginUser($data) {
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
$login = $this->find('all');
foreach ($login as $form):
if ($this->data['User']['email_id'] == $form['User']['email_id'] && $this->data['User']['password'] == $form['User']['password']) {
$this->data['User']['id'] = $this->find('all',
array(
'fields' => array('User.id'),
'conditions' => array(
'User.email_id' => $this->data['User']['email_id'],
'User.password'=>$this->data['User']['password']
)
)
);
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
endforeach;
}
function registerUser($data) {
if (!empty($data)) {
$this->data['User']['name'] = $data['User']['name'];
$this->data['User']['email_id'] = $data['User']['email_id'];
$this->data['User']['password'] = $data['User']['password'];
if($this->save($this->data)) {
$this->data['User']['id']= $this->find('all', array(
'fields' => array('User.id'),
'order' => 'User.id DESC'
));
$userId=$this->data['User']['id'][0]['User']['id'];
return $userId;
}
}
}
}
This is my controller:
class UsersController extends AppController {
var $name = 'Users';
var $uses=array('Form','User','Attribute','Result');
var $helpers=array('Html','Ajax','Javascript','Form');
function login() {
$userId = $this->User->loginUser($this->data);
if($userId>0) {
$this->Session->setFlash('Login Successful.');
$this->redirect('/forms/homepage/'.$userId);
break;
} else {
$this->flash('Login Unsuccessful.','/forms');
}
}
function register() {
$userId=$this->User->registerUser($this->data);
$this->Session->setFlash('You have been registered.');
$this->redirect('/forms/homepage/'.$userId);
}
}
EDIT
Why is the message,example,"Minimum 8 characters long", is not being displayed when give less than 8 characters in the password field?
<!--My view file File: /app/views/forms/index.ctp -->
<?php
echo $javascript->link('prototype.js');
echo $javascript->link('scriptaculous.js');
echo $html->css('main.css');
?>
<div id="appTitle">
<h2> formBuildr </h2>
</div>
<div id="register">
<h3>Register</h3>
<?php
echo $form->create('User',array('action'=>'register'));
echo $form->input('User.name');
echo $form->error('User.name','Name not found');
echo $form->input('User.email_id');
echo $form->error('User.email_id','Email does not match');
echo $form->input('User.password');
echo $form->end('Register');
?>
</div>
<div id="login">
<h3>Login</h3>
<?php
echo $form->create('User',array('action'=>'login'));
echo $form->input('User.email_id');
echo $form->input('User.password');
echo $form->end('Login');
?>
</div>
Your validation seems correct
How about trying the following:
Make sure set your $form->create to the appropriate function
Make sure there is no $this->Model->read() before issuing Model->save();
Edit
Did you have the following?:
function register()
{
//do not put any $this->User->read or find() here or before saving pls.
if ($this->User->save($this->data))
{
//...
}
}
Edit2
IF you're doing a read() or find() before saving the Model then that will reset the fields. You should be passing the variable as type=hidden in the form. I hope i am making sense.
Edit3
I think you need to move your registerUser() into your controller because having that function in the model doesn't provide you a false return. it's always going to be true even if it has validation errors.
Comment out the redirect line and set the debug to 2 in config/core.php. Then look at the sql that is being generated to see if your insert is working. If the errors are not being displayed, maybe in the view, you are using $form->text or $form->select instead of the $form->input functions. Only the $form->input functions will automatically display the error messages.

Resources