Laravel seeder : Call to undefined method Illuminate\Notifications\Notification::getConnectionName() - php

I have a many to many relationship between two models:
User
namespace App\Models;
class User extends Model
{
use HasApiTokens, Notifiable,hasFactory;
/**
* The attributes that are mass assignable.
*
* #var array
*/
];
}
Notification
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Notification extends Model
{
/**
* #var array
*/
protected $guarded = ['id'];
use HasFactory;
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
I created a factory for each model and a Seeder which calls the two factories in order to create users and attach notifications to each one of them.
NotificationUserSeeder:
<?php
namespace Database\Seeders;
use App\Models\Notification;
use App\Models\User;
use Illuminate\Database\Seeder;
class MockNotificationUser extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
}
}
I am getting this error when running db:seed:
Call to undefined method Illuminate\Notifications\Notification::getConnectionName()

Since you have named model name as Notification .And while importing in seeder class ,it look like you have imported
use Illuminate\Notifications\Notification;
instead of
use App\Models\Notification;
Updated
The issue is with User model due to conflict in model name and Illuminate Notification facade's. Notification facade not used in User model so better to remove notification import. Suppose if you are using Notification illuminate then you can use as alias any one of the imports

Related

Laravel Model Can not Find Factory

I create model to another path
namespace Core\Entity;
use Core\Base\BaseEntity;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class News extends BaseEntity
{
use HasFactory;
And This is My seeder
use Core\Entity\News;
class NewsSeeder extends Seeder
{
public function run()
{
News::factory(500)->create();
}
And This is my factory
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\Core\Entity\News>
*/
class NewsFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
];
}
}
Problem Is it Can not Find path of Factory , gives me like this ERROR
Class "Database\Factories\Core\Entity\NewsFactory" not found
How I can solve this problem?
Update your namespace in Factory class:
namespace Database\Factories;
to
namespace Database\Factories\Core\Entity;
And run composer dump-autoload

Laravel 8 belongsTo relationship not returning data on User model

