I am new to laravel and I am trying to use user model and controller doing singup => post after submitting the form I would like to get user info to store into users table, but I kept getting this error Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException from \laravel\framework\src\Illuminate\Routing\RouteCollection.php I am not sure what part I messed up, any suggestion would help. Thank you. :
// ====route
Route::get('/signup', 'UserController#getSignup');
Route::get('/login', 'UserController#getLogin' );
Route::resource('user', 'UserController');
// ====model
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
//====user migration table
public function up() {
Schema::create('users', function($table) {
$table->increments('id');
$table->string('email')->unique();
$table->boolean('remember_token');
$table->string('password');
$table->timestamps();
});
}
//====userController
<?php
class UserController extends BaseController {
public function __construct() {
$this->beforeFilter('guest', array('only' => array('getLogin','getSignup')));
}
public function getSignup() {
return View::make('user_signup');
}
public function postSignup() {
# Step 1) Define the rules
$rules = array(
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6'
);
# Step 2)
$validator = Validator::make(Input::all(), $rules);
# Step 3
if($validator->fails()) {
return Redirect::to('/signup')
->with('flash_message', 'Sign up failed; please fix the errors listed below.')
->withInput()
->withErrors($validator);
}
$user = new User;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
try {
$user->save();
}
catch (Exception $e) {
return Redirect::to('/signup')
->with('flash_message', 'Sign up failed; please try again.')
->withInput();
}
# Log in
Auth::login($user);
return Redirect::to('/list')->with('flash_message', 'Welcome to Foobooks!');
}
public function getLogin() {
return View::make('user_login');
}
public function postLogin() {
$credentials = Input::only('email', 'password');
if (Auth::attempt($credentials, $remember = true)) {
return Redirect::intended('/')->with('flash_message', 'Welcome Back!');
}
else {
return Redirect::to('/login')
->with('flash_message', 'Log in failed; please try again.')
->withInput();
}
return Redirect::to('login');
}
public function getLogout() {
# Log out
Auth::logout();
# Send them to the homepage
return Redirect::to('/');
}
}
//=====user_signup.blade.php
#extends('_master')
#section('title')
Sign up
#stop
#section('content')
<h1>Sign up</h1>
#foreach($errors->all() as $message)
<div class='error'>{{ $message }}</div>
#endforeach
{{ Form::open(array('url' => '/signup')) }}
Email<br>
{{ Form::text('email') }}<br><br>
Password:<br>
{{ Form::password('password') }}<br>
<small>Min: 6</small><br><br>
{{ Form::submit('Submit') }}
{{ Form::close() }}
#stop
'MethodNotAllowedHttpException' means that the route that is being hit isnt set up for the http type that has been sent.
So for /signup, you allow a GET request but your form is using POST to send data to it. Make a route that accepts POST to use the relevant controller and method.
Route::post('/signup', 'UserController#postSignup');
Edit:
Ah, I think it may be Route::resource('user', 'UserController') that's causing the problem. Laravel Docs says that ::resource('user', 'UserController') should have restful actions in your controller like UserController#index, UserController#create, UserController#store, etc.
Your controller can be autopopulated with the relevant actions using 'php artisan controller:make UserController' Note: this may delete what you currently have in place
If you're not utilising Route::resource to handle requests though, go ahead and remove it.
Related
At the most basic of understanding, I've been trying to match the route and the form action. I think that I am doing it right but I wonder why does the error keeps on showing ? I may have missed something anywhere but I just really couldn't find it. Please help. In a very tight schedule, I need to complete this project by tuesday
P.S : when i submit the form it goes to this address http://127.0.0.1:8000/profile/edit/1 .
Form
<x-layout>
<x-setting heading="Edit Staff Profile">
<div class="flex flex-col">
<form method="POST" action="/profile/edit/{{$profil->id}}" enctype="multipart/form-data">
#csrf
<div class="mb-6">
<label class="block mb-2 uppercase font-bold text-sm text-gray-700" for="images">
Profile photo
</label>
<input type="file" name="images">
</div>
Route
Route::get('profile', [UserController::class, 'index'])->middleware('auth')->name('profile');
Route::get('profile/edit/{id}', [UserController::class, 'show'])->middleware('auth');
Route::post('profile/edit/{id}', [UserController::class, 'update'])->middleware('auth');
UserController
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Profile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function index()
{
$id = Auth::user()->id;
$info = User::where('id', $id)->first();
return view('profile', compact('info'));
}
// public function create()
// {
// return view('staffrecord.create');
// }
public function store()
{
$attributes = request()->validate([
'name' => 'required|max:255',
'username' => 'required|min:3|max:255|unique:users,username',
'email' => 'required|email|max:255|unique:users,email',
'password' => 'required|min:7|max:255',
]);
if (auth()->attempt($attributes)) {
return redirect('/')->with('success', 'Your account has been created.');
}
return redirect('/profile')->with('errors', 'Authentication failed.');
}
public function show($id)
{
$profil = User::findOrFail($id);
return view('staffrecord.edit', compact('profil'));
}
public function edit()
{
$id = Auth::user()->id;
$profil = Profile::findOrFail($id);
return view('staffrecord.edit', compact('profil'));
}
public function update(Request $request, $id)
{
$data = Profile::findOrFail($id);
$data->staff_id = $request->staff_id;
$data->name = $request->name;
$data->gender = $request->gender;
$data->address = $request->address;
$data->email = $request->email;
$data->phonenumber = $request->phonenumber;
$data->department = $request->department;
$data->save();
return redirect('/')->route('profile');
}
}
A user may has his logins but they may not have setup their profiles so when you do such request profile find will fail and return to 404 error.
Also to make a note ALWAYS use foreign keys in Profile table linking to user id it's not necessary that a user->id say 1 will have profile->id 1.
in User model add this function:
public function profile() {
return $this->hasOne('App\Models\Profile');
}
Then load user profile in update function of controller like:
public function update(Request $request, $id){
$user = User::with('profile')->findOrFail($id);
if (is_null($user->profile){ echo 'user don't has profile'; }
//Update profile from within
$user->profile()->updateOrCreate([$request->all()]);
//NOTE request->all is not safe
}
use updateOrCreate() for in case user does not have a profile.
I always name my routes:
Route::post('profile/edit/{id}', [UserController::class, 'update'])->name('user.update')-> middleware('auth')
Then form action looks like this:
<form method="POST" action="{{route('user.update', ['id' =>$profil->id]) }}"
This way 'id' defined in route will be easier to be identified.
Naming routes and using route() may save you some headaches when moving to production.
This question already has answers here:
Laravel blank white screen
(35 answers)
Closed 6 years ago.
I have this view page index.blade.php
#section('main')
<h1>All Users</h1>
<p><a href={!! url('users\create') !!}>Add new user</a></p>
#if ($users->count())
<table border="2">
<tr><td>s.n.</td><td>name</td><td>email</td><td>options</td>
#foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td><a href={{ url('users\{id}\edit', $user->id)}}>Edit</a>
<td>
{!! Form::open(array('method' => 'DELETE',
'route' => array('users.destroy', $user->id))) !!}
{!! Form::submit('Delete', array('class' => 'btn btn-danger')) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
</table>
#else
There are no users
#endif
#stop
and controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
class usercontroller extends Controller
{
public function index()
{
$users=User::all();
return view('users.index', compact('users'));
}
public function create()
{
return View('users.create');
}
public function store()
{
$input = Input::all();
$validation = Validator::make($input, User::$rules);
if ($validation->passes())
{
User::create($input);
return Redirect::route('users.index');
}
return Redirect::route('users.create')
->withInput()
->withErrors($validation)
->with('message', 'There were validation errors.');
}
public function show($id)
{
//
}
public function edit($id)
{
$user = User::find($id);
if (is_null($user))
{
return Redirect::route('users.index');
}
return View('users.edit', compact('user'));
}
public function update($id)
{
$input = Input::all();
$validation = Validator::make($input, User::$rules);
if ($validation->passes())
{
$user = User::find($id);
$user->update($input);
return Redirect::route('users.show', $id);
}
return Redirect::route('users.edit', $id)
->withInput()
->withErrors($validation)
->with('message', 'There were validation errors.');
}
public function destroy($id)
{
User::find($id)->delete();
return Redirect::route('users.index');
}
}
and
routes.php
Route::resource('users', 'UserController');
but when i enter laravel/public/users it displays the white blank page. same problem with any other routes such as:
Route::get('/users/edit/{id}','UserController#edit');
Route::put('/users/{id}','UserController#update');
Route::delete('/users/{id}','UserController#delete');
the problem occurred when i follow these steps https://laravelcollective.com/docs/5.2/html to use forms.
. earlier the error was 'class form' not found.
the app/User.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
class User extends BaseModel
{
protected $primarykey='id';
protected $table='users';
protected $fillable=array('name','email','password');
public static $rules = array(
'name' => 'required|min:5',
'email' => 'required|email'
);
}
and basemodel
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
class BaseModel extends Model {
public function selectQuery($sql_stmt) {
return DB::select($sql_stmt);
}
public function sqlStatement($sql_stmt) {
DB::statement($sql_stmt);
}
}
at first change your controller file name app/Http/Controller/usercontroller.php to app/Http/Controller/UserController.php.then in UserController.php you edit your class name like below:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
class UserController extends Controller
Then make sure that you have a model name app/User.php which contains all the table field and table name.In app/Http/routes.php you set another route
Route::get('users','UserController#index');
then you can enter laravel/public/users
I am new to PHP and Laravel. I am making a Laravel login app which prints "success" after comparing the entered value and database value.
My problem is: when both value are matched it prints "success" but when they are not matched it shows ModelNotFoundException .
I have created an exception for this but again same error occurs.
Thank you in advance!
Here is my route.php code
route.php
Route::get('register', 'RegisterController#register');
Route::post('register/show', 'RegisterController#show');
Route::post('register/store', 'RegisterController#store');
Route::get('register/login', 'RegisterController#login');
Here is my register controller which get value from index.blade.php and from database named registers which has two columns username and password
RegisterController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Register;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Request;
class RegisterController extends Controller {
public function register()
{
return view('register.index');
}
public function store()
{
$input = Request::all();
Register::create($input);
return redirect('register');
}
public function show()
{
try
{
$result2 = Request::get('username');
$result = Register::where('username', $result2)->firstOrFail();
return view('register.show', compact('result','result2'));
}
catch(ModelNotFoundException $e)
{
return "login fail" . redirect('register/login');
}
}
public function login()
{
return view('register.login');
}
}
Register.php
use Illuminate\Database\Eloquent\Model;
class Register extends Model {
protected $fillable = ['username', 'password'];
}
CreateRegistersTable
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRegistersTable extends Migration {
public function up()
{
Schema::create('registers', function(Blueprint $table)
{
$table->increments('id');
$table->string('username');
$table->string('password');
$table->timestamps();
});
}
public function down()
{
Schema::drop('registers');
}
}
index.blade.php
#extends('master')
#section('login')
{!! Form::open(['url' => 'register/store']) !!}
{!!Form::label('username','Name:')!!}
{!!Form::text('username', null)!!}
<br>
{!!Form::label('password','Password:')!!}
{!!Form::text('password', null)!!}
{!!Form::submit('submit')!!}
{!! Form::close() !!}
#stop
login.blade.php
#extends('master')
#section('register')
{!! Form::open(['url' => 'register/show']) !!}
{!!Form::label('username','Name:')!!}
{!!Form::text('username', null)!!}
<br>
{!!Form::label('password','Password:')!!}
{!!Form::text('password', null)!!}
{!!Form::submit('submit')!!}
{!! Form::close() !!}
#stop
** show.blade.php **
#extends('master')
#section('show')
<?php
if( $result->username == $result2 )
{
echo "success";
}
?>
#stop
Have you added the error trapping logic to your app/Exceptions/Handler.php file?
Check out http://laravel.com/docs/5.0/eloquent ; specifically where it states:
Retrieving A Model By Primary Key Or Throw An Exception
Sometimes you may wish to throw an exception if a model is not found. To do this, you may use the firstOrFail method:
$model = User::findOrFail(1);
$model = User::where('votes', '>', 100)->firstOrFail();
Doing this will let you catch the exception so you can log and display an error page as necessary. To catch the ModelNotFoundException, add some logic to your app/Exceptions/Handler.php file.
use Illuminate\Database\Eloquent\ModelNotFoundException;
class Handler extends ExceptionHandler {
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException)
{
// Custom logic for model not found...
}
return parent::render($request, $e);
}
}
I am following along with the "Build Larabook from Scratch" series on Laracasts
I have checked the code over and over but can't find my error.
I am able to register a user and so Auth::login($user) works, but I cannot get Auth::attempt() to work.
I have tried the following (and much more). I cannot figure it out.
moving Users back to app/models
using a simpler User model (standard)
gone over the videos 3 times trying to identify if I mad ea mistake
turned filters on and off
hashing the password and not hashing them before
How can I debug this problem?! I want to know WHY Auth::attempt() failed!!
Please help!
My Route for Login
Route::post('login', [
'as' => 'login_path',
'uses' => 'SessionsController#store'
]);
My SessionsController constructor() and store() methods [Logging is temporary to try to solve this problem]
public function __construct(SignInForm $signInForm) {
$this->signInForm = $signInForm;
$this->beforeFilter('guest', ['except' => 'destroy']);
}
public function store() {
$input = Input::only('email', 'password');
Log::info('User tried to login with email => ' . Input::get('email') . ' and password => ' . Input::get('password'));
$this->signInForm->validate($input);
$info = [
'email' => Input::get('email'),
'password' => Input::get('password')
];
if (Auth::attempt($info)) {
Log::info('AUTH ATTEMPT was successful');
// Add flash message "Welcome Back"
return Redirect::intended('/statuses');
} else {
Log::info('AUTH ATTEMPT failed');
return Redirect::to('login');
}
}
My SignInForm.php
namespace Fujibook\Forms;
use Laracasts\Validation\FormValidator;
class SignInForm extends FormValidator {
/**
*Validation rules for the registration form
* #var type
*/
protected $rules = [
'email' => 'required',
'password' => 'required'
];
}
My create.blade.php
<h1>Sign In</h1>
{{ Form::open(['route' => 'login_path']) }}
<div class="form-group">
{{ Form::label('email', 'Email:') }}
{{ Form::email('email', null, ['class' => 'form-control', 'required' => 'required']) }}
</div>
<div class="form-group">
{{ Form::label('password', 'Password:') }}
{{ Form::password('password', null, ['class' => 'form-control', 'required' => 'required']) }}
</div>
<div class="form-group">
{{ Form::submit('Sign In', ['class' => 'btn btn-primary']) }}
</div>
{{ Form::close() }}
Finally, my User Model \Fujibook\Users
<?php
namespace Fujibook\Users;
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use Fujibook\Registration\Events\UserRegistered;
use Laracasts\Commander\Events\EventGenerator;
use Eloquent, Hash;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait,
RemindableTrait,
EventGenerator;
/**
* Which fileds that may be massassigned
*
* #var type
*/
protected $fillable = ['username', 'email', 'password'];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
/**
* Passwords must always be used;
* #param type $password
*/
public function setPasswordAttribute($password){
$this->attributes['password'] = Hash::make($password);
}
public function getAuthIdentifier() {
return $this->getKey();
}
public function getAuthPassword() {
return $this->password;
}
/**
* Register a new user
* #param type $username
* #param type $email
* #param type $password
*/
public static function register($username, $email, $password) {
$user = new static(
compact('username', 'email', 'password')
);
// raise an event
$user->raise(new UserRegistered($user));
return $user;
}
}
Additionally, I have set the model in the model in app/config/auth.php
'model' => 'Fujibook\Users\User',
And I might as well include my DB migration
public function up() {
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password', 70);
$table->timestamps();
$table->rememberToken();
});
}
Well firstly you don't need to use Input::get() again to get the email and password. What is the field in the database called, username or email? I'd imagine email, if so, change the login code to look like this:
public function store() {
$input = Input::only('email', 'password');
Log::info('User tried to login with email => ' . Input::get('email') . ' and password => ' . Input::get('password'));
$this->signInForm->validate($input);
if (Auth::attempt($input)) {
Log::info('AUTH ATTEMPT was successful');
// Add flash message "Welcome Back"
return Redirect::intended('/statuses');
} else {
Log::info('AUTH ATTEMPT failed');
return Redirect::to('login');
}
}
The problem I'm seeing is just this
$info = [
'username' => Input::get('email'), <--- username = email???
'password' => Input::get('password')
];
if (Auth::attempt($info)) {
Shouldn't it be like:
$info = [ 'email' => Input::get('email'), 'password' => Input::get('password') ];
I am doing a project for school and I need more than one user type : User, Registrar and Teacher.
I followed Laravel documentation and got the user working perfectly (login/register).
Then I tried adding another user: Registrar. I got the registration working and it's even adding the user in the "registrar" table.
But when I'm trying to log in it is using the "users" table, not the "registrar" one, and giving me a controller method "not found" error.
Model: Registrar.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Registrar extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'registrar';
protected $hidden = array('password');
public function getAuthIdentifier() {
return $this->getKey();
}
public function getAuthPassword() {
return $this->password;
}
}
Routes:
Route::get('/', array('uses' => 'HomeController#AuthenticateUser'));
Route::get('/student/member', array('uses' => 'UsersController#getStudent'));
Route::get('logout', array('uses' => 'UsersController#doLogout'));
Route::controller('users', 'UsersController');
Route::controller('password', 'RemindersController');
Route::controller('registrar', 'RegistrarController');
Route::get('/registrar/member', array('uses' => 'RegistrarController#getRegistrar'));
RegistrarController, Sign-In method:
public function postSignin() {
if (Auth::attempt(array('email'=>Input::get('login_input')) {
return Redirect::to('registrar/member')->with('status', 'You are now logged in!');
} else {
return Redirect::to('registrar/login')
->with('error', 'Your username/password combination was incorrect')
->withInput();
}
}
Other functions inside:
class RegistrarController extends BaseController {
public function __construct() {
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth', array('only'=>array('getRegistrar')));
}
public function getRegister() {
return View::make('registrar.register');
}
public function getRegistrar() {
return View::make('registrar.member');
}
login.blade.php
{{ Form::open(array('url'=>'registrar/signin', 'class'=>'form-signin' , 'id'=>'login-form')) }}
.
.
.
.
-- form close--
I'm wondering if this line is not the problem in the signin function:
if (Auth::attempt(array('email'=>Input::get('login_input')) {
return Redirect::to('registrar/member')->with('status', 'You are now logged in!')
As I'm not sure how the system checks which database table to use, or its default on the "users".
You can do this to swap the model during runtime:
$provider = new \Illuminate\Auth\EloquentUserProvider(app('hash'), 'Registrar');
Auth::setProvider($provider);