Laravel User Class was not found - laravel

I ran into a Laravel problem trying to access the build-in class on Laravel named 'User', basically I want to create new users. But I get the error saying this: 'Undefined type 'App\Http\Controllers\User'.intelephense(1009)`. What is the fix?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public function register(Request $request){
$validator = Validator::make($request->all(),[
'name' => 'required',
'email' => 'required|email',
'password' => 'required'
]);
if($validator->fails()){
return response()->json(['status_code']);
};
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
return response()->json([
'status_code' => 200,
'message' => 'User was saved!'
]);
}
}

You forgot to import the User class:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
// this is the default for Laravel 8+, before it was App\User
use App\Models\User;
class AuthController extends Controller
{
public function register(Request $request){
$validator = Validator::make($request->all(),[
'name' => 'required',
'email' => 'required|email',
'password' => 'required'
]);
if($validator->fails()){
return response()->json(['status_code']);
};
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
return response()->json([
'status_code' => 200,
'message' => 'User was saved!'
]);
}
}

Related

laravel 8 form validation stop working and throw an error

here is my code for validate request
public function signup(Request $request) {
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|unique:users|max:255',
'password' => 'required|min:6|confirmed',
]);
$data = array();
$data['name'] = $request->name;
$data['email'] = $request->email;
$data['password'] = Hash::make($request->password);
DB::table('users')->insert($data);
return $this->login($request);
}
when I try this validation not working how can I fix this?
for example
when this data for validation
'name' = "",(empty)
'email' = "test2#mail.com"
'password'= "test2#mail.com"
and I expect my validation should work but its throw BadMethodCallException error
here is my route (via API)
<?php
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('login', [App\Http\Controllers\AuthController::class, 'login']);
Route::post('logout', [App\Http\Controllers\AuthController::class, 'logout']);
Route::post('refresh', [App\Http\Controllers\AuthController::class, 'refresh']);
Route::post('me', [App\Http\Controllers\AuthController::class, 'me']);
//custom
Route::post('signup', [App\Http\Controllers\AuthController::class, 'signup']);
});
NOTE: am check this VIA postman
You can do it another way with the laravel Validator class. Please add use Validator class before your class declaration.
Then create your function like this:
public function signup(Request $request) {
$validate = array(
'name' => 'required',
'email' => 'required|unique:users|max:255',
'password' => 'required|min:6|confirmed',
);
$validatedData = Validator::make($request->all(),$validate);
if(!validatedData->fails()) {
return $validatedData->errors();
}else{
$data = array();
$data['name'] = $request->name;
$data['email'] = $request->email;
$data['password'] = Hash::make($request->password);
DB::table('users')->insert($data);
return $this->login($request);
}
}

Laravel Eloquent\Collection::save does not exist

I got this error
"Method Illuminate\Database\Eloquent\Collection::save does not exist."
when i'm trying to Register User API.
i dont know what 's wrong with it...
My AuthController
public function register(Request $request)
{
$request->validate([
'name' => 'required|min:3',
'email' => 'required|email',
'password' => 'required|between:6,25',
]);
$user = User::all();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return response()->json([
'registered' => true,
'token' => $user->createToken('token')->accessToken
]);
}
Any help? Thanks....
$user = User::all(); return a collection of all users in database, you should replace it with $user = new User;, which return a new User object.
Change code to
public function register(Request $request)
{
$request->validate([
'name' => 'required|min:3',
'email' => 'required|email',
'password' => 'required|between:6,25',
]);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return response()->json([
'registered' => true,
'token' => $user->createToken('token')->accessToken
]);
}

Laravel - Call to undefined method App\\User::getAvatarUrlAttribute()

