How to get rid of bcrypt in laravel - php

The reason I would like to get rid of bcrypt(for the moment,while developing) is because I'm creating an admin android app and I'm connecting it to the database .I have been having issues when I create a user from the app ,they cannot login into the webiste.The bcrypt came with the Auth installation.
[![enter image description here][1]][1]
I have figured out that the issued that is causing this problem is bcrypt .I can't seemed to find a way to remove the .
I want to remove the website requiring the user to have their password being bcrypted
I have tried in RegisterController 'password' => bcrypt($data['password']) the bcrypt but that has not worked
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
This LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
This is my login.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Login</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
Web.php
<?php
//use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/test', function () {
return Auth::user()->test();
});
Auth::routes();
Route::any('/home', 'HomeController#index')->name('home');
Route::group(['as' => 'user.'], function () {
Route::get('/front', function () {
return view('front');
});
Route::get('/settings', ['as' => 'settings', 'uses' => 'ProfileController#viewSettings']);
Route::post('/settings', ['as' => 'settings', 'uses' => 'ProfileController#saveSettings']);
Route::any('/profile/{userId}', ['as' => 'profile', 'uses' => 'ProfileController#viewProfile']);
Route::get('/search/{query?}', ['as' => 'search', 'uses' => 'SearchController#search']);
Route::get('users', function () {
return User::find(1)->toJson();
});
Route::get('/chat', function () {
return view('chat');
});
Route::get('/calendar', function () {
return view('calendar');
});
Route::resource('events', 'EventsController', ['only' => ['index', 'store', 'update', 'destroy']]);
//Friends route
Route::post('/friends/request', ['as' => 'friends', 'uses' => 'FriendsController#sendRequest']);
Route::get('/friends/viewReq', ['as' => 'friends', 'uses' => 'FriendsController#viewFriendReq']);
Route::post('/friends/reqAction', ['as' => 'friends', 'uses' => 'FriendsController#requestAction']);
Route::get('/status-delete/{status_id}',['uses' => 'HomeController#getDeleteStatus', 'as'=> 'status.delete',
'middleware' =>'auth'
]);
Route::get('/edit/{status_id}', 'HomeController#edit');
});
[1]: https://i.stack.imgur.com/BFMap.jpg

You may hash a password by calling the make method on the Hash facade. In your RegisterController just encrypt your password as
'password' => Hash:make($data['password'])
but make sure that, you must include this to use Hash Facade
use Illuminate\Support\Facades\Hash;
After that you can use check method which allows you to verify that a given plain-text string corresponds to a given hash as
if (Hash::check($data['password'], Hash::make($data['password']))) {
// The passwords match...
}

Related

Why registerController is not inserting data to database in laravel

