db:seed can't find factory() method - php

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.

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;
}

Class 'app\Models\Phone' not found in Laravel 8

I am trying ORM one to one relationship. I dont know why it cant recognize model class phone.
code as follows.
Phone.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, 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 Phone(){
return $this->hasOne('app\Models\Phone');
}
}
Phone.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
use HasFactory;
protected $table = "phones";
public function User(){
return $this->belongsTo('app\Models\User');
}
}
UserController.php
<?php
namespace App\Http\Controllers;
use App\Models\Phone;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function insert(){
$user = new User();
$user->name = 'BBB';
$user->email = 'bbb#mail.com';
$user->password = 'bbb#mail.com';
$user->save();
$phone = new Phone();
$phone->number = "445566";
$user->Phone()->save($phone);
return "RECORDS ADDED";
}
public function show($id){
$phone = User::find($id)->phone;
return $phone;
}
}
web.php
<?php
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('insert',[\App\Http\Controllers\UserController::class,'insert'])->name('user.insert');
Route::get('show/{id}',[\App\Http\Controllers\UserController::class,'show'])->name('user.show');
You need to fix this
public function User(){
return $this->belongsTo('App\Models\User');
}
here fix namespace app to App like that you need to fix all
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, 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 Phone(){
return $this->hasOne('App\Models\Phone');
//Better to use ::class notation for greater benefits with IDE
//return $this->hasOne(Phone::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
use HasFactory;
protected $table = "phones";
public function User(){
return $this->belongsTo('App\Models\User');
//Better to use ::class notation for greater benefits with IDE
//return $this->hasOne(User::class);
}
}
Folder/directory is app but the namespace is App
So need to change app\Models\Phone and app\Models\User to App\Models\Phone and App\Models\User
Better yet, use ::class notation for greater benefits with IDE - like easy navigation - not possible with string literals.
So instead of string literal App\Models\Phone import use App\Models\Phone statement and the Phone::class
Similarly for User import use App\Models\User and then use User::class

Laravel policy return unauthorized

I am trying to implement policies in my project. All tries have proven unsuccessful despite following documentation to the letter. And also read numerous posts on SO about it and other media. I did as described in docs, but nonetheless it doesn't work. What gives?
In AuthServiceProvider:
<?php
namespace App\Providers;
use App\User;
use App\Job;
use App\Policies\JobPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
'App\Job' => 'App\Policies\JobPolicy',
//Job::class => JobPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
In policy:
<?php
namespace App\Policies;
use App\Job;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class JobPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any jobs.
*
* #param \App\User $user
* #return mixed
*/
public function viewAny(User $user,Job $job)
{
//return (($user->isAdmin() || $user->isModerator() || $user->isUser()) && $user->status==1);
//return ($user->isMod());
return true;
}
In controller:
public function index()
{
$this->authorize('viewAny', User::class, Job::class);
return view("jobs.index");
}
My User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Role;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',"role_id"
];
/**
* 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("App\Role", "role_id");
}
public function isMod()
{
$user = User::find(auth()->user()->id);
$role = $user->role()->first()->name;
if($role==="job board moderator"){
return true;
}
else{
return false;
}
}
}
And Job model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Job extends Model
{
protected $fillable = [
"title", "description", "email"
];
public function user(){
return $this->belongsTo("App\User","user_id");
}
}
In policy:
public function viewAny(User $user)
{
return true;
}
In controller:
public function index()
{
$this->authorize('viewAny', Job::class);
return view("jobs.index");
}
The way to call a model policy method changes depending on the number of parameters it has.
No object
/* In policy*/
public function viewAny(User $user)
/* In controller */
$this->authorize('viewAny', Job::class)`
1 object
/* In policy*/
public function view(User $user, Job $job)
/* In controller */
$this->authorize('view', $job)
More than 1 object
/* In policy*/
public function view(User $user, Job $job, AnotherModel $model)
/* In controller */
$this->authorize('view', [$job, $model])
Source: https://laravel.com/docs/5.8/authorization#creating-policies

Laravel class not being found in a model

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

Database Seeding laravel create 50 users and attach a relationship to each user

I have use
factory(App\User::class, 50)->create()->each(function ($user) {
$user->posts()->save(factory(App\Post::class)->make());
});
inside run function in DatabaseSeeder
when I execute php artisan db:seed
the output is below
Seeding: UsersTableSeeder
BadMethodCallException : Call to undefined method App\User::posts()
at /home/ahmed/myDesgin/laravelApplication/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
46| * #throws \BadMethodCallException
47| */
48| protected static function throwBadMethodCallException($method)
49| {
> 50| throw new BadMethodCallException(sprintf(
51| 'Call to undefined method %s::%s()', static::class, $method
52| ));
53| }
54| }
Exception trace:
1 Illuminate\Database\Eloquent\Model::throwBadMethodCallException("posts")
/home/ahmed/myDesgin/laravelApplication/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:36
2 Illuminate\Database\Eloquent\Model::forwardCallTo(Object(Illuminate\Database\Eloquent\Builder), "posts", [])
/home/ahmed/myDesgin/laravelApplication/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1618
Please use the argument -v to see more details.
what is the cause of this problem and how to solve it
I'm not sure will it help you or not. But you can try to create users and their dummy post with relationship like that:
factory(User::class, 10)->create()->each(function ($user) {
$user->posts()->saveMany(factory(Posts::class, 5)->make());
});
this is my user model
<?php
namespace App;
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',
];
}
and below database seeds DatabaseSeeder.php
<?php
use App\User;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
/* $this->call([
UsersTableSeeder::class,
]); */
factory(User::class, 10)->create()->each(function ($user) {
$user->posts()->saveMany(factory(Posts::class, 5)->make());
});
}
}

Categories