Laravel parsing Input from a multiple select box not working - laravel

This is my pubf in my Controller which handles the request:
public function addPermissionsToRoleHandler($rid, Request $request)
{
$role = Role::find($rid);
dd($request->permissions);
foreach($request->permissions as $perm)
{
$permission = Permission::find($perm->id);
$role->attachPermission($permission);
}
return redirect()->route('showSpecificRole', $rid);
}
This is how I defined my multiple select-box:
{!! Form::select('permissions[]', $permissions, null, array('class' => 'selectpicker show-tick', 'data-live-search' => 'true', 'id' => 'permission_select', 'multiple' => true)) !!}
Why is my dd() returning null? $request->permission is empty. dd($request) only has token_.

I don't have the rep to comment so am posting as an answer. I am not sure, but I think it may be because the Request needs to be the first argument ?

Related

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!

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
}

Get the model ID when updating a resource

I have a form that will submit a Patch request to the controller's update method.
But the update method requires to have $id, as you can see below whenever I try that I get a
No query results for model [Item]. Since the update method did not receive the $id of the model
public function update($id)
{
$item = Item::findOrFail($id);
$update = Input::all();
// some codes to save changes
return Redirect::route('items.index');
}
Another thing is that whenever I submit the form, url turns into something like this:
mw.dev/items/%7Bitems%7D
Edit
routes.php
Route::resource('items','ItemsController');
ItemController
public function edit($id)
{
$item = Item::findOrFail($id);
return View::make('items.edit')->with('item',$item);
}
I have included the code on my edit.blade.php
{{Form::open(array('route' => 'items.update', 'method'=>'patch'))}}
{{Form::text('barcode', $item->barcode, array('placeholder' => 'barcode'))}}
{{Form::text('imei',$item->imei, array('placeholder' => 'imei'))}}
{{Form::text('item_name', $item->item_name, array('placeholder' => 'item name'))}}
{{Form::submit('edit')}}
{{Form::close()}}
You have to pass the model to your view and need to pass the id parameter when generating the form. Assume that you have a User model and it's available in the view. So you may generate the form action using something like this:
// Using Form::open method with route
Form::open(array('route' => array('route.name', $user->id)))
// Using Form::model method with route
Form::model($user, array('route' => array('route.name', $user->id), 'method' => 'patch'))
// Using Form::open method with action
Form::open(array('action' => array('Controller#update', $user->id), 'method' => 'patch'))
// Using Form::open method with url
Form::open(array('url' => 'something/update/' . $user->id, 'method' => 'patch'))
Check more on Opening A Form.
The URL
mw.dev/items/%7Bitems%7D
is most likely the url-encoded form of
mw.dev/items/{items}
I suppose there is a problem in the form submission or in the <form>'s action paremeter or in the Route::* declaration in routes.php.
This could also explain why you don't get any $id upon submission.

Laravel 4 password reminder: redirection issue

I'm using the Laravel 4 password reminder functionality, as described here: http://four.laravel.com/docs/security#password-reminders-and-reset. In order to generate the token, send the email and create de DB record in the password_reminder table, I use the standard code in my routes file :
Route::post('password/remind', function() {
$credentials = array('email' => Input::get('email'));
return Password::remind($credentials);
});
This code is suppose to send me back to my input form in case of any error (unknown email address for instance). Instead of that, I get a MethodNotAllowedHttpException. The reason is Laravel don't try to send me back to my form URL (which is /password/forgot): he tries to redirect me to /password/remind, in GET, and this route does not exist (of course) in my routes.php file.
I checked the code of the Illuminate\Auth\Reminders\PasswordBroker class, which is responsible of this redirection, and found out this method :
protected function makeErrorRedirect($reason = '')
{
if ($reason != '') $reason = 'reminders.'.$reason;
return $this->redirect->refresh()->with('error', true)->with('reason', $reason);
}
I replaced $this->redirect->refresh() by $this->redirect->back(), and everything is now working as excepted. But as I couldn't find any comment on this bug anywhere, I assume I'm doing something wrong… But I can't find what !
Here is my routes.php file:
Route::get('password/forgot', array('as' => 'forgot', 'uses' => 'SessionsController#forgot'));
Route::post('password/remind', function() {
$credentials = array('email' => Input::get('email'));
return Password::remind($credentials);
});
Route::get('password/reset/{token}', function($token) {
return View::make('sessions.reset')->with('token', $token);
});
Route::post('password/reset/{token}', array('as' => 'reset', 'uses' => 'SessionsController#reset'));
my SessionsController relevant code:
class SessionsController extends BaseController {
[...]
public function forgot() {
return View::make('sessions.forgot');
}
public function reset() {
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'password_confirmation' => Input::get('password_confirmation')
);
Input::flash();
return Password::reset($credentials, function($user, $password) {
$user->password = Hash::make($password);
$user->save();
return Redirect::to('home');
});
}
}
and finally my view code:
{{ Form::open(array('url' => 'password/remind', 'class' => 'form', 'role' => 'form', 'method'=>'post')) }}
<div class="form-group">
{{ Form::label('email', 'E-mail') }}
{{ Form::text('email', '', array('autocomplete'=>'off', 'class' => 'form-control')) }}
</div>
{{ Form::submit("Envoyer", array("class"=>"btn btn-primary")) }}
{{ Form::close() }}
If it is possible, I highly recommend you to upgrade to Laravel 4.1, because it comes with a more flexible (also easier to understand and to work with) solution for password remind/reset.
Check out this example with Laravel 4.1:
https://github.com/laracasts/Laravel-4.1-Password-Resets/blob/master/app/controllers/RemindersController.php

Resources