I am new to laravel. I want to insert users data to database using registerController in laravel.
What I have tried is:
register.blade.php
#extends('adminlte::auth.auth-page', ['auth_type' => 'register'])
#php( $login_url = View::getSection('login_url') ?? config('adminlte.login_url', 'login') )
#php( $register_url = View::getSection('register_url') ?? config('adminlte.register_url', 'register') )
#if (config('adminlte.use_route_url', false))
#php( $login_url = $login_url ? route($login_url) : '' )
#php( $register_url = $register_url ? route($register_url) : '' )
#else
#php( $login_url = $login_url ? url($login_url) : '' )
#php( $register_url = $register_url ? url($register_url) : '' )
#endif
#section('auth_header', __('adminlte::adminlte.register_message'))
#section('auth_body')
<?php $res= DB::table('states')->orderBy('name','asc')->get();
?>
<form method="POST" action="{{ route('register_user') }}" class="registerForm">
#csrf
<div class="row">
<div class="col-md-6">
{{-- First Name field --}}
<div class="col-md-6">
<div class="input-group form-group">
<input type="text" class="form-control" placeholder="First Name *" name="first_name" value="" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="input-group form-group">
<input type="text" class="form-control" placeholder="Last Name *" name="last_name" value="" required>
</div>
</div>
<div class="col-md-6">
<div class="input-group form-group">
<input type="email" class="form-control" name="email" value="" placeholder="Email *" required>
</div>
</div>
<div class="col-md-6">
<div class="input-group form-group">
<input type="text" class="form-control phoneMask" placeholder="Phone *" name="phone" value="" required>
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-offset-4 submit_btn">
{{-- Register button --}}
<button type="submit" class="btn btn-block {{ config('adminlte.classes_auth_btn', 'btn-flat btn-primary') }}">
<span class="fas fa-user-plus"></span>
{{ __('adminlte::adminlte.register') }}
</button>
</div>
</div>
</div>
</form>
#stop
#section('auth_footer')
<p class="my-0">
<a href="{{ route('login') }}">
{{ __('adminlte::adminlte.i_already_have_a_membership') }}
</a>
</p>
#stop
RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Auth;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users']
//'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
/*protected function create(array $data)
{
/*return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
dd($data);
$user= User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'mobile' => $data['phone']
]);
// dd($data['password'], $user->password);
return $user;
}*/
public function registerUsers(Request $request)
{
$first_name=$request->input('first_name');
$last_name=$request->input('last_name');
$email=$request->input('email');
$phone=$request->input('phone');
dd($request);
DB::insert('insert into users(first_name,last_name,email,phone)values(?,?,?,?)',[$first_name,$last_name,$email,$phone]);
}
}
web.php
Route::get('/', function () {
return view('auth.login');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/register_user', 'Auth\RegisterController#registerUsers')->name('register_user');
Model
class User extends Authenticatable implements AuditableContract
{
use HasApiTokens, Notifiable;
use SoftDeletes;
use Auditable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $fillable = ['first_name', 'last_name','email','phone','device_token','password','approved','added_by','removed','removed_by','deleted_at'];
}
When I try to submit this form, it is not inserting data to database and is showing HTTP error 500 and couldn't handle request.
What my form looks like
How to fix and insert data to database.
Try to add the cross-fire request forgery to your form. Generally I get this error when I forget it.
Add it like that in your view:
<?php $res= DB::table('states')->orderBy('name','asc')->get(); ?>
<form method="POST" action="{{ route('register_user') }}" class="registerForm">
#csrf
<div class="row">
<div class="col-md-6">
{{-- First Name field --}}
Route
Route::post('/test', 'Auth\RegisterController#test')->name('test');
Auth\RegisterController
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
.
.
.
public function test ( Request $request){
$rules = array(
'first_name' => 'required', 'string', 'max:255',
// add validation rules here
);
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$user = new User();
$user->name = $request->input('first_name');
//copy above line and add remaining fields.
$user->save();
return redirect()->back()->with(array('message' => 'user added.'));
} else {
return redirect()->back()->withErrors($validator)->withInput();
}
}
follow these steps
make sure your request received by the desired route
make sure you have passed validation
then input data like this
DB::table('post')->insert([
DB::table('posts')->insert([
'name_name' => \request()->name,
'last_name' => \request()->last_name,
'email' => \request()->email,
'phone' => \request()->phone,
]);

How to add more fields to the Register form of backpack-laravel?

I tried to add more fields to the Register form of backpack-laravel but the Controller is not found.
I followed the documentation: https://backpackforlaravel.com/docs/4.1/base-how-to#add-one-or-more-fields-to-the-register-form
This is what I wrote into my routes/backpack/custom.php:
Route::get('admin/register', 'App\Http\Controllers\Admin\Auth\RegisterController')->name('backpack.auth.register');
My Register Controller looks like that:
<?php
namespace App\Http\Controllers\Admin\Auth;
use Backpack\CRUD\app\Http\Controllers\Auth\RegisterController as BackpackRegisterController;
class RegisterController extends BackpackRegisterController
{
/**
* Get a validator for an incoming registration request.
*
* #param array $data
*
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
$user_model_fqn = config('backpack.base.user_model_fqn');
$user = new $user_model_fqn();
$users_table = $user->getTable();
$email_validation = backpack_authentication_column() == 'email' ? 'email|' : '';
return Validator::make($data, [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
backpack_authentication_column() => 'required|'.$email_validation.'max:255|unique:'.$users_table,
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
*
* #return User
*/
protected function create(array $data)
{
$user_model_fqn = config('backpack.base.user_model_fqn');
$user = new $user_model_fqn();
return $user->create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
backpack_authentication_column() => $data[backpack_authentication_column()],
'password' => bcrypt($data['password']),
]);
}
}
I always get the error:
UnexpectedValueException
Invalid route action: [App\Http\Controllers\Admin\Auth\RegisterController].
at vendor/laravel/framework/src/Illuminate/Routing/RouteAction.php:91
87| */
88| protected static function makeInvokable($action)
89| {
90| if (! method_exists($action, '__invoke')) {
> 91| throw new UnexpectedValueException("Invalid route action: [{$action}].");
92| }
93|
94| return $action.'#__invoke';
95| }
• `App\Http\Controllers\Admin\Auth\RegisterController` was not found: Controller class `App\Http\Controllers\Admin\Auth\RegisterController` for one of your routes was not found. Are you sure this controller exists and is imported correctly?
+8 vendor frames
9 routes/backpack/custom.php:8
Illuminate\Support\Facades\Facade::__callStatic("get")
+11 vendor frames
21 [internal]:0
Illuminate\Foundation\Application::Illuminate\Foundation\{closure}(Object(Backpack\CRUD\BackpackServiceProvider))
Has anybody an idea what I can do?
Try this:
use App\Http\Controllers\Admin\Auth\RegisterController;
Route::get('admin/register', [RegisterController::class, 'showRegistrationForm'])->name('backpack.auth.register');
to handle the form POST you'll also want to add:
Route::post('admin/register', [RegisterController::class, 'register'])->name('backpack.auth.register');
This solution is based on an alternative format to create the route here which is documented here:
https://laravel.com/docs/8.x/routing
On that page you can find the following example, which I based my solution on:
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
Thanks for the Say. However, it was necessary to put more things. As shown the code below. So it worked for me.
//routes
Route::group(['middleware' => [config('backpack.base.web_middleware', 'web')]], function () {
//routes here
Route::get('admin/register', 'App\Http\Controllers\Admin\Auth\RegisterController#showRegistrationForm')->name('backpack.auth.register');
Route::post('admin/register', 'App\Http\Controllers\Admin\Auth\RegisterController#register');
});
Route::group([
'prefix' => config('backpack.base.route_prefix', 'admin'),
'middleware' => array_merge(
(array) config('backpack.base.web_middleware', 'web'),
(array) config('backpack.base.middleware_key', 'admin')
),
'namespace' => 'App\Http\Controllers\Admin',
], function () { // custom admin routes
Route::crud('tag', 'TagCrudController');
//your codes CRUDs
}); // this should be the absolute last line of this file
The controller stood in the folder
App\Http\Controllers\Admin\Auth\RegisterController
<?php
namespace App\Http\Controllers\Admin\Auth;
use App\Models\Pessoa;
use Backpack\CRUD\app\Library\Auth\RegistersUsers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Validator;
class RegisterController extends Controller
{
protected $data = []; // the information we send to the view
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$guard = backpack_guard_name();
$this->middleware("guest:$guard");
// Where to redirect users after login / registration.
$this->redirectTo = property_exists($this, 'redirectTo') ? $this->redirectTo
: config('backpack.base.route_prefix', 'dashboard');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
*
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
$user_model_fqn = config('backpack.base.user_model_fqn');
$user = new $user_model_fqn();
$users_table = $user->getTable();
$email_validation = backpack_authentication_column() == 'email' ? 'email|' : '';
return Validator::make(
$data,
[
'name' => 'required|max:100',
'cpf' => 'required|min:11|max:14',
backpack_authentication_column() => 'required|' . $email_validation . 'max:255|unique:' . $users_table,
'password' => 'required|min:6|confirmed',
],
[
'name.required' => 'O nome é obrigatório', // custom message
'cpf.min' => 'O CPF tem que ter no mínimo 11 caracteres e no máximo 14', // custom message
'cpf.max' => 'O CPF tem que ter no mínimo 11 caracteres e no máximo 14', // custom message
'cpf.required' => 'O CPF é obritagorio',
'email.required' => 'E-mail é obrigatório ',
'email.unique' => 'O email já foi registrado.',
'password.confirmed' => 'A confirmação da senha não corresponde.', //password
]
);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
*
* #return User
*/
protected function create(array $data)
{
$user_model_fqn = config('backpack.base.user_model_fqn');
$user = new $user_model_fqn();
return $user->create([
'name' => $data['name'],
'cpf' => $data['cpf'],
'pessoa_id' => $data['pessoa_id'],
backpack_authentication_column() => $data[backpack_authentication_column()],
'password' => bcrypt($data['password']),
]);
}
/**
* Show the application registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
// if registration is closed, deny access
if (!config('backpack.base.registration_open')) {
abort(403, trans('backpack::base.registration_closed'));
}
// $this->data['title'] = trans('backpack::base.register'); // set the page title
// $this->data['title'] = "Registrar Usuário"; // set the page title
return view(backpack_view('auth.register'));
// return view(backpack_view('auth.register'), $this->data);
}
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
// if registration is closed, deny access
if (!config('backpack.base.registration_open')) {
abort(403, trans('backpack::base.registration_closed'));
}
$requestData = $request->all();
$this->validator($requestData)->validate();
$objPessoa = new Pessoa();
$objPessoa->nome = $request->name;
$objPessoa->email = $request->email;
$objPessoa->cpf = $request->cpf;
$objPessoa->save();
$requestData['pessoa_id'] = $objPessoa->id;
$user = $this->create($requestData);
event(new Registered($user));
$this->guard()->login($user);
return redirect($this->redirectPath());
}
/**
* Get the guard to be used during registration.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return backpack_auth();
}
}
And Blande stayed in
resources\views\vendor\backpack\base\auth\register.blade.php
#extends(backpack_view('layouts.plain'))
#section('content')
<div class="row justify-content-center">
<div class="col-12 col-md-8 col-lg-4">
<h3 class="text-center mb-4">{{ trans('backpack::base.register') }}</h3>
<div class="card">
<div class="card-body">
<form class="col-md-12 p-t-10" role="form" method="POST"
action="{{ route('backpack.auth.register') }}">
{!! csrf_field() !!}
<div class="form-group">
<label class="control-label" for="name">{{ trans('backpack::base.name') }}</label>
<div>
<input type="text" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}"
name="name" id="name" value="{{ old('name') }}">
#if ($errors->has('name'))
<span class="invalid-feedback">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label class="control-label" for="name">CPF</label>
<div>
<input type="text" class="form-control{{ $errors->has('cpf') ? ' is-invalid' : '' }}"
name="cpf" id="cpf" value="{{ old('cpf') }}" placeholder="000.000.000-00">
#if ($errors->has('cpf'))
<span class="invalid-feedback">
<strong>{{ $errors->first('cpf') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label class="control-label"
for="{{ backpack_authentication_column() }}">{{ config('backpack.base.authentication_column_name') }}</label>
<div>
<input type="{{ backpack_authentication_column() == 'email' ? 'email' : 'text' }}"
class="form-control{{ $errors->has(backpack_authentication_column()) ? ' is-invalid' : '' }}"
name="{{ backpack_authentication_column() }}"
id="{{ backpack_authentication_column() }}"
value="{{ old(backpack_authentication_column()) }}">
#if ($errors->has(backpack_authentication_column()))
<span class="invalid-feedback">
<strong>{{ $errors->first(backpack_authentication_column()) }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label class="control-label" for="password">{{ trans('backpack::base.password') }}</label>
<div>
<input type="password"
class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}"
name="password" id="password">
#if ($errors->has('password'))
<span class="invalid-feedback">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label class="control-label"
for="password_confirmation">{{ trans('backpack::base.confirm_password') }}</label>
<div>
<input type="password"
class="form-control{{ $errors->has('password_confirmation') ? ' is-invalid' : '' }}"
name="password_confirmation" id="password_confirmation">
#if ($errors->has('password_confirmation'))
<span class="invalid-feedback">
<strong>{{ $errors->first('password_confirmation') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div>
<button type="submit" class="btn btn-block btn-primary">
{{ trans('backpack::base.register') }}
</button>
</div>
</div>
</form>
</div>
</div>
#if (backpack_users_have_email() && config('backpack.base.setup_password_recovery_routes', true))
<div class="text-center">{{ trans('backpack::base.forgot_your_password') }}
</div>
#endif
<div class="text-center">{{ trans('backpack::base.login') }}</div>
</div>
</div>
#endsection

laravel 5 PasswordController Route

in laravel 5 i try the PasswordController and the ResetsPasswords but always i have a route probleme
Route.php
Route::controllers(['uses' => 'Auth/PasswordController']);
Route::get('home/ResetsPasswords',array('as'=>'getEmail' ,'uses' => 'home/ResetsPasswords#getEmail') );
Route::post('home/ResetsPasswords',array('as'=>'postEmail' ,'uses' => 'home/ResetsPasswords#postEmail' ));
Route::get('home/ResetsPasswords/{token}',array('as' => 'getReset','uses' => 'home/ResetsPasswords#getReset' ) );
Route::post('home/ResetsPasswords/{token}', array( 'as' => 'postReset','uses' => 'home/ResetsPasswords#postReset'));
Route::get('home/ResetsPasswords',array('as'=>'getEmailSubject' ,'uses' => 'home/ResetsPasswords#getEmailSubject') );
Route::get('home/ResetsPasswords',array('as'=>'redirectPath' ,'uses' => 'home/ResetsPasswords#redirectPath') );
The PasswordController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
use ResetsPasswords;
public function __construct()
{
$this->middleware('guest');
}
}
the ResetsPasswords.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
ResetsPasswords.php
<?php
//namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
trait ResetsPasswords
{
/**
* Display the form to request a password reset link.
*
* #return \Illuminate\Http\Response
*/
public function getEmail()
{
return view('auth.password');
}
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return redirect()->back()->with('status', trans($response));
case Password::INVALID_USER:
return redirect()->back()->withErrors(['email' => trans($response)]);
}
}
/**
* Get the e-mail subject line to be used for the reset link email.
*
* #return string
*/
protected function getEmailSubject()
{
return isset($this->subject) ? $this->subject : 'Your Password Reset Link';
}
/**
* Display the password reset view for the given token.
*
* #param string $token
* #return \Illuminate\Http\Response
*/
public function getReset($token = null)
{
if (is_null($token)) {
throw new NotFoundHttpException;
}
return view('auth.reset')->with('token', $token);
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postReset(Request $request)
{
$this->validate($request, [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->resetPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return redirect($this->redirectPath());
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #param string $password
* #return void
*/
protected function resetPassword($user, $password)
{
$user->password = bcrypt($password);
$user->save();
Auth::login($user);
}
/**
* Get the post register / login redirect path.
*
* #return string
*/
public function redirectPath()
{
if (property_exists($this, 'redirectPath')) {
return $this->redirectPath;
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}
}
and for the views
first the emails/password.blade.php
<?php
Click here to reset your password: {{ url('password/reset/'.$token) }}
?>
the auth/password.blade.php
#extends('layouts.master')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="/password/email">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Send Password Reset Link
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
the reset.blade.php
#extends('layouts.master')
#section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" role="form" method="POST" action="/password/reset">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="token" value="{{ $token }}">
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Reset Password
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
and finally my login view
Mot de passe oublié?
so the error is
Call to undefined method Laravel\Routing\Route::controllers()
can you please help me :/ i try to change the route many time but always the same problem !!!!!!!
thank you
Implicit controllers are deprecated on Laravel 5. You need to remove this:
Route::controllers(['uses' => 'Auth/PasswordController']);
More info: https://laravel.com/docs/5.2/routing#route-model-binding
This is for laravel 5
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
This is for laravel 5.2
Route::group(['middleware' => ['web']], function () {
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
});
I think you are using in routes.php
use Illuminate\Routing\Route;
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
if you use this then the error comes.
Call to undefined method Illuminate\Routing\Route::controllers()
to avoid this error use this
use Illuminate\Support\Facades\Route;
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Note:Dont need to import anything route
leave it as
The below one also works
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);

Laravel 5.2 Login not working

I have created a new Laravel 5.2 installation. And I have run the following command to install the default Laravel authentication;
php artisan make:auth
The registration form works but the login just redirects home without logging in. And displays no errors when when I enter the wrong credentials.
This is my routes file:
Route::get('/', 'BaseController#index');
Route::get('/tutors', 'TutorsController#Index');
Route::get('/tutors/myrequest', 'TutorsController#RequestTutor');
Route::get('/tutors/{id}', 'TutorsController#show')->where(['id' => '[0-9]+']);
Route::get('/tutors/{GUID}', 'TutorsController#TutorByGUID')->where(['id' => '[A-Za-z]+[0-9]+']);
/********************Authentication routes**********************************/
Route::group(['middleware' => ['web']], function () {
Route::auth();
});
This is code from the AuthController:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => 'required|max:255',
'lastname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
This is the BaseController which contains the home method;
<?php namespace App\Http\Controllers;
use App\Services\InterfaceService;
use App\Repositories\TutorRepository;
use App\Http\Requests;
use Illuminate\Http\Request;
class BaseController extends Controller {
protected $TutorRepository;
protected $InterfaceService;
public function __construct(InterfaceService $InterfaceService, TutorRepository $TutorRepository)
{
//$this->middleware('guest');
$this->InterfaceService = $InterfaceService;
$this->TutorRepository = $TutorRepository;
}
public function index()
{
$tutors = $this->TutorRepository->all();
$page_info = \Config::get('constants.App.Pages.home');
$this->InterfaceService->SetPageInfo($page_info);
return view('home', ['TopTutors'=>$tutors]);
}
} ?>
This is code from the login view.
<form role="form" method="POST" action="{{ url('/login') }}" id="login_form">
{!! csrf_field() !!}
<div class="mj_login_form">
<div class="form-group">
<input type="text" placeholder="Email" id="email" name="email" class="form-control" value="{{ old('email') }}">
#if ($errors->has('email'))
<span class="help-block"><strong>{{ $errors->first('email') }}</strong></span>
#endif
</div>
<div class="form-group">
<input type="password" placeholder="Your Password" id="password" class="form-control" name="password">
#if ($errors->has('password'))
<span class="help-block"><strong>{{ $errors->first('password') }}</strong></span>
#endif
</div>
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 mj_toppadder20">
<div class="form-group pull-left">
<div class="mj_checkbox">
<input type="checkbox" value="1" id="check2" name="remember">
<label for="check2"></label>
</div>
<span> remember me</span>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 mj_toppadder20">
<div class="form-group pull-right">
<span>forget password ?</span>
</div>
</div>
</div>
</div>
<div class="mj_pricing_footer">
login Now
</div>
</form>
That happens because your '/' route is not under the web middleware group and you're not using the auth middleware for the routes you want to be authenticated
This means that when accessing that route, session is not available, and the auth middleware doesn't fire, so authentication doesn't work.
Try to put all the routes in which you want to use session under the web middleware group, and for the routes in which you want authentication use the auth middleware:
Route::group( ['middleware' => ['web'] ], function () {
/* these routes use 'auth' middleware, so only an authenticated user will access*/
Route::group( ['middleware' => 'auth' ], function () {
Route::get('/', 'BaseController#index');
});
Route::auth();
});
A Note on Laravel version:
Keep in mind that if you're using Laravel version >= 5.2.27 the middleware web is used by default on every route defined in routes.php as you can see in app/Providers/RouteServiceProvider.php:
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web'
], function ($router) {
require app_path('Http/routes.php');
});
}
In that case you can remove you statement for using the web middleware group, but you'll only need to use auth middleware for the authenticated routes

