laravel: using parameters from routes in blade forms - laravel

This is my add.blade.php.
{{ Form::open(array('url' => $id."/item", 'method' => 'post', 'files' => 'true', 'id'=>'add')) }}
{{ Form::text('title'}}
{{Form::submit('Submit')}}
{{Form::close()}}
This is my web.php
Route::resource('{categoryId}/item', 'ItemController');
This is my ItemController.php
public function create($categoryId){
return view('item.add', array('id' => $categoryId));
}
I am trying to add new item to a category. So I click add new and it opens add.blade.php. When I submit from add.blade.php, it is redirecting it to item/create. I think it is because of url in the form of add.blade.php. What is the correct way of doing this? Thanks in advance

I think you should try this:
{{Form::open(['route' => ['item.create', $id],'method' => 'post', 'files' => 'true', 'id'=>'add'])}}

You can try prefix instead of append parameter
Route::group(['prefix' => '{categoryId}'], function()
Route::resource('item', 'ItemController');
});
then use
route('item.create',['1']);
Here in your code just pass parameter and will work like this:
['route' => ['item.create', $id]

your View
{{ Form::open(array('url' => "/item/".$id , 'method' => 'post', 'files' => 'true', 'id'=>'add')) }}
{{ Form::text('title'}}
{{Form::submit('Submit')}}
{{Form::close()}}
your Route
Route::resource('item', 'ItemController');
Route::post('/item/{categoryId}', 'ItemController#create');
your Controller
public function create($categoryId){
$id = $categoryId;
return view('item.add', compact('id'));
}

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'
));

Why isn't the parameter getting passed to my route

I must have missed something...wondering why the parameter isn't getting passed into my route.
My URL ends up looking like
//admin/attendees/%7Battendee%7D/paid
I want the %7Battendees%7D to be replaced with a number
Here's my route and view
Route::post('attendees/{attendee}/paid', array('as' =>'admin.attendees.paid', 'uses'=>'AdminAttendeeController#postPaid'));
{{Form::open(array('class' => 'paid', 'method' => 'POST', 'route' => 'admin.attendees.paid', $attendee->id))}}
What did I do wrong?
This should work:
{{
Form::open(array(
'class' => 'paid',
'method' => 'POST',
'route' => array('admin.attendees.paid', $attendee->id)
))
}}
You can find more details in illuminate/html source code: https://github.com/illuminate/html/blob/master/FormBuilder.php#L799

Passing a param containing a path to a controller

I'm trying to pass a variable who contains a path from a form to a controller function in Laravel 4, with the purpose of download an image. I tried a lot of things but nothing worked for me. If I don't pass the parameter in the route, I get a missing parameter error, and if I pass the parameter in the route, I get a NotFoundHttpException.
Here's my code:
View Form:
{{ Form::open(array('route' => array('download', $myPath))) }}
{{ Form::submit('Download', array('class' => 'generator')); }}
{{ Form::close() }}
Route:
Route::post('/download/{myPath}', array('uses' => 'ImagesController#download', 'as' => 'download'));
ImagesController function:
public function download($myPath){
return Response::download($myPath);
}
When I click the submit I'm obtaining a URL like this with NotFoundHttpException:
http://localhost/resizer/public/download/images/myimage.jpg
I don't understand what I'm missing.
You are actually posting two variables. Try this instead
Route::post('/download/{myFolder}/{myFile}', array('uses' => 'ImagesController#download', 'as' => 'download'));
and in your controller
public function download($myFolder, $myFile){
return Response::download($myFolder.'/'.$myFile);
}

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!

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