Users Controller does not exist - laravel

I'm building a CMS in Laravel 5.8 with an in-built Authentication system. My app was working fine but suddenly it starts giving me an error as ReflectionException : Class App\Http\Controllers\Users does not exist on command php artisan route:list -v. However, if i define a new resource route, then that new route page works fine. It means, route file is getting saved but gives error while listing the routes.
I have not created any file named as Users but my user controller file name is UserController
Below is the structure of my application:
cms -> project folder
app
Http
Controllers
Auth
RegisterController.php
LoginController.php and other Auth files
backend
UserController.php and my other controller files
Below is my route file
Auth::routes();
Route::group(['as'=>'cms.' ,'prefix'=>'cms'],function(){
Route::get('/', 'backend\Dashboard#index')->name('dashboard');
Route::resource('/user-management', 'backend\UserController');
});
Below is my UserController file residing in backend folder
<?php
namespace App\Http\Controllers\backend;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use Auth;
use App\Models\backend\Admin;
use App\Models\backend\Menu;
use App\Models\backend\Submenu;
use Config;
use illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin');
}
public function AuthRouteAPI(Request $request)
{
return $request->user();
}
public function index()
{
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
$cms_users = Admin::withTrashed()->get();
return view('backend.pages.users.index', ['arrUserMenu'=>$arrUserMenu, 'cms_users'=>$cms_users]);
}
public function create()
{
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
return view('backend.pages.users.create', ['arrUserMenu'=>$arrUserMenu]);
}
public function store(Request $request)
{
$rules = [
'name' => 'required|min:'.Config::get('cms_const.USER_NAME_MIN_LEN').'|max:'.Config::get('cms_const.USER_NAME_MAX_LEN').'|regex:/(^[A-Za-z ]+$)+/',
'usrmail' => 'required|email|unique:cms_users,email|max:'.Config::get('cms_const.USER_EMAIL_MAX_LEN'),
'usrname' => 'required|min:'.Config::get('cms_const.USER_ID_MIN_LEN').'|max:'.Config::get('cms_const.USER_ID_MAX_LEN').'|regex:/(^[A-Za-z0-9._]+$)+/|unique:cms_users,username',
'usrpwd' => 'required|min:'.Config::get('cms_const.USER_PWD_MIN_LEN').'|max:'.Config::get('cms_const.USER_PWD_MAX_LEN').'|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-_]).{7,}$/'
];
$msgs = [
'name.required' => 'Please enter name',
'name.min' => 'Name should not be less then '.Config::get('cms_const.USER_NAME_MIN_LEN').' characters',
'name.max' => 'Name should not be more then '.Config::get('cms_const.USER_NAME_MAX_LEN').' characters',
'name.regex' => 'Only alphabets are allowed in name',
'usrmail.required' => 'Please enter email',
'usrmail.email' => 'Invalid email',
'usrmail.unique' => 'Email already exist',
'usrmail.max' => 'Email should not be more then '.Config::get('cms_const.USER_EMAIL_MAX_LEN').' characters',
'usrname.required' => 'Please enter the user name',
'usrname.min' => 'User name should not be less then '.Config::get('cms_const.USER_ID_MIN_LEN').' characters',
'usrname.max' => 'User name should not be more then '.Config::get('cms_const.USER_ID_MAX_LEN').' characters',
'usrname.regex' => 'Only Alphabets, Numbers, Dot and Underscore allowed in user name',
'usrname.unique' => 'User name already exist',
'usrpwd.required' => 'Please enter the password',
'usrpwd.min' => 'Password should not be less then '.Config::get('cms_const.USER_PWD_MIN_LEN').' characters',
'usrpwd.max' => 'Password should not be more then '.Config::get('cms_const.USER_PWD_MAX_LEN').' characters',
'usrpwd.regex' => 'Invalid password format',
];
$this->validate($request, $rules, $msgs);
Admin::create([
'name' => $request->name,
'username' => $request->usrname,
'password' => bcrypt($request->usrpwd),
'email' => $request->usrmail,
]);
return redirect()->route('cms.user-management.index')->with('success','New user account created successfully.');
}
public function edit($id)
{
if(!$id)
{
return redirect()->route('cms.user-management.index');
die;
}
$arrRecord = Admin::find($id);
if(is_null($arrRecord))
{
return redirect()->route('cms.user-management.index')->withErrors(['error'=>'Record you are trying to edit does not exist']);
die;
}
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
return view('backend.pages.users.edit', ['arrUserMenu'=>$arrUserMenu, 'arrRecord'=>$arrRecord]);
}
public function update(Request $request, $id)
{
$rules = [
'name' => 'required|min:'.Config::get('cms_const.USER_NAME_MIN_LEN').'|max:'.Config::get('cms_const.USER_NAME_MAX_LEN').'|regex:/(^[A-Za-z ]+$)+/',
'usrmail' => 'required|email|max:'.Config::get('cms_const.USER_EMAIL_MAX_LEN'),
'usrpwd' => 'nullable|min:'.Config::get('cms_const.USER_PWD_MIN_LEN').'|max:'.Config::get('cms_const.USER_PWD_MAX_LEN').'|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-_]).{7,}$/'
];
$msgs = [
'name.required' => 'Please enter name',
'name.min' => 'Name should not be less then '.Config::get('cms_const.USER_NAME_MIN_LEN').' characters',
'name.max' => 'Name should not be more then '.Config::get('cms_const.USER_NAME_MAX_LEN').' characters',
'name.regex' => 'Only alphabets are allowed in name',
'usrmail.required' => 'Please enter email',
'usrmail.email' => 'Invalid email',
'usrmail.max' => 'Email should not be more then '.Config::get('cms_const.USER_EMAIL_MAX_LEN').' characters',
'usrpwd.min' => 'Password should not be less then '.Config::get('cms_const.USER_PWD_MIN_LEN').' characters',
'usrpwd.max' => 'Password should not be more then '.Config::get('cms_const.USER_PWD_MAX_LEN').' characters',
'usrpwd.regex' => 'Invalid password format',
];
$this->validate($request, $rules, $msgs);
$arrRecord = Admin::find($id);
if(is_null($arrRecord))
{
return redirect()->route('cms.user-management.index')->withErrors(['error'=>'Record you are trying to edit does not exist']);
die;
}
$arrRecord->name = $request->input('name');
$arrRecord->email = $request->input('usrmail');
if($request->input('usrpwd'))
{
$arrRecord->password = bcrypt($request->input('usrpwd'));
}
$arrRecord->save();
return redirect()->route('cms.user-management.index')->with('success','User account details updated successfully.');
}
public function destroy($id)
{
try
{
$user = Admin::findOrFail($id);
$user->delete();
return response()->json(['success'=>'Record successfully deleted', 'status'=>'Suspended']);
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
return response()->json(['error'=>'Record you are trying to delete does not exist']);
}
}
}
I have tried the below commands and they all run successfully but none resolved the error
php artisan clear-compiled
composer dump-autoload
php artisan optimize
php artisan route:cache
Don't know from where this Users controller class in being referenced.
Can anyone help me in this regard as I'm badly stuck in my development.
Much Regards,
Javed

