I am using Laravel 5.3 My ForgotPasswordController looks like that:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Base\BaseController;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class ForgotPasswordController extends BaseController
{
use SendsPasswordResetEmails;
public function __construct()
{
$this->middleware('guest');
}
public function showLinkRequestForm()
{
$title = $this->title;
$appName = $this->appName;
$action = $this->action;
return view('password.forgotPassword')->with(compact('title', 'appName', 'action'));
}
}
ResetPasswordController code :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Base\BaseController;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends BaseController
{
use ResetsPasswords;
public function __construct()
{
$this->middleware('guest');
}
public function showResetForm(Request $request, $token = null)
{
return view('passwords.resetPassword')->with(
['token' => $token, 'email' => $request->email]
);
}
public function reset(Request $request)
{
$this->validate($request, [
'token' => 'required',
'password' => 'required|confirmed|min:6',
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->sendResetFailedResponse($request, $response);
}
}
My Admin Route :
Route::group(['namespace' => 'Auth'], function() {
Route::get('/forgotpassword/reset', 'ForgotPasswordController#showLinkRequestForm');
Route::post('/forgotpassword/email', 'ForgotPasswordController#sendResetLinkEmail');
Route::get('/password/reset/{token}', 'ResetPasswordController#showResetForm');
Route::post('/password/reset', 'ResetPasswordController#reset');
});
BaseController Code :
<?php
namespace App\Http\Controllers\Base;
use App\Http\Controllers\Controller;
class BaseController extends Controller
{
protected $appName = 'Stackoverflow';
protected $title = 'Welcome to Stackoverflow';
protected $action;
}
I can send the link to my email, but once I click the link/button.
It throws an error like above. Any idea ?
You are not using the required namespace, try to use the following in your controller:
use Illuminate\Http\Request;
You are getting the error due to the fact that your script tries to load the Request class from the current namespace :App\Http\Controllers\Auth
Request docs for Laravel 5.3
Related
I am creating user authentication using a custom table. In my login controller authentication is working fine and redirected to dashboard. But when I am going to create another url using a new controller, user auth data not showing for that controller.
I want to get user data through auth facade in constructor. How will that possible?
Here is my code:
web.php:
<!---Routes for login and dashboard-->
Route::get('/login','CustomLogin#index');
Route::post('/login','CustomLogin#checklogin');
Route::get('/','CustomLogin#SuccessLogin');
Route::get('/logout','CustomLogin#logout');
<!---Routes for other controller where user auth not working-->
Route::get('/add-creditor', 'AddCreditor#index');
CustomLogin.php (controller):
<?php
namespace App\Http\Controllers;
use App\library\My_functions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\User;
use Illuminate\Support\Facades\Auth;
use Redirect;
use View;
use Session;
use Cookie;
class CustomLogin extends Controller
{
public function __construct()
{
$this->_myFun = new My_functions;
}
public function index()
{
if(!Auth::check()) {
return view('CustomLogin.CustomLogin');
}
else{
Redirect::to(SITE_URL)->send();
}
}
public function username()
{
return 'user_name';
}
function checklogin(Request $request)
{
$this->validate($request, [
'input-username' => 'required',
'input-password' => 'required'
]);
$user_data = array(
'user_name' => $request->get('input-username'),
'password' => $request->get('input-password')
);
if(Auth::attempt($user_data)){
return redirect('/');
}
else
{
return back()->with('error','Wrong Login Details');
}
}
function SuccessLogin(){
if (!$this->_myFun->DoLogIn()) {
Redirect::to(SITE_URL.'login')->send();
}
else {
$data=array();
return View::make('include.dashboard',$data);
}
}
function logout(Request $request){
Auth::logout();
return redirect('/login');
}
}
Function DoLogIn() (app/library)
<?php namespace App\library {
use Illuminate\Routing\Controller as BaseController;
use App\library\CreateCrmGuid; // Get custom function
use App\library\FunctionForContact; // Get custom function
use Illuminate\Http\Request;
use Session;
use DB;
use Hash;
use Auth;
use App\User;
class My_functions{
public function DoLogIn()
{
//dd(Auth::user()); /*returns data if run from Login controller but null from Add Creditor controller*/
if(Auth::check())
{
$user_id = Auth::user()->id;
define('authenticated_user_id' ,$user_id);
return true;
}
else
{
return false;
}
}
}
AddCreditor Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Cookie;
use Config;
use App\library\my_functions; // Get custom function
use Redirect;
use DB;
use Session;
class AddCreditor extends Controller
{
protected $_myFun;
function __construct(){
dd(Auth::user()); // this returns null
$this->_myFun = new My_functions;
if (!$this->_myFun->DoLogIn()) {
Redirect::to(SITE_URL.'login')->send();
}
}
}
Add auth Middleware in your routes
Route::middleware(['auth'])->get('/add-creditor', 'AddCreditor#index');
Still, after this, you might not get user data through Auth facade in the controller constructor, But in your Route method i.e. AddCreditor#index you will get the user data either through the following methods
Auth::user();
or
request()->user();
I am trying to make Multi Authentication for Admin and User.
User is getting logged in and logged out without any problem.
But Admin is logged in but not getting logged out. Do I require double
logout function or I am making up mistake.
AdminLoginController.php
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin', ['except' => 'logout']);
}
public function showLoginForm(){
return view('auth.admin-login');
}
public function login(Request $request)
{
//Validate the form data
$this->validate($request,[
'email' => 'required|email',
'password' => 'required|min:6'
]);
//Attempt to log th user in
if (Auth::guard('admin')->attempt(['email' => $request->email,'password' => $request->password],$request->remember)){
//if successful, then redirects to their intended location
return redirect()->intended(route('admin.dashboard'));
}
// if unsuccessful, then redirect back to thee login with the form data
return redirect()->back()->withInput($request->only('email','remember'));
}
}
Login Controller.php
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function logout(Request $request) {
Auth::logout();
return redirect('/');
}
}
I have Laravel version 5.3 and i created a file createArticleRequest.php under the request folder , which looks like below:
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class CreateArticleRequest extends Request {
public function authorize() {
return true;
}
public function rules() {
return [
'title' => 'required|min:3',
'body' => 'required',
'published_at' => 'required|date',
]
}
}
?>
In My articles controller i have the following method:
public function store(CreateArticleRequest $request) {
// $input = Request::all();
Article::create($request->all());
return redirect('articles');
}
But when i fill the form in my view and click on submit i get an error like so:
ReflectionException in Route.php line 286:
Class App\Http\Controllers\CreateArticleRequest does not exist
Why am i getting this error ??
I believe my articles Controller and my createArticlesRequest are in the same namespace so why am i getthing this error?
You should use PHP' use keyword at the top of the PHP file, so that php can find the CreateArticleRequest package Class in the right namespace like this:
namespace App\Http\Controllers;
use App\Http\Requests\CreateArticleRequest;
class Controller {
public function store(CreateArticleRequest $request) {
// $input = Request::all();
Article::create($request->all());
return redirect('articles');
}
}
Hope this helps!
First of all, I already check that in other controller (not in resource controller) my session work very well, but when I did it in the resource controller my code for get session didn't work.
Here's my resource controller
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//tambahan
use DB;
use Session;
//model
use App\_admins;
use App\Mahasiswas;
class MahasiswaController extends Controller
{
protected $data;
protected $token;
public function __contruct(){
$this->data = array();
$this->middleware(function ($request, $next) {
$this->token = $request->session()->get('_admin_id');
if (!$request->session()->has('_admin_id')) {
abort(404);
}
return $next($request);
});
}
private function user($token){
$this->data['query'] = _admins::find($token);
}
public function index(){
echo $this->token;
}
There is more public function, but it's still empty so I am not showing it here to avoid confusion. And here is my route in web.php:
Route::group(['namespace' => 'Admin'],function(){
Route::resource('/admin/mahasiswa','MahasiswaController');
Route::resource('/admin/nilai','NilaiController');
});
In 5.3 the middleware hasn't run yet in the constructor, so you're unable to gather session data. But using your closure-based approach, you should be able to access it with something like this:
$this->middleware(function($request, $next) {
// Get the session value (uses global helper)
$this->token = session('_admin_id');
// If the value is null, abort the request
if (null === $this->token) abort(404);
return $next($request);
});
I have added a controller for my package and I need to call Auth methods inside the constructor of this controller but I get the following error :
ReflectionException in Container.php line 734:
Class hash does not exist
Here is my code :
use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Session;
class CartController extends Controller
{
private $customer;
public function __construct()
{
$this->middleware('auth', ['except' => ['add']]);
$multiauth = config('cart.multiauth');
if ($multiauth) {
$guard = config('auth.defaults.guard');
$this->customer = Auth::guard($guard)->user();
} else {
$this->customer = Auth::user();
}
}
public function add()
{
// Code
}
}
When I add the code of constructor inside the other functions it works properly but it fails when it is called from constructor of the controller.
I have searched alot for this and found no working solution.
I've solved the problem by adding a middleware :
namespace myNamespace\myPackage;
use Closure;
use Illuminate\Support\Facades\Auth;
class CustomerMiddleware
{
public function handle($request, Closure $next)
{
$multiauth = config('cart.multiauth');
if ($multiauth) {
$guard = config('auth.defaults.guard');
$customer = Auth::guard($guard)->user();
} else {
$customer = Auth::user();
}
$request->attributes->add(['customer' => $customer]);
return $next($request);
}
}
Then I used this middleware for the 'cart/add' route :
Route::group(['middleware' => ['web']], function () {
Route::group(['middleware' => 'customer'], function() {
Route::post('cart/add',
'myNamespace\myPackage\CartController#add');
});
});
So by checking the $request->get('customer') parameter inside the 'add' method of 'CartController', I have access to information of current user :
class CartController extends Controller
{
public function __construct() { }
public function add()
{
$customer = $request->get('customer');
// Code
}
}
I hope this helps someone else :)
You can't use middleware in controller __construct , create a functions and use it