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.
Related
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.
I am making a multiple inputs search query and i need help cause i do not know how to exactly to do this i have read all the documentation and i did not understand it.Now i am stuck in the controller.....
Also i would really appreciate of how to call the informations that i want in in the show.blade ! Thank you for any help !
Index blade
<div class="panel-body">
<div class="form-group">
<div><h4></h4></div>
<div class="form-group col-md-4">
{{ Form::open(array('action' => array('UserController#search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
<div id="prefetch">
{{ Form::text('name', null, array('class' => 'typeahead form-group form-control', 'placeholder' => 'name...')) }}
{{ Form::text('lastname', null, array('class' => 'form-group form-control', 'placeholder' => 'lastname...')) }}
{{-- {{ Form::text('id', null, array('class' => 'form-group form-control', 'placeholder' => 'id...')) }}
{{ Form::text('user-seminars', null, array('class' => 'form-group form-control', 'placeholder' => 'Class tha is enrolled...')) }}
{{ Form::text('user-class', null, array('class' => 'form-group form-control', 'placeholder' => 'Class that belongs...')) }}
{{ Form::text('user-annex', null, array('class' => 'form-group form-control', 'placeholder' => 'Department that belongs...')) }}
{{ Form::text('type', null, array('class' => 'form-group form-control', 'placeholder' => 'User type...')) }}
{{ Form::text('date_created', null, array('class' => 'form-group form-control', 'placeholder' => 'date created account...')) }}
{{ Form::text('date_enrolled', null, array('class' => 'form-group form-control', 'placeholder' => 'date enrolled in class...')) }}
routes
Route::get('users/index', 'UserController#index');
Route::get('users/search', 'UserController#search');
Route::get('users/show', 'UserController#show');
UserContoller
public function index(){
return View::make('user.index');
}
public function search(){
return View::make('user.show');
}
public function show(){
return View::make('user.show');
}
USERS TABLE
id , firstname,last_name,etc etc etc
public function search(Request $request){
$users = App\User::where('firstname',$request->name)
->orWhere('lastname',$request->lastname)
->orWhere('id',$request->id)
// more orWhere Clause
->get();
return View::make('user.show',compact('users'));
}
public function show($id){
$user = App\User::find($id);
return View::make('user.show',compact('user'));
}
Why are you using return View::make('user.show') to render two different resources?
the first thing i see its the form action
your code
{{ Form::open(array('action' => array('UserController#search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
should be
{{ Form::open(array('action' => array('users/search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
the controller is the fun part. if you're looking for all the inputs to be required you should validate it first
//first we set the inputs rultes
$data = Input::all();
$rules = array(
'name' => 'required',
'lastname' => 'required',
//rest of the inputs that are required
);
//then we use the validator method
$val = Validator::make($data,$rules);
if($val->fails())
{
/*redirect to the form again, you can set errors with session
or ->withError($validator)*/
return Redirect::back();
}
then you make your query
$user = User::where('name','=',$data['name'])
->where('lastname','=',$data['lastname'])
//more where('field','=','value')
->get();
if the fields arent required you only make the query with
$user = User::where('name','=',$data['name'])
->orWhere('lastname','=',$data['lastname'])
//more orWhere('field','=','value')
->get();
and finally you return your result to the view like:
return View::make('user.show')->with('user',$user);
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.
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'
));
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))) }}