On laravel 9.19, laravel/passport": "^11.3 site
I added some more custom fields into users table, and making login method with code like :
public function login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User login successfully.');
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}
When I read logged user :
$user = Auth::user();
\Log::info($user);
$user has no my custom fields.
Just common app/Models/User.php :
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
How have I to define my custom fields ?
"laravel/framework": "^9.19",
"laravel/passport": "^11.3",
Thanks in advance!
Related
I want a simple program that shows the user profile after login. I used session and middleware. But it is saying that the name property is null. Please help me solve this error. I have used User model. The value of the properties are not retrieving from the database.
Blade code:
<h1>Profile</h1>
<h2>Welcome Mr/Ms {{$user->name}}</h2>
Logout
Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Models\PremiumModel;
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $timestamp = false;
protected $fillable = [
'name',
'email',
'password',
'type',
'email_verified_at',
'pro_pic',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
function admin()
{
return $this->hasOne('App\Models\admin', 'user_id', 'admin_id');
}
function premium()
{
return $this->hasMany(PremiumModel::class, 'user_id', 'user_id');
}
}
Controller code:
function profile()
{
$user = User::where('user_id',session()->get('logged'))->first();
return view('premium.profile')->with('user',$user);
}
Here, logged is the middleware.
You can try hasOne in the User model:
public function premium()
{
return $this->hasOne(PremiumModel::class, 'user_id', 'user_id');
}
Because hasMany returned an array, but hasOne returned just a single Object
I get a token it has 40 character random string like this...
1|z5F4SMYZRxLo8ScUYMmnExdYtQoJ8eaftQevF0Pa
And I want 240 character random string like this...
1|nvbqwunxjyxujtnqnqcxzhintxyswmsjdunbmuhkifbncgrucxchzirgkybtbcadrjjtjunroewmpidxwiobcvimbolzcjlmeddvusgqzmcakffyzqllbzihnvbqwunxjyxujtnqnqcxzhintxyswmsjdunbmuhkifbncgrucxchzirgkybtbcadrjjtjunroewmpidxwiobcvimbolzcjlmeddvusgqzmcakffyzqllbzih
Please help me for how to increase the length of the Laravel Sanctum Token
Open file: app/Models/User.php then
Check if this file is used Laravel\Sanctum\HasApiTokens trait
Override method: createToken like this:
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
use Laravel\Sanctum\NewAccessToken;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Create a new personal access token for the user.
*
* #param string $name
* #param array $abilities
* #return \Laravel\Sanctum\NewAccessToken
*/
public function createToken(string $name, array $abilities = ['*'])
{
$token = $this->tokens()->create([
'name' => $name,
'token' => hash('sha256', $plainTextToken = Str::random(240)),
'abilities' => $abilities,
]);
return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken);
}
}
You can use:
$user->createToken('your name token')->plainTextToken;
I'm making a simple user authentication with laravel passport, I made an AuthController where I put login and register functions, whenever I try to login with the right email and password I get
{"message":"invalid user"}
its like the attempt() method always returning false, I am using laravel 8.
here is AuthController.php
<?php
namespace App\Http\Controllers;
use http\Env\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function login(Request $request){
if(Auth::attempt($request->only('email', 'password'))){
$user=Auth::user();
return $user;
}
return response([
'message'=> 'invalid user'
], 401);
}
}
user model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname',
'lastname',
'email',
'password',
'phone',
'skype',
'birthdate',
'address',
'postalcode',
'city',
'country',
'status',
'image',
'description',
'geo_lat',
'geo_lng'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
AuthServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
I've been searching everywhere for a solution to my issue. I've created a welcome email, created the Mailable, Controller, and View. But for some reason, the $user isn't showing in the email itself. It's blank. Am I missing something?
Mailable
<?php
namespace App\Http\Mail;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class Welcome extends Mailable
{
use Queueable, SerializesModels;
public $user;
/**
* #return void
*/
public function _construct(User $user)
{
$this->user = $user;
}
/**
*#return $this
*/
public function build()
{
return $this->view('emails.welcome')->subject('Welcome to');
}
}
Controller
<?php
namespace App\Http\Controllers\Auth;
use Mail;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Auth;
use App\Http\Mail\Welcome;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'mobile' => 'required',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'mobile' => $data['mobile'],
'password' => bcrypt($data['password']),
'payment_mode' => 'CASH',
]);
Mail::to($data['email'])->send(new Welcome($user));
return $user;
// send welcome email here
}
/**
* Show the application registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
return view('user.auth.register');
}
}
View (shortened to show problem)
Welcome {{ $user->first_name }}
User
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens,Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'mobile', 'picture', 'password', 'device_type','device_token','login_by', 'payment_mode','social_unique_id','device_id','wallet_balance'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token', 'created_at', 'updated_at'
];
}
As was mentioned, everything passes successfully, however, in the email itself, the name of the user is blank. Please help!
I got it working for anyone else dealing with same issue. I changed the register controller and just skipped the mailable entirely. In other words, I didn't need a separate mailable. Below is the result.
Mail::send('emails.welcome', [
'first_name' => $data['first_name'],
'email' => $data['email']
], function ($mail) use($data) {
$mail->from('Whatever', 'site/company name');
$mail->to($data['email'])->subject('Whatever');
});
return $user;
And in the view I just pass the first name like so
Welcome {{ $first_name }}
My application in Laravel is presenting the following error after registering:
"BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::getAuthIdentifierName()"
The error only appears after performing the authentication. If I clear my browser's cache, the error disappears and the application works normally.
I already saw other answers in StackOverflow and other sites, but none of them solved my problem. What could be happening?
Here is my User.php file:
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'cpf', 'name', 'lastname', 'email', 'password', 'auth', 'authy_id', 'api_token', 'block', 'blocked_at', 'session'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My code that does authentication is here:
public function auth($session, $gtag){
$user = User::where('session', $session)->first();
if(isset($user) && !empty($user)){
Auth::login($user);
//$time = decrypt($user->session);
$user->session = NULL;
$user->save();
setcookie('_ga', $gtag, (time() + 605800), '/', 'bmydomain.com');
setcookie('_gat_gtag_UA_115432851_1', '1', (time() + 605800), '/', 'mydomain.com');
return redirect($this->redirectTo);
}
else{
return redirect($this->redirectNotAuth);
}
}
On Kernel.php file use:
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
instead of
'auth' => \App\Http\Middleware\Authenticate::class,