Class App\Http\Controllers\API\UserController does not exist - laravel-5

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');

Related

Issues with Middleware | Too few arguments to function App\Http\Middleware\HasPermission::handle()

This is the error I'm receiving when I try to load my index page
Too few arguments to function App\Http\Middleware\HasPermission::handle(), 2 passed in /app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php on line 180 and exactly 3 expected
I'm using Spatie's Roles and Permissions Package, and have created a custom middleware HasPermission, to check if the user has the permissions to access and utilise the page they are trying to view.
This is the middleware
namespace App\Http\Middleware;
use Closure;
use Spatie\Permission\Models\Permission;
class HasPermission
{
public function handle($request, Closure $next,$permissions)
{
$permissions_array = explode('|', $permissions);
foreach($permissions_array as $permission){
if (!$request->user()->hasPermission($permission)){
return redirect()->back();
}
}
return $next($request);
}
}
The controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
use Illuminate\Support\Arr;
use App\Http\Middleware\HasPermission;
class UserController extends Controller
{
public function __construct() {
$this->middleware('permission:usermgmt.users|usermgmt.users.create|usermgmt.users.edit|users.delete', ['only' => ['index','store']]);
$this->middleware('permission:usermgmt.users.create', ['only' => ['create','store']]);
$this->middleware('permission:usermgmt.users.edit', ['only' => ['edit','update']]);
$this->middleware('permission:users.delete', ['only' => ['destroy']]);
}
And my routes
Route::middleware('HasPermission')->group(function() {
Route::get('/usermgmt/users', [App\Http\Controllers\UserController::class, 'index'])->name('usermgmt.users');
Route::resource('users', UserController::class);
Route::get('add-user', [App\Http\Controllers\UserController::class, 'create'])->name('usermgmt.users.create');
Route::delete('users/{user}',[App\Http\Controllers\UserController::class, 'destroy'])->name('users.destroy');
Route::get('users/{user}/edit', [App\Http\Controllers\UserController::class, 'edit'])->name('usermgmt.users.edit');
});
I have added the HasPermission middleware class to the Kernel.php, but am struggling to understand why I am receiving that error.
Any help would be appreciated, cheers.
I tried initially removing the Route Middleware Group and instead trying to do everything in the controller, and tried something like the below
$this->middleware(HasPermission::class, ['usermgmt.users','usermgmt.users.create','usermgmt.users.edit','users.delete'], ['only' => ['index','store']]);
But this would give me the same error as before.
Did you try this way:
public function handle(Request $request, Closure $next, ...$permissions)
{
foreach($permissions as $permission){
if (!$request->user()->hasPermission($permission)){
return redirect()->back();
}
}
return $next($request);
}
The in your controller, change the syntax:
$this->middleware('permission:usermgmt.users,usermgmt.users.create,usermgmt.users.edit,users.delete', ['only' => ['index','store']]);

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

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.

Routing No hint path defined for [module-name]

I am using Laravel5.5 and Module package. I have one student module and want to make this as a default for front-end, so committed code of the laravel's default routes/web.php
Here is my student's routes:
<?php
Route::group(['middleware' => 'web', 'namespace' => 'Modules\Student\Http\Controllers'], function() {
/** Frontend routes which does not require authentication
*
*/
Route::get('/', 'FrontEndController#index')->name('frontend.home');
Route::get('/program-search', 'FrontEndController#programs')->name('student.programs');
Route::get('/univeristy-search', 'FrontEndController#univerities')->name('student.universities');
});
And here is my controller code:
<?php
namespace Modules\Student\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Modules\Admin\Http\Models\ProgramCategory;
use Modules\University\Http\Models\Program;
use Modules\Student\Http\Models\Student;
use Modules\University\Http\Models\University;
class FrontEndController extends Controller
{
/**
* Display a listing of the resource.
* #return Response
*/
public function index()
{
return view('student::index');
}
/**
* Show all programs
*/
public function programs(){
$categories = ProgramCategory::orderBy('catagory_name')
->where('status', '=', 'active');
$programs = Program::orderBy('program_name')
->where([
['status', '=', 'active']
]);
$programs->categories = $categories;
return view('student::program_list')
->withPrograms( $programs );
}
public function univerities()
{
return view('student::university_list');
}
}
only first route '/' is working. when I try to access '/program-search' and '/univeristy-search' it throws an error like "No hint path defined for [sutdent]. (View: /var/www/development/unigatenew/Modules/Student/Resources/views/university_list.blade.php)".
What is the wrong I am doing? can anybody help out this?
The mistake was including the same file name inside view. Renaming file name which was included solved the problem.

laravel UserRequest $request error

laravel5.2,I create a UserRequest.php under Requests directory,but in controller,public function add(UserRequest $request) show error,but use public function add(Request $request) is normal.
UserRequest
namespace App\Http\Requests;
use App\Http\Requests\Request;
class UserRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'user_sn' => 'required|unique',
'user_name' => 'required',
'email' => 'required|unique',
'password' => 'required',
];
}
}
UserController
namespace App\Http\Controllers;
use App\Http\Requests\UserRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function add(UserRequest $request)
{
if ($request->get('dosubmit')) {
$validator = Validator::make($request->all(), $request
->rules(), $request->messages());
if ($validator->fails()) {
return redirect('user/add')->withErrors($validator)
->withInput();
}
}
$corporation_list = DB::table('corporation')->get();
$department_list = DB::table('department')->get();
return view('user.add', ['corporation_list' => $corporation_list, 'department_list' => $department_list]);
}
}
Route
Route::group(['middleware'],function (){
Route::any('user/add',['as'=>'user.add','uses'=>'UserController#add']);
});
There are usually 2 reasons you could be having this issue.
You've not added the use statement for the UserRequest.
At the top of your controller (above the class) add:
use App\Http\Requests\UserRequest
assuming that is the correct namespace.
You may need to run composer dump-autoload to make sure the class has been added to the autoloader.
Edit
Firstly, replace the add() method with the following methods:
public function create()
{
$corporation_list = DB::table('corporation')->get();
$department_list = DB::table('department')->get();
return view('user.add', compact('corporation_list', 'department_list'));
}
public function store(UserRequest $request)
{
// If you get to this point the validation will have passed
// Process the request
}
Then change your routes from:
Route::any('user/add',['as'=>'user.add','uses'=>'UserControl‌​ler#add'])
to:
Route::get('user/add', ['as' => 'user.add', 'uses' => 'UserControl‌​ler#create']);
Route::post('user/add', ['as' => 'user.store', 'uses' => 'UserControl‌​ler#store']);
Obviously, feel free to change the as in the Routes to whatever, they should unique though.
Lastly, I would suggest looking at Resource Controllers which is a RESTful approach.
The problem is that you have not identified UserController that you are using UserRequest file
use App\Http\Requests\UserRequest
It will solve the problem

