Laravel 4 - Controller method not found - laravel

I want to modify an user from the list. I have the codes in the routes.php:
Route::get('users/{all}/edit', 'UserController#getEdit');
Route::post('users/update', ['as' => 'users.postUpdate', 'uses' => 'UserController#postUpdate']);
Route::controller('users', 'UserController');
In the UserController.php, I wrote the following script for edit and update:
public function getEdit($id)
{
//
$user = User::find($id);
if (is_null($user))
{
return Redirect::to('users/all');
}
return View::make('users.edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function postUpdate($id)
{
//
$input = Input::all();
$validation = Validator::make($input, User::$rules);
if ($validation->passes())
{
//$user = User::find($id);
$user = User::find($id);
$user->username = Input::get('username');
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->phone = Input::get('phone');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::route('users.getIndex', $id);
}
return Redirect::route('users.getEdit', $id)
->withInput()
->withErrors($validation)
->with('message', 'There were validation errors.');
}
The code under edit.blade.php as below:
#extends('users.user')
#section('main')
<h1>Edit User</h1>
{{ Form::model($user, array('method' => 'PATCH', 'route' => array('users.postUpdate', $user->id))) }}
<ul>
<li>
{{ Form::label('username', 'Username:') }}
{{ Form::text('username') }}
</li>
<li>
{{ Form::label('password', 'Password:') }}
{{ Form::text('password') }}
</li>
<li>
{{ Form::label('email', 'Email:') }}
{{ Form::text('email') }}
</li>
<li>
{{ Form::label('phone', 'Phone:') }}
{{ Form::text('phone') }}
</li>
<li>
{{ Form::label('name', 'Name:') }}
{{ Form::text('name') }}
</li>
<li>
{{ Form::submit('Update', array('class' => 'btn btn-info')) }}
{{ link_to_route('users.getAll', 'Cancel', $user->id, array('class' => 'btn')) }}
</li>
</ul>
{{ Form::close() }}
#if ($errors->any())
<ul>
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</ul>
#endif
#stop
The edit screen is opening well. However, when modify the values and submit the form, the URL shows as http://localhost/testlaravell/users/update?5 and the error occurs that -
Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException
Controller method not found.
Please help me how can I solve this issue.

The problem here is that you use PATCH method but in Controller you have method postUpdate (and same for routes.php).
What you should probably do is:
changing in controller method postUpdate to putUpdate
changing
Route::post('users/update', ['as' => 'users.postUpdate', 'uses' => 'UserController#postUpdate']);
into
Route::put('users/update/{id}', ['as' => 'users.putUpdate', 'uses' => 'UserController#putUpdate']);
changing in your form
{{ Form::model($user, array('method' => 'PATCH', 'route' => array('users.postUpdate', $user->id))) }
into
{{ Form::model($user, array('method' => 'PUT', 'route' => array('users.putUpdate', $user->id))) }

Define your route like this:
Route::resource('users', 'UsersController');
Change it:
{{ Form::model($user, array('method' => 'PATCH', 'route' => array('users.postUpdate', $user->id))) }}
to
{!! Form::model($user, array('method' => 'PATCH', 'route' => array('users.update', $user->id))) !!}
Write your controller like this:
public function edit($id)
{
$user = User::find($id);
if (is_null($user))
{
return Redirect::to('users/all');
}
return View::make('users.edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$input = Input::all();
$validation = Validator::make($input, User::$rules);
if ($validation->passes())
{
$user = User::find($id);
$user->username = Input::get('username');
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->phone = Input::get('phone');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::route('users.getIndex', $id);
}
return Redirect::route('users.getEdit', $id)
->withInput()
->withErrors($validation)
->with('message', 'There were validation errors.');
}
Hope, it'll works.

Related

Laravel 5.3 - Blade not working

When I try to load my project on web browser. It shows header and footer, but the middle section containing form is missing, and I don't understand what am I doing wrong?
views/welcome.blade:
<!DOCTYPE html>
<html lang="en">
<head>
#include('partials._head')
</head>
<body>
#include('partials._nav')
<div class="container">
#include('partials._messages')
#yield('content')
#include('partials._footer')
</div>
#include('partials._javascript')
</body>
</html>
views/user_auth/user_register.blade:
#extends('welcome')
#section('title')
Welcome!!
#endsection
#section('content')
{!! Form::open(['route' => 'signup']) !!}
{{ Form::label('user_name','Name:') }}
{{ Form::text('user_name',null,['class' => 'form-control']) }}
{{ Form::label('email','E-mail:') }}
{{ Form::text('email',null,['class' => 'form-control']) }}
{{ Form::label('mobile_num','Mobile No.:') }}
{{ Form::text('mobile_num',null,['class' => 'form-control']) }}
{{ Form::label('address','Address:') }}
{{ Form::text('address',null,['class' => 'form-control']) }}
{{ Form::label('state','State:') }}
{{ Form::text('state',null,['class' => 'form-control']) }}
{{ Form::label('city','City:') }}
{{ Form::text('city',null,['class' => 'form-control']) }}
{{ Form::label('district','District:') }}
{{ Form::text('district',null,['class' => 'form-control']) }}
{{ Form::submit('Register',array('class' => 'btn btn-success btn-lg btn- block form-spacing-top')) }}
{!! Form::close() !!}
#endsection
RegisterController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
public function getRegistrationPage()
{
return view('user_auth.user_register');
}
public function postSignUp(Request $request)
{
$this -> validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:20',
'mobile_num' => 'required|digits:10',
'address' => 'required',
'city' => 'required',
'district' => 'required',
'state' => 'required',
'password' => 'required|min:4'
]);
$email = $request['email'];
$name = $request['name'];
$mobile_num = $request['mobile_num'];
$address = $request['address'];
$city = $request['city'];
$district = $request['district'];
$state = $request['state'];
$password = bcrypt($request['password']);
$user = new User();
$user->email =$email;
$user->name = $name;
$user->mobile_num = $mobile_num;
$user->address = $address;
$user->city = $city;
$user->district = $district;
$user->state = $state;
$user->password = $password;
$user->save();
return redirect()->route('dashboard');
Auth::login($user);
}
public function postSignIn(Request $request)
{
$this -> validate($request,[
'mobile_num' => 'required',
'password' => 'required'
]);
if(Auth::attempt(['mobile_num' => $request['mobile_num'], 'password' => $request['password']])) {
return redirect()->route('dashboard');
}
return redirect()->back();
}
public function getDashboard()
{
return view('pages.dashboard');
}
}
routes/web.php :
Route::group(['middleware' => ['web']], function(){
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::post('/signup',[
'uses' => 'RegisterController#postSignUp',
'as' => 'signup'
]);
Route::post('/signin',[
'uses' => 'RegisterController#postSignIn',
'as' => 'signin'
]);
Route::get('/dashboard',[
'uses' => 'RegisterController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
Route::get('/register',[
'uses' => 'RegisterController#getRegistrationPage',
'as' => 'register',
'middleware' => 'auth'
]);
});
You need to return user_register view which should extend layout (in this case it called welcome):
#extends('welcome')
Or you can call welcome and include user_register view:
#include('user_auth.user_register')
It depends on what you want to achieve, but renaming welcome to layout and extending it looks like right solution here.
Also rename files to .blade.php, because now names are like welcome.blade instead of welcome.blade.php.
Your code is correct but Please check your route file Have you called user_register route?
You have set a welcome page as a layout file so When you will call welcome page it displays only header & footer file which you have included.

Laravel validation throwing route error

I am attempting a basic validation check on form fields in the controller. The code is below:
$validator = Validator::make(
array('email' => 'required|min:7'),
array('password' => 'required|min:7'),
array('firstName' => 'required'),
array('lastName' => 'required'));
if ($validator->fails())
{
// The given data did not pass validation
/*Get error msgs from validator*/
return Redirect::to('members.registration')->withErrors($validator);
}
The parameter passed to Redirect::to here is the folder members and registration view which resides in it. The problem is being caused by this line specifically:
return Redirect::to('members.registration')->withErrors($validator);
When it is commented out, form submission returns a blank white page. Otherwise the following error in the picture is shown
The route file has the following content:
Route::get('/', 'MainController#index');
Route::get('membersaccess', array('as' => 'membersaccess', 'uses' => 'MainController#loadMembersAccess'));
Route::get('signin', array('as' => 'signin', 'uses' => 'MembersController#loadlogin'));
Route::get('signup', array('as' => 'signup', 'uses' => 'MembersController#loadRegistration'));
Route::post('postLogin', array('as' => 'postLogin', 'uses' => 'MembersController#login'));
Route::post('postRegistration', array('as' => 'postRegistration', 'uses' => 'MembersController#registration'));
function containing the validation part is:
public function registration()
{
$email = Input::get('email');
$password = md5(Input::get('password'));
$firstName = Input::get('firstName');
$lastName = Input::get('lastName');
$country = Input::get('country');
//echo $email;
$validator = Validator::make(
array('email' => 'required|min:7'),
array('password' => 'required|min:7'),
array('firstName' => 'required'),
array('lastName' => 'required'));
if ($validator->fails())
{
// The given data did not pass validation
/*Get error msgs from validator*/
return Redirect::to('members.registration')->withErrors($validator);
}
}
and the form for reference:
#if(Session::has('errors'))
<? $errors = Session::get('errors'); ?>
<h3> {{ $errors->first('email') }}</h3>
#endif
{{ Form::open(array('route' => 'postRegistration')) }}
{{ Form::text('email', null, array('placeholder'=>'Email', 'class' => 'randomfieldsize' ) ) }}
{{ Form::password('password', array('placeholder'=>'Password', 'class'=>'randomfieldsize' ) ) }}
{{ Form::text('firstname', null, array('placeholder'=>'First Name', 'class' => 'randomfieldsize' ) ) }}
{{ Form::text('lastName', null, array('placeholder'=>'Last Name', 'class' => 'randomfieldsize' ) ) }}
{{ Form::select('country', array('' => '', 'saudi' => 'Saudi Arabia', 'uae' => 'UAE')) }} <br><br>
{{Form::submit('Proceed', ['class' => 'button [radius round]'])}}
{{ Form::close() }}
Try this:
return Redirect::route('signup')->withErrors($validator);
You have no route defined as members.registration, so that may be the problem.
To show errors I usually use this (styling with bootstrap):
#if( $errors->has() )
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<ul>
#foreach ( $errors->all('<li>:message</li>') as $error )
{{ $error }}
#endforeach
</ul>
</div>
#endif
Edit: Ugh, didn't noticed it before, but your validation code is wrong. Please refer to http://laravel.com/docs/validation It should be something like this:
$email = Input::get('email');
$password = Input::get('password'); // Better to hash the password in another place, since md5 can create a hash even of an empty string. Also, please use laravel hash utility instead of md5: http://laravel.com/docs/security#storing-passwords
$firstName = Input::get('firstName');
$lastName = Input::get('lastName');
$country = Input::get('country');
$validator = Validator::make(
compact('email', 'password', 'firstName', 'lastName', 'country'),
array(
'email' => 'required|min:7',
'password' => 'required|min:7'
'firstName' => 'required'
'lastName' => 'required'
));

Error when instantiating model

I am working on a project, using Laravel, and when I try to create a new model instance, I get 500 Internal Server Error. If I comment the "$user = new User;" line and then try redirecting to another page, it works, otherwise it just redirects me to /users and show me "Whoops, looks like something went wrong.".
This is my route:
Route::resource('users', 'UserController');
These are the create and store functions from the UserController:
public function create()
{
return View::make('register');
}
public function store()
{
$rules = array(
'name' => 'required',
'password' => 'required|confirmed',
'password_confirmation' => 'required',
'email' => 'required|email'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('users/create')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$user = new User; //The Error happens here
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
Session::flash('message', 'Successfully created user!');
return Redirect::to('users');
}
}
This is my view:
{{ HTML::ul($errors->all()) }}
{{ Form::open(array('url' => 'users')) }}
{{ Form::label('name', 'Name') }}
{{ Form::text('name', Input::old('name')) }}
<br>
{{ Form::label('password', 'Password') }}
{{ Form::password('password', Input::get('password')) }}
<br>
{{ Form::label('password_confirmation', 'Password Confirmation') }}
{{ Form::password('password_confirmation', Input::get('password_confirmation')) }}
<br>
{{ Form::label('email', 'Email') }}
{{ Form::text('email', Input::old('email')) }}
<br>
{{ Form::submit('Submit') }}
{{ Form::close() }}
And this is my model:
<?php
class User extends Eloquent{
public static $timestamps = false;
}
I would be glad if you could help me.

laravel Undefined offset: 0

I am trying to diplay an error mesasge in case the field selected is duplicated in db.For this I am using laravel validation required unique. I am having problem with redirect
Here is store controller
public function store() {
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id'),
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
// Validation has failed.
return Redirect::to('insur_docs/create')->with_input()->with_errors($validation);
} else {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
// redirect
return Redirect::to('/');
}
}
Here is the route
Route::get('insur_docs/create', array('as' => 'insur_docs.create','uses' => 'Insur_DocController#create'));
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_create.blade.php
<div id="div-1" class="body">
{{ Form::open(array('url' => 'insur_docs/store', 'class'=>'form-horizontal','id'=>'inline-validate')) }}
<div class="form-group">
{{ Form::label('ownership_cert', 'Ownership Certificate', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('ownership_cert', array('' => '', '1' => 'Yes', '0' => 'No'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid ownership certificate',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('authoriz', 'Authorization', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('authoriz', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid authorization date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('drive_permis', 'Drive Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('drive_permis', array('' => '', '1' => 'Active', '0' => 'Not active'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid drive permission',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('sgs', 'SGS', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('sgs', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid sgs date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('tpl', 'TPL', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('tpl', isset($v->sgs) ? $v->sgs : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid tpl date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('kasko', 'Kasko', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('kasko', isset($v->kasko) ? $v->kasko : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid kasko date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('inter_permis', 'International Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('inter_permis', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid international permission date',
'class' => 'form-control'))
}}
</div>
</div>
<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'))
}}
{{ $errors->first('car') }}
</div>
</div>
{{ Form::submit('Save', array('class' => 'btn btn-success btn-line')) }}
<input type="button" value="Back" class="btn btn-danger btn-line" onClick="history.go(-1);
return true;">
<div>
#foreach($errors as $error)
<li>{{$error}}</li>
#endforeach
</div>
{{ Form::close() }}
I t displays this error :
Undefined offset: 0
It might be that you are using a get, using post might help. Other than that you are mixing model and controller code. It's always a good idea to seperate these. For instance your redirects should be done inside the controller and not in the model.
http://laravel.com/docs/validation
http://laravelbook.com/laravel-input-validation/
http://culttt.com/2013/07/29/creating-laravel-4-validation-services/
It's also better to do stuff on $validator->passes() and then else return with errors.
Controller
public function store() {
$data = [
"errors" => null
];
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id')
);
$validation = Validator::make(Input::all(), $rules);
if($validation->passes()) {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
return Redirect::to('/');
} else {
$data['errors'] = $validation->errors();
return View::make('pages.insur_docs_create', $data);
}
}
Your errors will be available in your view under $errors. Just do a {{var_dump($errors)}} in your blade template to verify that they are there.
View
#if($errors->count() > 0)
<p>The following errors have occurred:</p>
<ul>
#foreach($errors->all() as $message)
<li>{{$message}}</li>
#endforeach
</ul>
#endif
I Think this is a really better answer from this refrenece
Laravel 4, ->withInput(); = Undefined offset: 0
withInput() doesn't work the way you think it does. It's only a function of Redirect, not View.
Calling withInput($data) on View has a completely different effect; it passes the following key value pair to your view: 'input' => $data (you get an error because you're not passing any data to the function)
To get the effect that you want, call Input::flash() before making your view, instead of calling withInput(). This should allow you to use the Input::old() function in your view to access the data.
Alternatively, you could simply pass Input::all() to your view, and use the input[] array in your view:
View::make(...)->withInput(Input::all());
which is translated to
View::make(...)->with('input', Input::all());
As for your comment, I recommend doing it like so:
$position_options = DB::table('jposition')->lists('friendly','id');
$category_options = DB::table('jcategory')->lists('friendly','id');
$location_options = DB::table('jlocation')->lists('friendly','id');
$category = Input::get('category');
$location = Input::get('location');
$type = Input:: get('type');
$data = compact('position_options', 'category_options', 'location_options', 'category', 'type', 'location');
return View::make('jobsearch.search', $data);
also thinks about laravel resource controller. because when we call no parameter get method, it redirects to the show method with ignoring our function name.
eg:-Route::get('hasith', 'Order\OrderController#hasith');----->
this parameter rederect to this function
public function show($id, Request $request) {
//code
}

Laravel 4: Route::post return URL with model name in brackets instead of id

I am building a post/comment system, with the comment form inside the post view. So, when I'm watching a post in the url http://example.dev/post/1 and click on the form submit buttom the url goes to http://example.dev/post/%7Bpost%7D where %7B = { and %7D = }).
I think the controller associated to the url post method doesn't even start.
My routes:
Route::model('post','Post');
Route::get('partido/{post}', 'FrontendController#viewPost');
Route::post('partido/{post}', array(
'before' => 'basicAuth',
'uses' => 'FrontendController#handleComment'
)
);
My viewPost controller:
public function viewPost(Post $post)
{
$comments = $post->comments()->get();
return View::make('post')
->with(compact('comments'))
->with(compact('posts'));
}
My handleComment controller:
public function handleComment(Post $post)
{
// Get the data
$data = Input::all();
// Build the rules
$rules = array(
'title' => 'required',
'description' => 'required',
);
// Error messages
$messages = array(
'title.required' => 'Title required.',
'description.required' => 'Description required.',
);
// Validator: He Comes, He sees, He decides
$validator = Validator::make($data, $rules, $messages);
if ($validator->passes()) {
// Save the new comment.
$comment = new Comment;
$comment->title = Input::get('title');
$comment->description = Input::get('description');
$post->comments()->save($comment);
return Redirect::to('post/'.$post->id.'');
}
else {
return Redirect::to('post/'.$post->id.'')->withErrors($validator);
}
}
And the form in the view:
{{ Form::open(array(
'action' => 'FrontendController#handleComment', $post->id
)) }}
<ul class="errors">
#foreach($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
{{ Form::label('title', 'Title')}}<br />
{{ Form::text('title', '', array('id' => 'title')) }}
<br />
{{ Form::label('description', 'Description')}}<br />
{{ Form::textarea('description', '', array('id' => 'description')) }}
<br />
{{ Form::submit('Submit') }}
{{ Form::close() }}
You need another array for the Form::open() - try this:
{{ Form::open(array('action' => array('FrontendController#handleComment', $post->id))) }}

Resources