You can use toArray() method: https://laravel.com/docs/9.x/collections#method-toarray also you can write it like this:
$role = Role::firstWhere('id',$role_id)->toArray();
or
$role = Role::find($role_id)->toArray();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi!
After User is authorized, i want to switch to a given role Find this code for User model:
<?php
namespace App\Models;
use \DateTimeInterface;
use App\Support\HasAdvancedFilter;
use Carbon\Carbon;
use Hash;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasAdvancedFilter;
use SoftDeletes;
use Notifiable;
use HasFactory;
public $table = 'users';
protected $hidden = [
'remember_token',
'password',
];
protected $dates = [
'email_verified_at',
'created_at',
'updated_at',
'deleted_at',
];
protected $orderable = [
'id',
'name',
'email',
'email_verified_at',
'country.name',
'golfclub.name',
];
protected $filterable = [
'id',
'name',
'email',
'email_verified_at',
'roles.title',
'country.name',
'golfclub.name',
];
protected $fillable = [
'name',
'email',
'email_verified_at',
'password',
'remember_token',
'country_id',
'golfclub_id',
'created_at',
'updated_at',
'deleted_at',
];
public function syncRoles(array $roles)
{
$this->roles()->sync($this->getStoredRoleIds($roles));
}
protected function getStoredRoleIds($roles)
{
$ids = [];
foreach ($roles as $role) {
$ids[] = $this->getRoleId($role);
}
return $ids;
}
private function getRoleId($role)
{
if (is_string($role)) {
return app(Role::class)->findByName($role)->id;
}
return $role->id;
}
public function getIsAdminAttribute()
{
return $this->roles()->where('title', 'Admin')->exists();
}
public function getEmailVerifiedAtAttribute($value)
{
return $value ? Carbon::createFromFormat('Y-m-d H:i:s', $value)->format(config('project.datetime_format')) : null;
}
public function setEmailVerifiedAtAttribute($value)
{
$this->attributes['email_verified_at'] = $value ? Carbon::createFromFormat(config('project.datetime_format'), $value)->format('Y-m-d H:i:s') : null;
}
public function setPasswordAttribute($input)
{
if ($input) {
$this->attributes['password'] = Hash::needsRehash($input) ? Hash::make($input) : $input;
}
}
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function country()
{
return $this->belongsTo(Country::class);
}
public function golfclub()
{
return $this->belongsTo(Golfclub::class);
}
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
}
This is used in my logincontroller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Auth;
use App\Models\Role;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo;
public function redirectTo()
{
$role_id = 9; // dashboard
$role = Role::where('id',$role_id)->first();
$user=Auth()->user();
$user->syncRoles($role);
switch ($role_id) {
case "4":
$url = '/admin/dashboard';
return $url;
break;
case "9":
$url = '/admin/player';
return $url;
break;
case "5":
$url = '/admin/user';
return $url;
break;
}
return '/admin/dashboard';
}
/**
* Create a new controller instance.
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* The user has logged out of the application.
*
* @return mixed
*/
protected function loggedOut(Request $request)
{
if ($request->wantsJson()) {
return response(null, Response::HTTP_NO_CONTENT);
}
}
}
Gives me error:
Argument 1 passed to App\Models\User::syncRoles() must be of the type array, object given, called in /home/vagrant/code/app/Http/Controllers/Auth/LoginController.php on line 40
So $role = Role::where('id',$role_id)->first(); return a object
Can i convert this object to array ?
You can use toArray() method: https://laravel.com/docs/9.x/collections#method-toarray also you can write it like this:
$role = Role::firstWhere('id',$role_id)->toArray();
or
$role = Role::find($role_id)->toArray();
Please or to participate in this conversation.