Laravel seed issue, laravel is looking for plural table name - laravel

i've just started learning Laravel and I have problem generating seed for my test table.
Console error says:
"Base table or view not found: 1146 Table 'laravel.testms' doesn't exists..."
My table is called "testm" - I have no idea why it looks for testms
TestmFactory.php
use Faker\Generator as Faker;
$factory->define(App\Testm::class, function (Faker $faker) {
return [
'test' => $faker->paragraph
];
});
TestmTableSeeder.php
use Illuminate\Database\Seeder;
class TestmTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\Testm::class, 5)->create();
}
}
DatabaseSeeder.php
public function run()
{
$this->call(LinksTableSeeder::class);
$this->call(TestmTableSeeder::class);
}
app/Testm.php
class Testm extends Model
{
// Below line fixed my code :-)
protected $table = 'testm';
protected $fillable = [
'test'
];
}

From Laravels documentation:
By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified.
And in order to explicitly define the table name in the model, Testm.php in your case, you would want to add the following code to the class:
protected $table = 'testm';
Hope this helps!

Try adding this to your model
protected $table = 'testm';

Related

Morph field doesn't have a default value when seeding factory relationship

I have a Recipe and Review model:
class Recipe extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function reviews(): MorphToMany
{
return $this->morphToMany(Review::class, 'reviewable');
}
}
class Review extends Model
{
use HasFactory;
protected $guarded = ['id'];
}
Each has a factory:
class RecipeFactory extends Factory
{
protected $model = Recipe::class;
public function definition()
{
return [
'name' => $this->faker->sentence(5, true),
];
}
}
class ReviewFactory extends Factory
{
protected $model = Review::class;
public function definition()
{
return [
'review' => $this->faker->paragraphs(1, true),
];
}
}
When I try to seed new test records using this:
Recipe::factory()->hasAttached(
Review::factory()
->count(5)
);
I get the SQL error:
SQLSTATE[HY000]: General error: 1364 Field 'reviewable_type' doesn't have a default value
How do I get Laravel to fill in the correct morph reviewable_type and reviewable_id values when seeding the related records?
In my case, I have a program, and a form, the form can be attached to various tables.
When I created my seeder I would grab a program, create a form, and then got the error General error: 1364 Field 'formable_type' doesn't have a default value
I fixed this by updating my migration to use nullableMorphs.
$table->nullableMorphs('formable');
Hope that will help someone.

Laravel, how to call table name without hardcode by using same class model?

The table name is MySQL I have like this
energydata_1001
energydata_1002
energydata_1003
energydata_1004
energydata_1005
"energydata_prefix" is the id from another table
so the table name would be a lot in my database table depending on the user selection. the column table is the same.
this is my EnergyData model
namespace App;
use Illuminate\Database\Eloquent\Model;
class EnergyData extends Model
{
protected $table = 'energydata_';
}
this is my EnergyData Controller, how do I get table name like energydata_1001
namespace App\Http\Controllers;
use App\EnergyData;
use Illuminate\Http\Request;
class EnergyDataController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$gettableID = 1001;
return view('energydata.index',compact('energydata_1001'))
}
I suppose if you have to you can set a static variable on the model and use that to generate the table name:
class Something extends Model
{
protected $table = 'energydata_';
static $tableId = null;
public function getTable()
{
return $this->table . static::$tableId;
}
public static function tableId($tableId = null)
{
if (is_null($tableId)) {
return static::$tableId;
}
static::$tableId = $tableId;
}
}
Something::tableId('1001');
This is possible but may not be the best solution.
Eloquent models have a getTable function, so you can get the table for a model like this:
(new EnergyData())->getTable();
If you want to dynamically add prefix to the table name, you will need to use the Query Builder. Assign 'energydata_' to a variable and concatenate the prefix and call it using the query builder
public function index()
{
$gettableID = 1001;
$table_name = 'energydata_' . $gettableID;
$users = DB::table($table_name)->get();
}

lararvel uuid as primary key

