PHP Route not defined laravel - php

Working on a job portal, so I arrived at a point where employers need to edit their posted jobs,On page load it gave me an error Route [employers/job/save/Mw==] not defined, please I need help my deadline is 3hours from now!
Here is my code:
Routes:
//Route for Employer's specified Job Editting -> To get ID as argv
Route::get('employers/job/edit/{id}', 'employerController#editJob');
//Route for Employer's to save specified Job after Editting -> To get ID as argv
Route::post('/employers/job/save/{id}', [
'as' => 'saveJob',
'uses' => 'employerController#saveJob'
]);
View:
{{ Form::open(['action'=>'employers/job/save/'.base64_encode($jobData->id),'class'=>'full-job-form', 'id'=>'jobForm','role'=>'form']) }}
<div class="form-group col-lg-12 col-sm-12 col-md-12">
<label class="sr-only" for="">Job Title</label>
<input type="text" class="form-control"
name="job_title" placeholder="Job Title"
value="{{ $jobData->job_title }}">
<span class="help-block">Eg. Marketing Manager</span>
</div>

Your issue is that you're using the action parameter for your Form::open() call. This expects the name for a controller method (e.g. {{ Form::open(['action' => 'employerController#saveJob']) }}. If you want to link to a pre-generated URL use the url parameter:
{{ Form::open(['url' => 'employers/job/save/'.base64_encode($jobData->id)]) }}
That said, that's not the best practice, as, if you change your routing system, you now have to change all these hardcoded URLs. As such, you should rely on named routing or controller actions.
Now, your route is already named ('as' => 'saveJob') so you should actually use the route parameter of Form::open():
{{ Form::open(['route' => ['saveJob', base64_encode($jobData->id)]]) }}
Alternatively, you could use the action parameter as you are currently trying to do (albeit erroneously):
{{ Form::open(['action' => ['employerController#saveJob', base64_encode($jobData->id)]]) }}
See the docs on forms for more information.
Also, as #TheShiftExchange says, its a bit odd to be using the base 64 encoded id, why not just use the raw id?

Related

Laravel route not defined error when it is clearly defined

I am trying to handle a basic form with laravel and am running in to an issue where my POST route isn't being detected and is resulting in a route not defined error in the blade template. My goal is to resolve this error and post the form to the controller, then access the various form fields with the $request param.
This is the error: Route [become-a-customer] not defined.
I appreciate any suggestions on how to resolve this.
Form
<form action="{{ route('become-a-customer') }}" method="post" class="col-md-8 offset-md-2">
<div class="form-row">
<div class="form-group col-md-6">
<label for="first_name">First Name</label>
<input name="last_name" type="email" class="form-control" id="first_name" placeholder="First Name">
</div>
...
</div>
<input type="hidden" name="_token " value="{{ Session::token() }}"/>
<button type="submit" class="btn">SUBMIT</button>
</form>
web.php
Route::post('/become-a-customer', 'BecomeACustomerFormController#postBecomeACustomer');
BecomeACustomerController . php
class BecomeACustomerFormController extends Controller
{
public function postBecomeACustomer(Request $request)
{
$firstName = $request['first_name'];
$lastName = $request['last_name'];
...
...
return redirect()->back();
}
}
Route::post('/become-a-customer', 'BecomeACustomerFormController#postBecomeACustomer')->name('become-a-customer');
use this command
php artisan optimize
In Your blade Template, You have used the Named route for the form action but, it is not specified in the route file (Web.php).
Change your route file like this
Route::post('/become-a-customer', 'BecomeACustomerFormController#postBecomeACustomer')->name('become-a-customer');
OR, you have to change the form action like this
action="{{ url('become-a-customer') }}"
Using the named route is the best practice for a Laravel project.
you can also define as following where "as" key is for naming your route
Route::post('/become-a-customer', ['uses' => 'BecomeACustomerFormController#postBecomeACustomer', 'as' => 'become-a-customer']);
Check your Apache or Nginx configurations. Sometimes a redirect from https to http will alter the method from POST to GET.
I'd recommend setting up a temporary endpoint for GET by the same Route and placing a dd() statement in it to test the theory.
route() method uses route name which is undefined. You can define it via name() method on route as below
Route::post('/become-a-customer', 'BecomeACustomerFormController#postBecomeACustomer')->name('become-a-customer');
for more see doucmentation
For me url('routeName') worked instead of route('routeName')

