Laravel class not being found in a model - php

I am trying to get my project to use authorization roles to restrict users to certain featuers and I am following along with a tutorial. When I make a call to a class in my user.php file I am getting an error that the class App\Role can't be found. I am not sure if it is a namespace issue but I can't get to the bottom of it. I believe it is the roles function that is giving me this issue.
<?php
namespace EliteWorker;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'address', 'phone', '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',
];
public function roles() {
return $this->belongsToMany('App\Role');
}
public function hasAnyRoles($roles){
return null !== $this->roles()->whereIn('name', $roles)->first();
}
public function hasAnyRole($role){
return null !== $this->roles()->where('name', $role)->first();
}
}

You changed the namespace to EliteWorker so if the Model class RoleĀ is generated with Artisan, it'll also have that namespace
public function roles()
{
return $this->belongsToMany('EliteWorker\Role');
}
Note that you can also get the model base name by calling the class static property
public function roles()
{
return $this->belongsToMany(Role::class);
}
No need to import it if it's in the same namespace
Also note that the artisan command app:name has been removed in Laravel 6 to encourage developers to use the generic App namespace

Related

Call to undefined method App\Models\User::createSetupIntent()

I am trying to implement subscriptions with stripe integration using cashier packages in my Laravel application. I am facing this error whenever I select a plan.
My PlanController.php file code is as followed
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Plan;
class PlanController extends Controller
{
/**
* Write code on Method
*
* #return response()
*/
public function index()
{
$plans = Plan::get();
return view("plans", compact("plans"));
}
/**
* Write code on Method
*
* #return response()
*/
public function show(Plan $plan, Request $request)
{
$intent = auth()->user()->createSetupIntent();
return view("subscription", compact("plan", "intent"));
}
/**
* Write code on Method
*
* #return response()
*/
public function subscription(Request $request)
{
$plan = Plan::find($request->plan);
$subscription = $request->user()->newSubscription($request->plan, $plan->stripe_plan)
->create($request->token);
return view("subscription_success");
}
}
After searching for solutions online I am still stuck at the same problem. Kindly help.
Some other models that might help you in finding solution are as followed:
Plan.php The model file for plans
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class plan extends Model
{
use HasFactory;
protected $fillable = [
'name',
'slug',
'stripe_plan',
'price',
'description',
];
/**
* Write code on Method
*
* #return response()
*/
public function getRouteKeyName()
{
return 'slug';
}
}
Model file for users 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\Sanctum\HasApiTokens;
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'role',
'plan',
'created_by',
'status',
];
/**
* 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',
];
}
Add the Billable trait from Laravel Cashier to your User model.
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use Billable, HasApiTokens, HasFactory, Notifiable;
}

db:seed can't find factory() method

I'm trying to seed two tables with the following code:
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Foundation\Auth\User;
use App\Models\Role;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
User::factory(10)->create();
$roles = [
'dps',
'tank',
'healer'
];
foreach ($roles as $role) {
Role::create([
'name' => $role,
]);
}
foreach(User::all() as $user) {
foreach (Role::all() as $role) {
$user->$roles()->attach($role->id);
}
}
}
}
using php artisan db:seed, but its returning Call to undefined method Illuminate\Foundation\Auth\User::factory().
Going through User model, I have the following:
<?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\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* 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',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
public function monstros() {
return $this->hasMany('App\Models\Monstro');
}
public function arsenais() {
return $this->hasMany('App\Models\Arsenal');
}
public function itens() {
return $this->hasMany('App\Models\Item');
}
public function roles() {
return $this->belongsToMany(Role::class);
}
}
Where we can clearly see it's calling for the Factory method with use HasFactory
What am I missing here?
Also tried to restart artisan, update the framework, dump-auto load, none of those helped.
You are calling the wrong class instead of calling the App\Models\User you are calling the Illuminate\Foundation\Auth\User. Which has the same name. You can take a look at the namespaces above.

How to show list of data based on the user in Laravel

I have two table (three actually, but in this context it's only related to these two tables), Pekerjaan and User. Both table are in eloquent. User hasMany pekerjaans, and Pekerjaan belongsTo User. In the User table it has status 'super' and 'ppk'. 'Super' is a super admin whereby it can view all data, and for 'ppk' it can only view certain data based on his/her USER_ID in Pekerjaan's table. Here is my code for User.php 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\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Model as Eloquent;
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'username',
'satker',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
public function pekerjaans(){
return $this->hasMany(Pekerjaan::class);
}
}
And here is the Pekerjaan.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Pekerjaan extends Eloquent
{
use HasFactory;
protected $guarded = [];
public function penyedia(){
return $this->belongsTo(Penyedia::class, 'penyedia_id');
}
public function user(){
return $this->belongsTo(User::class, 'user_id');
}
}
Here is what I've tried in AdminController:
public function tabelpekerjaan(User $user){
if(Auth::user()->status=='super'){
$pekerjaan = Pekerjaan::with('penyedia')->paginate();
return view('admin.datapekerjaan', compact('pekerjaan'));
}else{
$pekerjaan = $user->pekerjaans;
return view('admin.datapekerjaan', compact('pekerjaan'));
}
}
Here is my code in web.php:
Route::get('/datapekerjaan',[AdminController::class,'tabelpekerjaan'])->name('datapekerjaan');
For now it shows me blank table when I logged in as 'ppk', and what I need is it will shows list of pekerjaan based on the user id. How to achieve this? Here is my table pekerjaans in database:
public function tabelpekerjaan(){
if(Auth::user()->status=='super'){
$pekerjaan = Pekerjaan::with('penyedia')->paginate();
return view('admin.datapekerjaan', compact('pekerjaan'));
}else{
$pekerjaan = Auth::user()->pekerjaans;
return view('admin.datapekerjaan', compact('pekerjaan'));
}
}
Try the above code, i guess your route model binding is in correct.

Userpermission pivot-function is only accessible via the Auth class

I have a simple Userpermission System consisting of 3 tables: users, permissions and the pivot table permission_user.
This is the User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
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',
];
public function permissions()
{
return $this->belongsToMany('App\Permission');
}
}
and here is the Permission Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Permission extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'description', 'level', 'parentpermission',
];
public function users()
{
return $this->belongsToMany('App\User');
}
}
Now when I try to get all the permissions of the currently logged in user with this:
$user_permissions = Auth::user()->permissions()->get();
it works without problems.
But when I try to get another Users Permissions like this:
$user_permissions = User::where('id', '=', $userid)->permissions()->get();
I get the following error:
Method Illuminate\Database\Eloquent\Collection::permissions does not exist.
How do I proceed?
I think you're missing first() here, since you can't get relations of a query builder object. Try this :
$user_permissions = User::where('id', '=', $userid)->first()->permissions()->get();
This first() will actually return User object, and then you can load its relations.
simply you can just add first() method to get just one record and get it's permissions, try this:
$user_permissions = User::where('id', '=', $userid)->first()->permissions;
There's no need to use get() method, this will get all the user permissions directely
Do this -
$user_permissions = User::find($userid)->permissions()->get();

(E_ERROR) Too few arguments to function Symfony\Component\HttpKernel\Profiler\Profile::__construct(), 0 passed

I wanted to relate a profile model to the existing user model using the relationship belongs to and hasOne and I am getting that error.
here is my Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public function user(){
return $this->belongsTo(User::class);
}
}
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Symfony\Component\HttpKernel\Profiler\Profile;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'username', '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 profile()
{
return $this->hasOne(Profile::class);
}
}
In my terminals i can get the user through the profile but cannot get the profile using user. here is the error
$user->profile
TypeError: Too few arguments to function Symfony/Component/HttpKernel/Profiler/Profile::__construct(), 0 passed in /Users/macair13/freeCodeGram/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php on line 720 and exactly 1 expected.
To fix the issue, replace the use Symfony\Component\HttpKernel\Profiler\Profile; line on top of your User.php file with use App\Profile; instead.
This is happening as you've mistakenly included the wrong class on top of your User.php file. When Laravel is trying to load the relationship, it attempts to construct a Symfony\Component\HttpKernel\Profiler\Profile object instead of constructing your intended model.
Use like below in your user model
public function profile()
{
return $this->hasOne('App\Profile', 'foreign_key');
}
I am not sure why you have used Symfony\Component\HttpKernel\Profiler\Profile in your user model. When your relationship is building it is using that Profile and not your Profile Model. You have to use the Profile Model namespace while defining the relationship.

Categories