#ClémentBaconnier the error is resolved now. I made the changes in api.php to Route::middleware('auth:api')->get('/user', 'backend\Users#AuthRouteAPI'); and now all my routes are listed. Thanks u soooo much for ur advice.

Related

How to upload file in relationship hasOn<->belongsTo Laravel Backpack

Can be possible to store a file uploaded to a related table?
Scenario: I have a usres table in database and another one pictures. Users Model have the following function
public function picture()
{
return $this->hasOne(Picture::class);
}
And the Picture Model have the following function.
public function user_picture()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
Is possible to store the picture in pictures database table (id, user_id, img_path) from the UserCrudController store() function?
try something like this
public function store(Request $request)
{
Picture::create([
'user_id' => // get the user id from $request or auth()->user(),
'img_path' => $request->file('image')->store('images', 'public'),
]);
return // your view or something else
}
Let's say it is a registration form that need to insert an image. Instead of using the Picture model directly you can just do this :
public function store(Request $request)
{
$request->validate(...);
$user = User::create(...);
//It will ensure that the image belongs to the user.
$user->picture()->create([
'image_path' => $request->file('image')->store('images');
])
}
I resolved the issue with the following steps.
As per Laravel Backpack I added the input field in the Blade:
#include('crud::fields.upload', ['crud' => $crud, 'field' => ['name' => 'img1', 'label' => 'Image 1', 'type' => 'upload', 'upload'=> true, 'disk'=>'uploads', 'attributes' => ['id' => 'img1', 'capture' => 'user']]])
After this I added the function in the User Controller as follow:
$request->validate(['img1' => 'mimes:jpg,png,jpeg|max:5120']);
$fileModel = new Picture;
if($request->file()) {
$fileName1 = time().'_'.$request->img1->getClientOriginalName();
$filePath1 = $request->file('img1')->storeAs('uploads', $fileName1, 'public');
$fileModel->name = time().'_'.$request->img1->getClientOriginalName();
$fileModel->img1 = '/storage/' . $filePath1;
$fileModel->save();
}
With these lines of code I was able to store the related Picture with the User.
Thank you all for the guidelines.

Pusher trigger() method is giving error 500