I am using Laravel-5.8 as backend for an application. I have written all the Api for the endpoints.
Laravel: ApiController
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\User;
use App\Activity;
use Avatar;
use Storage;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Mail;
use Audit;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class ApiController extends Controller
{
public $successStatus = 200;
public function __construct() {
}
protected function guard()
{
return Auth::guard();
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()->email
], 200);
}
public function returnResponse($success, $data, $errorCode = 0, $message = false) {
$response = array();
$response['success'] = $success;
$response['message'] = isset($message) ? $message : '';
if ($errorCode) {
$response['errorCode'] = isset($errorCode) ? $errorCode : 0;
}
$response['data'] = $data;
return response()->json($response, 200);
}
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|string|email|max:255|unique:users',
// 'phone' => 'required',
// 'password' => 'required',
'password' => 'required|string|min:6',
// 'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$input = $request->all();
// code for check email / username / phone exist or not
if(isset($input['email'])){
$alreadyExist = User::where(function ($query) use ($input) {
$query->where('email', '=', $input['email']);
})->get();
}
if (count($alreadyExist->toArray()) > 0) {
return $this->returnResponse(false, ['error' => 'Email Already Exist'], 1, 'User Data Already Exist');
}
// code for register user
$user = new User();
$user->name = $input['name'];
$user->email = $input['email'];
$user->password = bcrypt($input['password']);
$user->save();
$mainData = array();
$mainData['to'] = $user->toArray()[0]['email'];
$mainData['from'] = "support#tsllimited.com";
$mainData['subject'] = "Successful Signup";
$mainData['content'] = "Your signup was successful, you can login with the credentials.";
$this->mailSend($mainData);
Activity::create([
'user_id' => $user->id,
'owner_id' => $user->client_id,
'type' => "User Registration",
'title' => "Successful Signup of User",
'state' => 2,
'created_at'=> date('Y-m-d H:i:s')
]);
$success = array();
$success['user_id'] = $user->id;
$success['user']=$user;
return $this->returnResponse(true, $success, 0, 'User registered successfully');
}
public function login(Request $request) {
$authenticated = false;
$validator = Validator::make($request->all(), [
'email' => 'required|string|email',
'password' => 'required|string',
'remember' => 'boolean'
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$remember = request('remember') ? true : false;
if (Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')], $remember)) {
$authenticated = true;
}
if ($authenticated == true) {
$user = Auth::guard('web')->user();
$date = date('Y-m-d');
$success['userId'] = $user->id;
$success['avatar'] = url('/storage/user') . '/' . $user->avatar;
$success['email'] = $user->email;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->returnResponse(true, $success);
} else {
$success = array();
return $this->returnResponse(false, $success, 1, 'Invalid User Credential');
}
}
}
api.php
Route::group([
], function () {
Route::post('login', 'ApiController#login');
Route::post('register', 'ApiController#register');
Route::post('forgetPassword', 'ApiController#forgetPassword');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
});
I stalled and configured Laravel Passport and also Spatie. I have checked the code and don't know what the error really is. When I test the resgister Post Request on the POSTMAN, I got the error shown below:
See the POSTMAN preview side:
What could have caused the error and how do I resolve it?
You do not have the column avatar on your users table.
Maybe you did not use the trait you need in your User class
class User extends Authenticatable {
use HasAvatar;
// ...
}
I eventually solved the problem myself. The issue is that, I forgot to add:
public function getAvatarUrlAttribute()
{
return Storage::url('avatars/'.$this->id.'/'.$this->avatar);
}
to User Model.
Thanks

Auth::login($user) in laravel not able to login the user

I am using laravel 5.4 and Auth::login($user) is showing Type error:
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must
implement interface Illuminate\Contracts\Auth\Authenticatable,
instance of Illuminate\Database\Eloquent\Builder given, called in
/home/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on
line 294
My User.php file is:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'role', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My AuthController.php is:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Auth;
use Illuminate\Support\Facades\Input;
use \Hash;
class AuthController extends Controller
{
//
public function register(Request $request){
$this->validate($request, [
'name' => 'required|max:30',
'email' => 'required|email|unique:users',
'regpassword' => 'required|alpha_num|confirmed'
]);
/*$user = new User();
$user['name'] = $request['name'];
$user['email'] = $request['email'];
$user['password'] = bcrypt($request['password']);
$user['role'] = 'user';
$user->save();
*/
$user = User::create(array(
'email' => Input::get('email'),
'name' => Input::get('name'),
'password' => Hash::make(Input::get('password')),
'role' => 'user'));
return 'success';
}
public function userLogin(Request $request){
$this->validate($request,[
'email' => 'required|email',
'password' => 'required'
]);
$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');
if($user){
Auth::login($user);
return $next($request);
}
else{
return redirect()->back();
}
}
}
My web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::post('/register', 'AuthController#register');
Route::post('/UserLogin','AuthController#userLogin');
Your problem is this:
$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');
Is lacking a call to get the result set back from the query. Add ->first().
What it' saying is:
You gave me an instance of the query Builder
But
I wanted a model that extends the authenticatable class
If you open App\User, you'll see that it does indeed extend this class:
class User extends Authenticatable {
This:
$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');
is not the way you will get the user.
Instead of
$user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');
if($user){
Auth::login($user);
return $next($request);
}
else{
return redirect()->back();
}
you could use:
$logged = auth()->attempt(
['email' => $request['email'],
'password' => $request['password'],
'role' => 'user']);
if($logged) {
return $next($request); // probably it won't work. This is fine in middleware but not in controller
}
else{
return redirect()->back();
}
Solved my problem as following:
$user = User::where('email', '=' $request['email'])->where('role','=','user')->first();
if(Hash::check($request['password'],$user->password)){
Auth::login($user);
return 'success';
}

Append errors with custom error

How can i append the $errors->all() array? Like a custom error message... Searched on the internet but i did not find anything.
In my view:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
My controller:
<?php
namespace App\Http\Controllers\Admin;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
/**
* #param Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email|exists:users,email',
'password' => 'required',
]);
if ($user = Auth::attempt([
'email' => $request->email,
'password' => $request->password
])) {
/** #var $user User */
if ($user->isAdmin()) {
return redirect()
->route('admin.dashboard');
}
}
// wrong email or password
return redirect('/admin/login');
}
}
First use Validator facade for validation and then
$inputs = $request->all();
$rules = array(
'email' => 'required|email|exists:users,email',
'password' => 'required',
);
$messages = array();
$validator = Validator::make($inputs,$rules,$messages);
$validator->after(function($validator) {
//do some stuff
$validator->errors()->add('error', 'error messgae');
})
custom error message :
return redirect('/admin/login')->withErrors([
'error_key' => 'error_message'
]);
and if you want flush old inputs :
return redirect('/admin/login')->withInput()->withErrors([
'error_key' => 'error_message'
]);
You should write this
<?php
namespace App\Http\Controllers\Admin;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
/**
* #param Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email|exists:users,email',
'password' => 'required',
]);
if ($user = Auth::attempt([
'email' => $request->email,
'password' => $request->password
])) {
/** #var $user User */
if ($user->isAdmin()) {
return redirect()
->route('admin.dashboard');
}else {
return redirect('/admin/login')->>with('errors', 'Sorry!!! something went wrong. please try again.');
}
}else {
return redirect('/admin/login')->>with('errors', 'Sorry!!! something went wrong. please try again.');
}
// wrong email or password
return redirect('/admin/login');
}
}
You can add to errors while using Validator Facade for validation:
$validator = Validator::make(
[
'email' => $request->email,
'password' => $request->password
],
[
'email' => 'required|email|exists:users,email',
'password' => 'required',
]
);
$validator->errors()->add('custom-error', 'my custom error');

Resources