How to set default value in laravel collective form

i'm fetching data from database and want to make dropdown list with one value selected by default
i tried this
Laravel-5 how to populate select box from database with id value and name value
but nothing happen
my view file:
<div class="row">
<!-- Country ID Field -->
<div class="form-group col-sm-6">
{!! Form::label('country_id', 'Country ID:') !!}
{!! Form::select('country_id',$countries, isset($user) ? $user->country_id : 'Nepal', ['class' => 'form-control']) !!}
</div>
i'm new to laravel-collective..please help :)
The Laravel Collective code is really helpful... but it is also buggy in some odd ways.
There is an automatic binding that you can take advantage of by using null in the Collective select() constructor:
<div class="row">
<div class="form-group col-sm-6">
{!! Form::label('country_id', 'Country ID:') !!}
{!! Form::select('country_id',$countries, null, ['class' => 'form-control']) !!}
</div>
This is usually really good if you use form-model binding on the forms. However, there may be cases when it doesn't pick up the user model. If so, you were correct with your original code. BUT, for some reason, Collective occasionally reads the isset section better when the isset block is within parenthesis:
<div class="row">
<div class="form-group col-sm-6">
{!! Form::label('country_id', 'Country ID:') !!}
{!! Form::select('country_id',$countries, (isset($user) ? $user->country_id : 'Nepal'), ['class' => 'form-control']) !!}
</div>
Try either of these - hopefully one will help you.
The other potential item to check is to make sure your $countries are set and contain some ids, INCLUDING the id for the $user->country_id. If the user's country is not in the $countries list, it will not work even if the user's id is set.
This is bit broader than the original question about <select> inputs, but note Laravel Collective also has form model binding using the model() method, so if you were using multiple fields from your 'country' model, to use this example, you don't need to specify $countries as an argument for every input, just once at the beginning.
Instead of calling Form::open, you do:
{!! Form::model($countries, [
'method' => 'POST',
'url' => ['/admin/country'],
]) !!}
This is the cleanest implementation I've found, because can also use it for 'create' in a "CRUD" context; i.e. where you want to pass some default values to an otherwise empty form.
You create a new instance of your model (e.g. $country = new Country()) and set the relevant values, without calling ->save(), then use compact() to pass it to your view and call Form::model, as above, within that view.
This allows you to use the same view for creating and editing, without having to write conditionals to handle any defaults (and avoids the risk of accidentally adding a default value to an existing record if a user wipes a field).

understanding how laravel interprets blade form url?

I have the below form in a larvel view:
<div id="admin">
<h1>Products Admin Panel</h1><hr>
<p>Here you can view, delete, and create new products.</p>
<h2>Products</h2><hr>
<!--admin/fileupload/create-->
{{ Form::open(array('url'=>'admin/products/create' , 'files'=>true)) }}
<p>
{{ Form::file('image') }}
</p>
{{ Form::submit('Create Product' , array('class'=>'secondary-cart-btn')) }}
{{ Form::close() }}
</div> <!-- end admin -->
I am new to laravel and basically just want to understand , in the URL when i specify 'url'=>'admin/products/create' , what is laravel going to look for ?
a modal called products ? or a controller called products ? and a method getCreate or postCreate inside it ? what is admin then , i want to understand how laravel interprets this blade form url , can anybody explain ?
I want somebody to explain to me how does laravel interpret blade form url ?
In laravel,you will specify which url to be processed by which controller and by which method inside that controller.This specify must be do in routes.php file that is located in projectname/app/Http/routes.php .
When you specify the 'url'=>'admin/products/create' you must define the route in routes.php .
Route can be define in different ways like:
Route::get('admin/products/create','ProductController#crete');
Here you can use get or post according to your request.
Another way you can do is
Route::get('admin/products/create',array(
'as'=> 'create-product',
'uses'=>'ProductController#create'
));
Now , you can do like this route('create-product'); instead of 'url'=>'admin/products/create' .
Another way by using Route group
Route::group(['prefix'=>'admin'],function(){
Route::group(['prefix'=>'products'],function(){
Route::get('/create',array(
'as'=>'create-product',
'uses'=> 'ProductController#create'
));
// Here you can define other route that have the url like /admin/products/*
});
});
Now you can do like route('create-product') or 'url'=>'admin/products/create' Advantage
For more info check the documentation Here