So I was building chat functionality in laravel for a website using Pusher , everything was working fine till yesterday. But when I run the chat module again, I found out that trigger() method is giving error (Internal server error).
`
use App\Http\Controllers\Controller;
use App\Model\Chatting;
use App\Model\Seller;
use App\Model\Shop;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Events\Message;
use Pusher\Pusher;
class ChattingController extends Controller
{
public function seller_message_store(Request $request)
{
//return 'hello';
if ($request->message == '') {
Toastr::warning('Type Something!');
return response()->json('type something!');
} else {
$shop_id = Shop::where('seller_id', auth('seller')->id())->first()->id;
$message = $request->message;
$time = now();
DB::table('chattings')->insert([
'user_id' => $request->user_id, //user_id == seller_id
'seller_id' => auth('seller')->id(),
'shop_id' => $shop_id,
'message' => $request->message,
'sent_by_seller' => 1,
'seen_by_seller' => 0,
'created_at' => now(),
]);
//return auth('seller')->user()->seller_plan_id;
if(auth('seller')->user()->seller_plan_id>2){
// pusher
$options = array(
'cluster' => 'ap2',
'useTLS' => false
);
$pusher = new Pusher('app auth key','app secret','app_id',$options);
//return $request->user_id;
$data = ['from' => auth('seller')->id(), 'to' => $request->user_id,'message'=>$request->message]; // sending from and to user id when pressed enter
$pusher->trigger('channel-name', 'event', $data);//here is the issue
}
return response()->json(['message' => $message, 'time' => $time]);
}
}
}
`
If I comment out the trigger line, it gives no error.
It was working completely fine till yesterday.
The version 5.0 of pusher is broken and has given me errors in the past.
What you could do is, change
"pusher/pusher-php-server": "5.0"
to
"pusher/pusher-php-server": "^5.0"
And then run the command composer update

How can I get api/register with Passport in laravel working?

Following a tutorial: https://www.twilio.com/blog/build-secure-api-php-laravel-passport
I manAged to get Laravel/Passport installed formy Laravel Api and Vue application.
I managed to create attoken with:
localhost:8000/oauth/token
get the login working in Postman:
localhost:8000/api/login?email=jennie05#example.com&password=password
Now when I try to register a user I get returned to the home-page.
I do get some "undefined method" errors from VS Code, but they show up in the login method,
and not in the failinf register method:
Here is the controller:
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
class AuthController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:55',
'email' => 'email|required|unique:users',
'password' => 'required|confirmed'
]);
$validatedData['password'] = bcrypt($request->password);
$user = User::create($validatedData);
$accessToken = $user->createToken('authToken')->accessToken;
return response([ 'user' => $user, 'access_token' => $accessToken]);
}
public function login(Request $request)
{
$loginData = $request->validate([
'email' => 'email|required',
'password' => 'required'
]);
if (!auth()->attempt($loginData)) {
return response(['message' => 'Invalid Credentials']);
}
$accessToken = auth()->user()->createToken('authToken')->accessToken;
return response(['user' => auth()->user(), 'access_token' => $accessToken]);
}
}
In these are the routes in api.php:
Route::post( 'register', 'App\Http\Controllers\API\AuthController#register');
Route::post( 'login', 'App\Http\Controllers\API\AuthController#login');
// Route::prefix('v2')->group(function(){ // prefix voor versie 2
Route::apiResource('/cards', 'App\Http\Controllers\CardController');
Route::apiResource('/games', 'App\Http\Controllers\GameController');
//Route::get('games', 'App\Http\Controllers\GameController#index')->middleware('auth:api');
//Route::post('games', 'App\Http\Controllers\GameController#store')->middleware('auth:api');
//Route::get('games/{id}', 'App\Http\Controllers\GameController#show')->middleware('auth:api');
//Route::put('games/{id}', 'App\Http\Controllers\GameController#update')->middleware('auth:api');
//Route::delete('games/{id}', 'App\Http\Controllers\GameController#destroy')->middleware('auth:api');
Route::get('/gameByPin/{pin}', 'App\Http\Controllers\GameController#searchPin');
Route::apiResource('/speler', 'App\Http\Controllers\SpelerController');
//});
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
is there anyone who can help troubleshooting this?
Postman does not give me errors, just the redirect to homepage..
Wow,
Thanks Patrick, your the best.
Just checked all the steps in the documentation.
reran the installation command I ran when setting up everything. ( Apperently need to do this twice ?!):
php artisan passport:install
It returned:
Encryption keys already exist. Use the --force option to overwrite them.
Personal access client created successfully.
Client ID: 5
Client secret: ikJEfthxxxxxxxxxxxxxxxxxxxxxxxxxxxBjJ36
Password grant client created successfully.
Client ID: 6
Client secret: H42lpMxxxxxxxxxxxxxxxxxxxxxxxxxxxQGZgH
Now the post request results in a token!
The error VS Code shows d for "use HasApiToken" is:
Undefined type 'Laravel\Passport\HasApiTokens'.intelephense(1009)