I'm building a Laravel 8 API and want to automatically join user_settings onto a user whenever the User model is queried.
My thinking is that I can achieve this with the belongsTo relationship since user_settings "belongs" to a user.
However, when I attach this to my UserSetting model and query a user I'm not seeing any user settings attached to my User despite having data in the user_settings table.
Where am I going wrong?
Model: User
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class UserSetting extends Model
{
use HasFactory, SoftDeletes;
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'user_settings';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'user_id',
'theme',
'refreshButtonPlacement',
'animationSpeed',
'fetchTimeout'
];
/**
* Get the user that owns the comment.
*/
public function user()
{
return $this->belongsTo(UserSetting::class);
}
}
Model: User
<?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 Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password'
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'last_login_at' => 'datetime'
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
I also tried using a One To One relationship and defined a settings method on my User model but in Tinker when I ran User::findOrFail(1)->settings; I had nothing either.
Relationship setup:
class User extends Model
{
//some custom stuff
/**
* Get the phone associated with the user.
*/
public function user_setting()
{
return $this->hasOne(UserSetting::class);
}
}
class UserSetting extends Model
{
//some custom things
/**
* Get the user that owns the comment.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
Afterwards you can use eager laoding by default, in your case you will have to add $with = ['user_setting'] to your User class.
You could also use the ->with() method, for that you will have to use either:
User::with('user_setting')->find(Auth::id());
//or
Auth::user()->with('organisation')->first()
Laravel doesn't load the relationship values in every call because of the obvious overhead. So you will either define the relationship to be loaded by default or you will have to work with the ->with() method for eager loading the relationship.
Add this method to your User model
And you can access the user settings through a dynamic attribute $user-> user_setting
on each User model instance
For more informations
https://laravel.com/docs/8.x/eloquent-relationships#one-to-one
public function user_setting(){
return $this->hasOne(UserSetting::class);
}

Laravel, Call to undefined function Database\Seeders\factory()

I get the title error when I run command:
php artisan db:seed
My screenshot:
I have no idea where this problem comes from. I was searching for code examples and solution but I haven't found anything :(
ArticlesTableSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
// use Laracasts\TestDummy\Factory as TestDummy;
class ArticlesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\Models\Article::class, 30)->create();
}
}
ArticleFactory.php
<?php
namespace Database\Factories;
use App\Models\Model;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class ModelFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = App\Models\Article::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'title' => $faker->text(50),
'body' => $faker->text(200)
];
}
}
DatabaseSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(ArticlesTableSeeder::class);
}
}
Thank you in advance for your help!
In laravel 8 the default route namespace was removed.
Try to change:
ArticlesTableSeeder.php:
factory(App\Models\Article::class, 30)->create();
to:
\App\Models\Article::factory()->count(30)->create();
ArticleFactory.php:
protected $model = App\Models\Article::class;
to:
protected $model = \App\Models\Article::class;
and you will probably have to change:
'title' => $faker->text(50),
'body' => $faker->text(200)
to:
'title' => $this->faker->text(50),
'body' => $this->faker->text(200)
All suggestions that were mentioned here are correct.
Sometimes running composer require laravel/legacy-factories might fix your problem if you're using Laravel 8.
Also, in case you get an error that says Class 'Database\Factories\ArticleFactory' not found
then make sure you have class ArticleFactory extends Factory and not ModalFactory.
And make sure you're using HasFactory in the Article Model like here.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
}
For more info: Laravel 8 Modal Factories
Try to change
factory(App\Models\Article::class, 30)->create();
to
App\Models\Article::factory()->count(30)->create();
ArticlesTableSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Article;
use Illuminate\Database\Seeder;
class ArticlesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Article::factory()->times(30)->create();
}
}
ArticleFactory.php
<?php
namespace Database\Factories;
use App\Models\Article;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class ArticleFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Article::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'title' => $this->faker->text(50),
'body' => $this->faker->text(200)
];
}
}
If you are using version 8 of laravel, look at the upgrade guide.
"Laravel's model factories feature has been totally rewritten to support classes and is not compatible with Laravel 7.x style factories. However, to ease the upgrade process, a new laravel/legacy-factories package has been created to continue using your existing factories with Laravel 8.x. You may install this package via Composer:
composer require laravel/legacy-factories"
https://laravel.com/docs/8.x/upgrade#seeder-factory-namespaces
change
‍factory(App\Models\Article::class, 30)->create(); ‍
to
\App\Models\Article::factory(30)->create();
I'm facing the same issue when I realized my model was not using the HasFactory trait.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'categories';
}
So make sure this trait is being used by your model.
If you are using version 8 of laravel you can directory use:
use App\Models\Article;
Article::factory()->count(30)->create();
composer require laravel/legacy-factories
php artisan db:seed

Laravel 5 SQLSTATE[42S02]: Base table or view not found

I'm studing about Repository Design Pattern in Laravel and I'm using https://github.com/andersao/l5-repository to do it.
I think i install success in my project . But when i run code with repository i have some problem
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'test.nhanviens' doesn't exist (SQL: select * from nhanviens)
Table in my database is Nhanvien not Nhanviens
Here in my code
NhanvienRepository.php
<?php
namespace App\Repositories;
use Prettus\Repository\Contracts\RepositoryInterface;
/**
* Interface NhanvienRepository
* #package namespace App\Repositories;
*/
interface NhanvienRepository extends RepositoryInterface
{
//
}
NhanvienRepositoryEloquent.php
<?php
namespace App\Repositories;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Repositories\NhanvienRepository;
use App\Entities\Nhanvien;
use App\Validators\NhanvienValidator;
/**
* Class NhanvienRepositoryEloquent
* #package namespace App\Repositories;
*/
class NhanvienRepositoryEloquent extends BaseRepository implements NhanvienRepository
{
/**
* Specify Model class name
*
* #return string
*/
public function model()
{
return Nhanvien::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
DataController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\nhanvien;
use App\Repositories\NhanvienRepository;
class DataController extends Controller
{
protected $repository;
public function __construct(NhanvienRepository $repository){
$this->repository = $repository;
}
public function DanhSach(){
var_dump($this->repository->all());
}
}
from App\Nhanvien.php Add this variable to the class:
protected $table = 'nhanvien';
Explanation: The "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the nhanvien model stores records in the nhanviens table.
As stated in the official Eloquent documentation you need to specifically set the table name in your Model definition. That is, in your App\Nhanvien.php file set the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Nhanvien extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'Nhanvien';
}
or use
protected $table = 'nhanvien';
instead if your table name is full lowercase.
Check your migration file, maybe you are using Schema::table, like this:
Schema::table('table_name', function ($table) {
// ... });
If you want to create a new table you must use Schema::create:
Schema::create('table_name', function ($table) {
// ... });
See the Laravel migration documentation for more information.
If you are using Schema::create then please provide the contents of your migration file.
In my case, I've got rid of similar error by executing the command
php artisan config:cache

Laravel 5 setup model event to "clear up" pivot tables on model delete

I am using Laravel 5 to build a user based application. Some models have a manyToMany relationship in my app and therefore I am using pivot tables.
When I delete a user from the system, I use this simple function:
/**
* Delete user.
*
* #param $id
* #return mixed
*/
public function deleteUser($id)
{
return $this->user->whereId($id)->delete();
}
However, when the user is deleted, the rows in the pivot tables (for example role_user) do not get deleted.
I have read on the laravel site that I can use model events to "clear up" my pivot tables, but i'm really unsure how I would implement that.
Can anyone point me in the right direction?
Edit
Below is my current model setup:
namespace App\Models\User;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use App\Scopes\MultiTenantTrait;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword, MultiTenantTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['cust_id', 'first_name', 'last_name', 'email', 'status', 'activation_code'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* Boot the model.
*
*/
public static function boot()
{
parent::boot();
static::deleting(function($user)
{
$user->roles()->delete();
$user->supervisors()->delete();
$user->types()->delete();
$user->rates()->delete();
$user->miscs()->delete();
});
}
...
You can add a boot method to your models, like the following:
public static function boot() {
parent::boot();
// This is a deleting event on the model
static::deleting(function($model) {
$model->... //Here your model is still available
// You could add something like this
DB::table('role_user')->where('user_id', $model->id)->delete();
})
}
But you can also extend the delete method in your models:
public function delete() {
DB::table('role_user')->where('user_id', $this->id)->delete();
parent::delete();
}

Categories