How can increase Laravel Sanctum token length - laravel

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;

Related

How to show in Auth::user() custom fields of User model?

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!

How to resolve mass assignment error in laravel?

I am new to the laravel, i am implementing user registration api while registering the user it's throwing an error like mass_assignment
Add [first_name] to fillable property to allow mass assignment on [App\\Entities\\User].
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $table ='user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name','last_name','phone_number','email'
];
protected $guarded =[];
/**
* 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',
];
}
UserController.php
public function userRegister(userRequest $request){
$data = $this->repository->create($request->all());
return $user = new UserTransformer($data);
}
}
please help why this error is happening ..?
The main problem is laravel5.8 the model paths are different so use following facade
use App\modelname
instead of use App\Entities\User,let me know if this resolves your problem :-)

Cannot sava data in database in notification file in Laravel

I'm using Laravel Notification and i want to save data in my database table if i write my insert query then i'm getting following error otherwise Notification are running :
TypeError: Return value of App\User::getLogNameToUse() must be of the
type string, null
This is the query
public function toMail($notifiable)
{
$users = User::find($notifiable->id);
$users->verification_link=$link;
$users->save();
...
...
}
Model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Notifications\ResetPasswordNotification;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Activitylog\Traits\LogsActivity;
class User extends Authenticatable
{
use Notifiable, LogsActivity;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'role_id', 'password',
];
/**
* 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',
];
public function role()
{
return $this->belongsTo(Models\Role::class);
}
}
Seems like the error is with the logName and without looking at more code and data it is difficult to pinpoint exactly what is wrong.
Following could work
/**
* Get the log name to use for the model.
*
* #param string $eventName
* #return string
*/
public function getLogNameToUse(string $eventName = ''): string
{
return Str::kebab(Str::plural(class_basename($this)));
}
This is just overriding the piece of code causing issue. Give it a try.

I get BadMethodCallException Call to undefined method App\Models\User::identifiableAttribute()

I get this error after clicking 'New Post' button the frontend of the app:
Posts view
Line from my log file:
[2020-09-27 14:41:03] local.ERROR: Call to undefined method App\Models\User::identifiableAttribute() {"exception":"[object] (BadMethodCallException(code: 0): Call to undefined method App\Models\User::identifiableAttribute() at C:\xampp\htdocs\backpack-demo\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php:50)
I am using Laravel 7 + Backpack CRDU generator
Posts Controller:
<?php
namespace App\Http\Controllers;
use App\Events\NewPost;
use App\Http\Requests\PostStoreRequest;
use App\Jobs\SyncMedia;
use App\Mail\ReviewPost;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class PostController extends Controller
{
/**
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index(Request $request)
{
$posts = Post::all();
return view('post.index', compact('posts'));
}
/**
* #param \App\Http\Requests\PostStoreRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(PostStoreRequest $request)
{
$post = Post::create($request->validated());
Mail::to($post->author->email)->send(new ReviewPost($post));
SyncMedia::dispatch($post);
event(new NewPost($post));
$request->session()->flash('post.title', $post->title);
return redirect()->route('post.index');
}
}
Posts Model:
class Post extends Model
{
use CrudTrait;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'title',
'content',
'published_at',
'author_id',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'id' => 'integer',
'author_id' => 'integer',
];
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'published_at',
];
public static function create(array $validated)
{
}
public function author()
{
return $this->belongsTo(User::class);
}
}
User model:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* 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',
];
}
your have forgotten to use 'CrudTrait' in your User Model:
use Backpack\CRUD\app\Models\Traits\CrudTrait;
class User extends Authenticatable
{
use Notifiable,CrudTrait
.......
}

Laravel Relationship with grabbing data

I'm not really sure how to title this one, but I have been trying to follow the docs on Laravel about relationships and I'm not sure how to make this one in the model. I have a users model:
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'first_name', 'last_name', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token', 'is_admin'
];
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'created_at',
'updated_at',
'email_verified_at'
];
public function companies()
{
return $this->hasManyThrough('App\Company', 'App\CompanyUser');
}
}
Then I have a companies model which is like the following:
<?php
namespace App;
use App\Traits\UserRelationsTrait;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
use UserRelationsTrait;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'created_at',
'updated_at'
];
public function users()
{
return $this->hasManyThrough('App\User', 'App\CompanyUser');
}
}
Next I have the intermediate table CompanyUsers
<?php
namespace App;
use App\Traits\UserRelationsTrait;
use Illuminate\Database\Eloquent\Model;
class CompanyUser extends Model
{
use UserRelationsTrait;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'company_id', 'role_id', 'user_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
];
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'created_at',
'updated_at'
];
}
In my models I am able to do a user has many companies through the CompanyUser model but how do I make a relationship of a user has one role in a company through the CompanyUser table? So when I want the role the user has with the company I can use the model relation. This is the part of the relations I dont understand. Do I have to use the morphTo methods or am I able to specify a certain company?
You are trying to retrieve data from the pivot table
-- Btw, you don't need to create the model CompanyUser, you just need the table.
Take a look at Retrieving Intermediate Table Columns in the docs
$companies = $user->companies;
foreach( $companies as $company) {
echo $role_id = $company->pivot->role_id;
}

Resources