Find data before validate form request laravel

I want to update the data using the request form validation with a unique email role, everything works normally.
Assume I have 3 data from id 1-3 with url:
127.0.0.1:8000/api/user/update/3
Controller:
use App\Http\Requests\Simak\User\Update;
...
public function update(Update $request, $id)
{
try {
// UPDATE DATA
return resp(200, trans('general.message.200'), true);
} catch (\Exception $e) {
// Ambil error
return $e;
}
}
FormRequest "Update":
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->id,
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
but if the updated id is not found eg:
127.0.0.1:8000/api/user/update/4
The response gets The email has already been taken.
What is the solution so that the return of the data is not found instead of validation first?
The code looks like it should work fine, sharing a few things below that may help.
Solution 1: Check if $this->id contains the id you are updating for.
Solution 2: Try using the following changes, try to get the id from the URL segment.
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->segment(4),
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
Sharing one more thing that may help you.
Some person uses Request keyword at the end of the request name. The Update sounds generic and the same as the method name you are using the request for. You can use UpdateRequest for more code readability.
What I understand from your question is, you need a way to check if the record really exists or not in the form request. If that's the case create a custom rule that will check if the record exists or not and use that rule inside your request.
CheckRecordRule
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class CheckRecordRule implements Rule
{
protected $recordId;
public function __construct($id)
{
$this->recordId = $id;
}
public function passes($attribute, $value)
{
// this will check and return true/false
return User::where('id', $this->recordId)->exists();
}
public function message()
{
return 'Record not found.';
}
}
Update form request
public function rules()
{
return [
'email' => 'required|email|unique:users,email,' . $this->id.'|'. new CheckRecordRule($this->id),
];
}
So when checking for duplicate it will also check if the record really exists or not and then redirect back with the proper message.

Laravel auth attempt not working or returning false always?

I've been looking all over the place (I checked all the other duplicate questions and answers ), no luck. I don't understand what am I doing wrong, all the values are coming from post, but Auth:attempt keeps on failing/returning false, if I try to implement login manually it won't authenticate as I am expecting, Also do I have to make or use separate methods like for validation, credentials, username ..etc ?
Here is my login Controller > login method
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'usermail' => 'required|max:255',
'password' => 'required_with:usermail',
],[
'password.required_with' => "The password field is empty."
]);
if ($validator->fails()) {
return redirect()
->route('admin.login')
->withErrors($validator)
->withInput();
}
$usermail = $request->get('usermail');
$password = $request->get('password');
$remember = $request->get('rememberMe');
if(filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
$isEmailExist = User::where('user_email',$usermail)->first();
if($isEmailExist != null){
if(Auth::attempt([
'user_email' => $usermail,
'user_pass' => $password
])){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the email address <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid email address.'
]);
}
}else{
$isUsernameExist = User::where('user_login',$usermail)->first();
if($isUsernameExist != null){
if(Auth::attempt([
'user_login' => $usermail,
'user_pass' => $password
],$remember)){
return redirect()->intended('admin/dashboard');
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: The password you entered for the username <strong>'.$usermail.'</strong> is incorrect. Lost your password?'
]);
}
}else{
return back()->with([
'message' => '<strong>ERROR</strong>: Invalid username. Lost your password?'
]);
}
}
}
And this is my user migration schema,
Schema::create('vw_users', function (Blueprint $table) {
$table->bigIncrements('ID');
$table->string('user_login','60')->unique()->default('');
$table->string('user_pass');
$table->string('user_email','100')->unique()->default('');
$table->rememberToken();
});
Here is how i seed user,
User::create([
'user_login' => 'admin',
'user_pass' => Hash::make("123456"),
'user_email' => 'admin#gmail.com',
]);
OK OK OK,
I made it work, I think in laravel framework we can only create the column name for the password is "password" field in database authentication table.
I updated the following changes:-
I renamed the password field name from migration schema the "user_pass" to "password". (Also updated in login controller and user model).
Added following code into user model:-
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
...
}
I checked twice to confirm so I revert back it didn't work.
If i make any sense to anyone please let me know and help me understand.
I've looked into very similar posts like this Laravel: How can i change the default Auth Password field name
can I please have a reference book or blog for all the laravel predefined libraries and functions? I know the vendor folder is full of surprises but still, I need more references.
Thank you so much for your time.

Resources