MethodNotAllowedHttpException on resource defined method Laravel-4

I created a very simple form so that I could use a submit button rather than a link to open up an edit users page. Using a link works perfectly, but the form button fails and yields a MethodNotAllowedHttpException even though the method ("edit") is perfectly defined in the UsersController resource and otherwise works fine.
Route:
Route::resource('users','UsersController');
UsersController:
public function edit($id)
{
$user = $this->user->find($id);
return View::make('users.edit')->with('user',$user);
}
show.blade.php:
<!-- This works fine: -->
{{ link_to_route('users.edit', ("Edit: " .$user->first_name." ".$user->last_name), $user->id) }}
<!-- This doesn't work, and yields the Method Not Allowed exception: -->
{{ Form::open(array('route' => array('users.edit',$user->id))) }}
{{ Form::submit('Edit User', array('class'=>'button')) }}
{{ Form::close() }}
Thanks.
When you do Form::open(), it defaults to using the post request method. But when you create a Route::resource(), the edit method takes a get request.
To make it work through the form, you'll need to open it with an additional parameter, like this:
{{ Form::open(array('route' => array('users.edit',$user->id),
'method' => 'get')) }}
You need to point to the update route, not edit.
{{ Form::open(array('route' => array('users.update', $user->id))) }}
The edit route is for displaying the view, while the update is for the put/patch request.
For more information about using the RESTful routes, I'd recommend checking out http://laravel.com/docs/controllers#resource-controllers

Laravel 4 - Multiple forms on same page?

I'm having some strange behavior with my forms in Laravel 4. I have a "settings" page with two forms, each (are supposed to) POST to a controller method, update the database and return back to the settings page. However, there seems to be an issue, either with the way my forms are working or my routes.
Here's how it is, simplified:
Settings page: (site.com/settings)
<div id="form-one" class="form-area">
{{ Form::open(array('action' => 'SettingController#editOption')) }}
{{ Form::text('optionvalue', 'Default')) }}
{{ Form::submit('Save Changes') }}
{{ Form::close() }}
</div>
<div id="form-two" class="form-area">
{{ Form::open(array('action' => 'SettingController#editPage')) }}
{{ Form::text('pagevalue', 'Default')) }}
{{ Form::submit('Save Changes') }}
{{ Form::close() }}
</div>
So basically, two seperate forms on the same page that post to two seperate methods in the same Controller - when the method is successful, it redirects them back to "settings". I won't post the methods, since tested them and they work, I believe the problem is in the routes file:
routes.php
// Checks if a session is active
Route::group(array('before' => 'require_login'), function()
{
Route::group(array('prefix' => 'settings'), function()
{
Route::get('/', 'SettingController#index');
Route::post('/', 'SettingController#editOption');
Route::post('/', 'SettingController#editPage');
});
});
Now I'm pretty sure it doesn't like the two POST routes being like that, however I cannot think of another way to do it, since the forms are on the same page. I get the error:
Unknown action [SettingController#editOption].
Since the option form comes first I guess. If I take the open form blade code out (for both), it loads the page - but obviously the form doesn't do anything.
Any help would be nice! Thanks in advance.
You can't add two same routes for different actions, because of they will be passed to first matched route and in your case to SettingController#editOption. Change your routes to :
Route::post('/option', 'SettingController#editOption');
Route::post('/page', 'SettingController#editPage');
Than in both actions you can redirect to '/': return Redirect::back(), and if error was occured:
if ($validation->fails())
{
return Redirect::to('/settings')->with_errors($validation);
}
My alternative solution for this is to create an hidden html input in each form and make the controller identify what for is submitted based in this field. So, yu can use just one route for both.

Categories