Hi I got problem with my Laravel Rest-API apps, whenever i access localhost:8000/api/login in my Postman its say
(1/1) ReflectionException Class signature does not exist
This is my artisan route:list for api/login
POST | api/login | | App\Http\Controllers\Api\UserController#login | api
This is my api route
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('oauth/token', '\Laravel\Passport\Http\Controllers\AccessTokenController#issueToken');
Route::group(['namespace' => 'Api'], function () {
Route::post('/login', 'UserController#login');
});
This is my UserController inside Api folder
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\User;
use Response;
class UserController extends Controller
{
public function __construct()
{
$this->content = array();
}
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$this->content['token'] = $user->createToken('Pizza App')->accessToken;
$status = 200;
} else {
$this->content['error'] = "Unauthorised";
$status = 401;
}
return response()->json($this->content, $status);
}
}
please help me, if I trying to test my Rest-Api in postman, its keep saying
(1/1) ReflectionException
Class signature does not exist
I think you can use a sample for custom authentication in laravel:
https://www.minddevelopmentanddesign.com/blog/add-custom-api-authentication-to-laravel/
Related
I'm trying to implement email verification so what I'd like to do is redirect the authenticated user to the specific React Router route called /blogs from the Authenticate.php file as this is the React Router route where the auth starts.
In Authenticate.php, I'd need to use a value that emanates from ->name('someValue) on one of the routes in the api.php file but the problem is that /blogs is a React Router route so I cannot use ->name('someValue').
I'm not sure the wildcard any route in web.php file is causing the issue.
I know the Laravel router and the React Router cannot be used together but I'd really like to know if there's something clever out there that needs to be done in order to achieve this?
Authenticate.php:
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
return route('blogs');
}
}
}
web.php:
Route::get('/{any}', function () {
return view('app');
})->where('any', '.*');
api.php:
Route::post('email/verification-notification', [EmailVerificationController::class, 'sendVerificationEmail'])->middleware('auth:sanctum');
Route::get('verify-email/{id}/{hash}', [EmailVerificationController::class, 'verify'])->name('verification.verify')->middleware('auth:sanctum');
EmailVerificationController.php:
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
class EmailVerificationController extends Controller
{
public function sendVerificationEmail(Request $request)
{
if ($request->user()->hasVerifiedEmail()) {
return [
'message' => 'Already Verified'
];
}
$request->user()->sendEmailVerificationNotification();
return ['status' => 'verification-link-sent'];
}
public function verify(EmailVerificationRequest $request)
{
if ($request->user()->hasVerifiedEmail()) {
return [
'message' => 'Email already verified'
];
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return [
'message'=>'Email has been verified'
];
}
}
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 using laravel 5.2 and following is my code
I am getting error
ReflectionException in Route.php line 280:
Method App\Http\Controllers\Signup_controllers::guestcheckout() does not exist
whats wrong i am doing? plz help
this is my route.php
Route::group(array('prefix' => 'signup'), function()
{
Route::resource('/register', 'Signup_controllers#register');
Route::resource('/guestcheckout', 'Signup_controllers#guestcheckout');
Route::resource('/login', 'Signup_controllers#login');
Route::resource('/logout', 'Signup_controllers#logout');
Route::resource('/ajaxCheckCustomerEmailExist', 'Signup_controllers#ajaxCheckCustomerEmailExist');
});
this is my signup controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Session\Session1;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use Image;
use Session;
use DB;
use Mail;
use App\Http\Models\Frm_mailing_list;
use App\Http\Models\Frm_contactus;
use App\Http\Models\Emailautoresponse;
use App\Http\Models\Adminemail;
use App\Http\Models\Emailsetting;
use App\Http\Models\Product_price;
class Signup_controllers extends Controller
{
public function index(Request $request)
{
}
public function register(Request $request)
{
include(public_path().'/app/Http/Controllers/action/register_controllers.php');
}
public function login(Request $request)
{
include(public_path().'/app/Http/Controllers/action/login_controllers.php');
}
public function logout()
{
Session::flush();
return Redirect::away(url('/login-registration'))->send();
}
public function guestcheckout(Request $request)
{
include(public_path().'/app/Http/Controllers/action/guestcheckout_controllers.php');
}
public function ajaxCheckCustomerEmailExist(Request $request)
{
//Checked By Ranjit
$email=$request->email;
$customerData=array('email'=>$email);
$Customer=new Customer;
$resultCustomer=$Customer->getByAttributesQuery($customerData);
if($resultCustomer['recordCount']>0){
echo "false";
}else{
echo "true";
}
}
}
when i try to call guestcheckout it says method not found even i have defined it
Route::get('/register', 'Signup_controllers#register');
You're including controllers within Controllers and alsorts of things are wrong with your code that are going to cause you problems
I'd consider reading the documentation to understand how Laravel works
You are using Resource Controllers incorrectly. See Laravel Documention.
https://laravel.com/docs/5.4/controllers#resource-controllers
change:
Route::resource('/guestcheckout', 'Signup_controllers#guestcheckout');
to
Route::post('/guestcheckout', 'Signup_controllers#guestcheckout');
and do the same thing for other routes, replace resource with post or get for your needs
Laravel resource routing assigns the typical "CRUD" routes to a
controller with a single line of code. and you call it like this :
Route::resource('photos', 'PhotoController');
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
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