Laravel API: Illuminate\Contracts\Container\BindingResolutionException: Target class - laravel

i am working on API. I want to create login api. i have created UsersController in API folder it in controllers. when i run in postman i shows an error
Illuminate\Contracts\Container\BindingResolutionException: Target class [App\Http\Controllers\App\Http\Controllers\API\UsersController] does not exist. in file F:\University_Data\xamp\htdocs\stylooworld\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 835`
I don't now why its duplicated the routing path Target class [App\Http\Controllers\App\Http\Controllers\API\UsersController]
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::namespace('App\Http\Controllers\API')->group(function () {
Route::post('login', 'UsersController#loginUser');
});
UsersController.php
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\UserController;
class UsersController extends Controller
{
//
public function loginUser(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
echo "<pre>";
print_r($data);
die;
if (Auth::attempt(['email' => $data['email'], 'password' => $data['password']])) {
// check email is activated or not (Only Work Online Server)
/* $userStatus = User::where('email', $data['email'])->first();
if ($userStatus->status == 0) {
Auth::logout();
$message = "Your account is not activated yet! Please confirm your email to activate!";
Session::flash('error_message', $message);
return redirect()->back();
}*/
//update user cart with user id
if (!empty(Session::get('session_id'))) {
$user_id = Auth::user()->id;
$session_id = Session::get('session_id');
Cart::where('session_id', $session_id)->update(['user_id' => $user_id]);
}
return redirect('/');
} else {
$message = "Invalid Username or Password";
Session::flash('error_message', $message);
return redirect()->back();
}
}
}
}
I don't know why this happen?

Update the routes.
For details please check (ref link) https://laravel.com/docs/8.x/upgrade and https://laravel.com/docs/8.x/releases#routing-namespace-updates
Use like this
api.php
If not working
Route::namespace('App\Http\Controllers\API')->group(function () {
Route::post('login', 'UsersController#loginUser');
});
Then Use like this
use App\Http\Controllers\API\UsersController;
Route::post('login', [UsersController::class, 'loginUser']);

import method Request
class Request extends SymfonyRequest implements Arrayable, ArrayAccess
on click (import method) always ready.
are you ok.

Related

Failed Manually Authenticating Users while login

i'm new in laravel. I'm stuck when creating manual authentication with laravel 9.
when the user is successfully logged in, but cannot access the view page with middleware Auth.
I tried dd(Auth::user()) and the result is null.
where is my mistake?
Controller
`
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
class OtorisasiController extends Controller
{
public function create()
{
return view('otorisasi.login');
}
public function login(Request $request)
{
$validasi = $request->validate([
'username' => 'required',
'password' => 'required'
]);
if (Auth::attempt($validasi)) {
$request->session()->regenerate();
return redirect()->intended('/');
}
return back()->with('infologin', 'Data yang anda masukan salah');
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
`
route
// Deafult Page After Login Route::get('/', [TransfersController::class, 'index'])->name('home')->middleware('auth');
how to do so, when login is successful, I can access all middleware auth pages

Larvel passport auth_token not saved

I am working on a Laravel site and I have been the LoginController. Although I obtain the auth_token at login - it doesn't allow me to call the user method - it claims the user is "unauthetnicated"
https://laravel.com/docs/7.x/passport
https://laravel.com/docs/5.8/api-authentication
I followed some documentation claiming that its unauthenticated because I need to group commands in the route?
"This is because we are not authenticated to access that route"
https://www.toptal.com/laravel/passport-tutorial-auth-user-access
but then it throws an error with ['cors', 'json.response']?
my route/api.php looks like this
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['middleware' => [/*'cors', 'json.response'*/]], function () {
// public routes
// get auth token, POST, /login
Route::post('login', 'LoginController#login');
Route::post('logout', 'LoginController#logout')->middleware('auth:api');
});
Route::middleware('auth:api')->group(function () {
// our routes to be protected will go in here
});
and my logincontroller is like this
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
//
function login(Request $request)
{
$request->validate([
'email' => ['required', 'email'],
'password' => ['required']
]);
$user = User::where('email', $request->email)->first();
//if user not found or the request password and user password does not match
if(!$user || !Hash::check($request->password, $user->password)){
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect']
]);
}
return $user->createToken('Auth Token')->accessToken;
}
function logout(Request $request)
{
$request->user()->tokens()->delete();
}
}

Class App\Http\Controllers\API\UserController does not exist

I am Having the issue of not getting token in postman as well as the following problem
ReflectionException
…\vendor\laravel\framework\src\Illuminate\Container\Container.php790
user controller does not exist
my route file;
Route::post('login', 'API\UserController#login');
Route::post('register', 'API\UserController#register');
Route::group(['middleware' => 'auth:api'], function(){
Route::post('details', 'API\UserController#details');
});
My controller file;
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Http\Request;
class UserController extends Controller {
//
public $successStatus = 200;
/**
* login api
*
* #return \Illuminate\Http\Response
*/
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success], $this-> successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
/**
* Register api
*
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]); if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
} $input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')-> accessToken;
$success['name'] = $user->name; return response()->json(['success'=>$success], $this-> successStatus);
}
/**
* details api
*
* #return \Illuminate\Http\Response
*/
public function details()
{
$user = Auth::user();
return response()->json(['success' => $user], $this-> successStatus);
}
}
How can I Solve this?
If your controller path is /App/Http/Controllers/API, you need to adjust it's namespace :
namespace App\Http\Controllers\API;
If your controller path is /App/Http/Controllers, you need to adjust your routes:
Route::post('login', 'UserController#login');
simply just write folder extension in namespace
for example in your case
namespace App\Http\Controllers\API;
And in route you just write
Route::post('register','api\UserController#register');
It could be because you are not calling the right middleware on the user route that directs to that controller. You would have to create a user middleware.
You can do this by navigating to your App\Http\Middleware and add the user middleware with the name UserMiddleware.php and some code to it.
Firstly, you would need to import the following files;
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
Then you create a class called; class UserMiddleware
Add a handle function to it like so; public function handle($request, Closure $next)
Inside this function include the following code;
if (Auth::user()->usertype == 'user')
{
return $next($request);
}
Next up, head over to you App\Http\Kernel.php and add the following code at the bottom of the protected $routeMiddleware section;
'user' => \App\Http\Middleware\UserMiddleware::class,
Then go over to your route (API) and include this predefined user middleware to your URLs.
Route::group(['middleware' => 'user'], function () {
Route::post('login', 'API\UserController#login');
Route::post('register', 'API\UserController#register');
Route::post('details', 'API\UserController#details');
});
});
For this to work you would need to have a usertype field in your users table that is set to user by default. Your usertype column should look like this;
$table->string('usertype')->nullable()->default('user');
1. Copy the existing functions of your controller and delete it.
2. Recreate your controller but this time specifying the location of were you want to place it, in the Controllers directory. e.g.
php artisan make:controller NameOfYourSubFolder\YourControllersName
3. Paste you functions.
Laravel has web route and API route, with different namespace/path configuration, where the issue such as "Class App\Http\Controllers\API\UserController does not exist" comes from.
Web route:
in controller:
<?php
namespace App\Http\Controllers;
use Auth;
use App\Application;
use Illuminate\Http\Request;
class HomeController extends Controller
{
in web.php route file:
Route::get('/home', 'HomeController#index')->name('home');
API route:
in controller:
the namespace should be App\Http\Controllers\API if you put your API controllers in \API path.
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CartController extends Controller
{
in api.php route file, add API\ to the controller path.
Route::get('/carts', 'API\CartController#index');

Auth::User() gives null in laravel 5.2

I am new to laravel. I am using multi authentication in my application. User and Admin are 2 type of user in my application. Iam developing change password for admin after logged in to application through admin's profile page. now I want to get logged in admin user detail so that i have use below code in my controller
if (Auth::guard('admin')->check()) {
$user = Auth::id();
echo '<pre>';
dd($user);
exit;
}
I have also add following code in controller
use App\Http\Controllers\Adminauth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Admin;
use Session;
use DB;
use App\Http\Controllers\Controller;
use Auth;
In route.php i have write following code
Route::group(['middleware' => ['admin']], function () {
//Login Routes...
Route::auth();
Route::get('admin/profile/change_password', 'Admin\AdminController#change_password');
});
But i am not able to get admin user detail. can anyone help me to solve this problem.
Try this
public function __construct() {
$this->middleware('auth:admin');
$this->middleware(function ($request, $next) {
$user = $this->user = Auth::user();
dd($user);
});
}
In routes
Route::get('/', function () {
//return view('welcome');
return view('auth.login');
});
Auth::user() is working only under auth middleware. You may call auth middleware on controller or call it on routes, but not on both.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class YourController extends Controller
{
public function __construct()
{
$this->middleware('auth')
}
public function yourFunction(Request $request)
{
$user = \Auth::user();
dd($user);
}
}
<?php
Route::get('your-uri', function () {
$user = \Auth::user();
dd($user);
})->middleware('auth');

Laravel route group middleware issue

I keep some laravel routes in the middleware auth group as:
Route::group(['middleware'=>'auth'],function(){
Route::controller('Activities', 'ActivitiesController');
Route::get('foo','FooController#getFoo');
.....
});
When I try to login to access these page, I am unable to login and url redirect to login page again and again. But If I use constructor as:
public function __construct()
{
$this->middleware('auth');
}
In those controllers It works perfectly. What is route group problem?
Route has a ::middleware class that you can use:
Routes > web.php
Route::middleware(['auth'])->group(function(){
Route::get('/activities', 'ActivitiesController#index');
});
You can also use Route::resource(); which I prefer. If you don't know what it does, here are the docs: https://laravel.com/docs/5.8/controllers#resource-controllers
This works for me , in route
Route::group(['middleware'=>'auth'],function(){
Route::controller('activities', 'ActivitiesController');
});
then controller
<?php namespace App\Http\Controllers;
class ActivitiesController extends Controller {
public function getIndex() {
return 'you are in;
}
}
on attempt to visit /activities I was redirected to login page , and on success back to \activities with 'you are in'.
In web.php:
$roleGeneral = role1.'~'.role2.'~'.role3.'~'.role4;
Route::group(['middleware' => ['permission.role:'.$roleGeneral]], function() {})
In Kernel.php:
protected $routeMiddleware = [...,
'permission.role' => \App\Http\Middleware\CheckPermission::class,
];
In CheckPermission.php:
public function handle($request, Closure $next, $role)
{
$roleArr = explode('~', $role);
$token = JWTAuth::getToken();
$user = JWTAuth::toUser($token);
$roleLogin = SysRoleModel::where('id', $user->role_id)->first();
if (in_array($roleLogin['name'], $roleArr)){
return $next($request);
}else{
return \Redirect::back()->withMessage('You are not authorized to access!');
}
}

Resources