Can't redirect users to custom URL after succesful login in Laravel

I am trying to redirect the users to a custom URL after a succesful login but it doesn't work. It keeps redirecting users to this dashboard page "/". I already deployed the website to the server so I can't clear the route cache with artisan.
Laravel version is 5.3.29
App\Http\Controllers\Auth\LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/my-profile';
protected $redirectPath = '/my-profile';
protected function redirectTo()
{
return '/my-profile';
}
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
}
App\Http\Middleware\RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check())
{
return redirect('/my-profile');
}
return $next($request);
}
}
I have read that there might be some problems with Laravel in this post. It says that there might be some problems with this file: /vendor/laravel/framework/src/Illuminate/Foundation/Auth/RedirectsUser.php, but this error was fixed in Laravel version 5.3.29, but I can see that it is fixed and 'returnTo' method should work.
/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RedirectsUser.php
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Support\Facades\Log;
trait RedirectsUsers
{
/**
* Get the post register / login redirect path.
*
* #return string
*/
public function redirectPath()
{
Log::info("RedirectsUsers");
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/homeeeee';
}
}
And my routes file:
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Auth::routes();
Route::get('/', 'HomeController#index');
Route::get('/home', 'HomeController#index');
Route::get('/confirm-your-email', 'Auth\ConfirmEmailController#confirm_email');
Route::get('/confirm-email/{register_token}', 'Auth\ConfirmEmailController#index');
Route::get('/my-profile', ['as' => 'my-profile' , 'uses' => 'MyProfileController#show', 'userAlert' => null]);
Route::post('/my-profile/edit-about', 'MyProfileController#editAbout');
Route::post('/my-profile/edit-profile-picture', 'MyProfileController#editProfilePicture');
Route::get('/search/company', 'SearchController#searchCompany');
Route::get('/my-profile/add-job', 'MyProfileController#addJobPage');
Route::get('/my-profile/add-job/{id}', 'MyProfileController#addCompanyJobPage');
Route::post('/my-profile/add-a-job', 'MyProfileController#addJob');
Route::post('/my-profile/delete-job', 'MyProfileController#deleteJob');
Route::get('/users/{id}', ['as' => 'users', 'uses' => 'UserController#show']);
Route::get('/rate/user/{id}', ['as' => 'rate', 'uses' => 'RateController#showUserRate']);
Route::post('/rate/rate-user/{id}', 'RateController#rateUser');
Route::get('/invite-user-rate/{id}', 'RateController#showInviteUserToRateYou');
Route::post('/invite-rate/user/{id}', 'RateController#inviteUserToRateYou');
Route::get('/company/{id}', ['as' => 'company', 'uses' => 'CompanyController#show']);
Route::get('/rate/company/{id}', 'RateController#showCompanyRate');
Route::post('/rate/rate-company/{id}', 'RateController#rateCompany');
Route::get('/search/{page}/results/', 'SearchController#showSearchCompanies');
Route::get('/search/{page}/people/results', 'SearchController#showSearchPeople');
Route::get('/leave-a-rating/', 'SearchController#showLeaveARating');
Route::get('/invite', ['as' => 'invite', 'uses' => 'OtherAuthentificatedController#showInvite']);
Route::post('/email-invite', 'OtherAuthentificatedController#emailInvite');
Route::get('/contact', 'OtherController#showContact');
Route::post('/send-contact-email', 'OtherController#sendContact');
Route::get('/tyfcu', 'OtherController#thankYouForContactingUs');
you can run this command on your server for clear chache
if you want
php artisan cache:clear
and for redirecting you can redirect by this method
return Redirect::route('/my-profile');
think this might be help you

Resources