php - Laravel 5.2 Auth not Working

I want to make a authentication user login and register in laravel. But when I submit to save the register info..It's showing
Object not found!
The requested URL was not found on this server. The link on the
referring page seems to be wrong or outdated. Please inform the author
of that page about the error.
If you think this is a server error, please contact the webmaster.
Here is my authController:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
protected function getLogin() {
return View('auth.login');
}
protected function postLogin(LoginRequest $request) {
if ($this->auth->attempt($request->only('email', 'password'))) {
return redirect()->route('/');
// return view('course.index');
}
return redirect('auth/login')->withErrors([
'email' => 'The email or the password is invalid. Please try again.',
]);
}
/* Register get post methods */
protected function getRegister() {
return View('auth.register');
}
protected function postRegister(RegisterRequest $request) {
$this->user->name = $request->name;
$this->user->email = $request->email;
$this->user->password = bcrypt($request->password);
$this->user->save();
return redirect('auth.login');
}
protected function getLogout()
{
$this->auth->logout();
return redirect('auth.login');
}
protected $redirectTo = '/course';
protected $loginPath = '/auth/login';
}
Here is my login.blade.php file:
<form method="POST" action="/auth/login">
{!! csrf_field() !!}
<div>
Email
<input type="email" name="email" value="{{ old('email') }}">
</div>
<div>
Password
<input type="password" name="password" id="password">
</div>
<div>
<input type="checkbox" name="remember"> Remember Me
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
Here is my register.blade.php file
<form method="POST" action="/auth/register">
{!! csrf_field() !!}
<div>
Name
<input type="text" name="name" value="{{ old('name') }}">
</div>
<div>
Email
<input type="email" name="email" value="{{ old('email') }}">
</div>
<div>
Password
<input type="password" name="password">
</div>
<div>
Confirm Password
<input type="password" name="password_confirmation">
</div>
<div>
<button type="submit">Register</button>
</div>
</form>
And Here is the routes.php
<?php
/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/all_user',function(){
return view('all_user');
});
Route::get('all_user/{id}/{name}',function($id,$name){ // Here we pass the peremeter in url all_user
return 'User '.$id." ".$name; // with the parameter id and name
});
Route::get('home','basicController#index'); // Here Home is the URL and it
//execute the basiccontroller index page
Route::get('about','basicController#about');
Route::resource('course','courseController');
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
Route::get('auth/login', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
// Registration routes...
Route::get('auth/register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
});
In your view
For login :
{{ !! Form::open(array('route'=>route('auth.login'))) !!}}
For Register :
{{ !! Form::open(array('route'=>route('auth.register'))) !! }}
In you Routes
For login
Route::post('auth/login', array('as'=>'auth.login','uses'=>'Auth\AuthController#postLogin'));
For Register
Route::post('auth/register', array('as'=>'auth.register','uses'=>'Auth\AuthController#postRegister'));
And don't forgot to close your form as :
{{ !! Form::close() !! }}

Categories