I'm trying to set an uuid as primary key in a Laravel Model. I've done it setting a boot method in my model as stablished here so I don't have to manually create it everytime I want to create and save the model. I have a controller that just creates the model and saves it in database.
It is saved correctly in database but when controller returns the value of the id is always returned with 0. How can I make it to actually return the value that it is creating in database?
Model
class UserPersona extends Model
{
protected $guarded = [];
protected $casts = [
'id' => 'string'
];
/**
* Setup model event hooks
*/
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$uuid = Uuid::uuid4();
$model->id = $uuid->toString();
});
}
}
Controller
class UserPersonaController extends Controller
{
public function new(Request $request)
{
return UserPersona::create();
}
}
You need to change the keyType to string and incrementing to false. Since it's not incrementing.
public $incrementing = false;
protected $keyType = 'string';
Additionally I have an trait which I simply add to those models which have UUID keys. Which is pretty flexible. This comes originally from https://garrettstjohn.com/articles/using-uuid-laravel-eloquent-orm/ and I added some small adjustments to it for issues which I have discovered while using it intensively.
use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;
/**
* Class Uuid.
* Manages the usage of creating UUID values for primary keys. Drop into your models as
* per normal to use this functionality. Works right out of the box.
* Taken from: http://garrettstjohn.com/entry/using-uuids-laravel-eloquent-orm/
*/
trait UuidForKey
{
/**
* The "booting" method of the model.
*/
public static function bootUuidForKey()
{
static::retrieved(function (Model $model) {
$model->incrementing = false; // this is used after instance is loaded from DB
});
static::creating(function (Model $model) {
$model->incrementing = false; // this is used for new instances
if (empty($model->{$model->getKeyName()})) { // if it's not empty, then we want to use a specific id
$model->{$model->getKeyName()} = (string)Uuid::uuid4();
}
});
}
public function initializeUuidForKey()
{
$this->keyType = 'string';
}
}
Hope this helps.
Accepted answer not worked for me on Laravel 9, but this way worked perfect, you can try it:
1- Create new Trait Class in project path app/Traits/IdAsUuidTrait.php (if you not found Traits folder create it, this is full code of this Class:
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait IdAsUuidTrait
{
public function initializeIdAsUuidTrait(): void
{
$this->keyType = 'string';
$this->id = Str::orderedUuid()->toString();
}
}
2- In any model you want to make id as UUID just call trait like this:
use App\Traits\IdAsUuidTrait;
class YourModelName extends Model
{
use IdAsUuidTrait;
...
That is it, now try to create, select, update any row in database by this model...

Mapping of Eloquent models to tables?

We are able to create Eloquent models for tables. But how Laravel knows to which table to associate a model with? Do we have something similar to hbm.xml(mapping file we use for Hibernate) which says this model means this table.
The table name is a protected property:
class User extends Eloquent {
protected $table = 'my_users';
}
Laravel Docs
You can manually override the table name as the above answer states.
Its just a protected member of the Model.php class.
class User extends Eloquent {
protected $table = 'my_users';
}
Otherwise, a lowercase, plural format is automatically used, based on the classname of the Model. (class_basename($this))
As shown here... (Illuminate/Database/Eloquent/Model.php)
/**
* Get the table associated with the model.
*
* #return string
*/
public function getTable()
{
if (isset($this->table)) {
return $this->table;
}
return str_replace('\\', '', Str::snake(Str::plural(class_basename($this))));
}

How to fix the "Table 'database.teches' doesn't exist" error?

Not sure why migrate is looking for 'teches' rather than the real table name 'techs'??
File: TechsTableSeeder.php
class TechsTableSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Eloquent::unguard();
Tech::create(
[
'name'=>'technology',
'description'=>'...',
'year'=>'2014'
]);
}
}
Upon php artisan db:seed --class="TechsTableSeeder", I get the following error in Terminal:
[Illuminate\Database\QueryException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'database.teches' doesn't exist (SQL: insert into teches (name,
description, year, updated_at, created_at) values (technology,
..., 2014, 2013-12-30 03:23:39, 2013-12-30 03:23:39))
Model Tech.php does exist and was auto-generated through php artisan generate:model
Tech as follows:
class Tech extends Eloquent {
protected $guarded = array();
public static $rules = array();
}
It tries to put the table name in the plural.
Just add
protected $table = 'tech';
In your model class Tech
Antonio is right, by the way if it works with the model itself you could instead format your seeder in this way:
class TechsTableSeeder extends Seeder {
public function run()
{
$techs = [
];
DB::table('techs')->insert($techs);
}
}
I always prefer this method when I seed.

Resources