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

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.

Related

Laravel Eloquent one --> many relationship assigning parent

User model has many friends primary key id
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function friends()
{
return $this->hasMany(Friend::class);
}
}
Friend model; belongs to user. Foreign key user_id.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Friend extends Model
{
protected $guarded = ['id'];
//Make sure birthday is always in right format
public function setBirthdayAttribute($value)
{
//Put in mysql format
$this->attributes['birthday'] = date("Y-m-d",strtotime($value));
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Error when updating user with following controller code:
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Friend $friend
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Friend $friend)
{
$friend->fill($request->all());
//Assign user to logged in user...does NOT work; things it is a column
$friend->user = \Auth::user();
$friend->save();
return redirect(action('FriendsController#index'));
}
Error message when saving:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user' in 'field list' (SQL: update `friends` set `last_name` = Muench!!, `updated_at` = 2018-09-28 13:26:01, `user` = {"id":1,"name":"Chris","email":"me#chrismuench.com","email_verified_at":null,"created_at":"2018-09-27 19:52:03","updated_at":"2018-09-27 19:52:03","braintree_id":null,"paypal_email":null,"card_brand":null,"card_last_four":null,"trial_ends_at":null} where `id` = 8)
Is there a reason I cannot assign user with a user object? I know I could set the user_id column but this would be nice if I could pass around objects.
If you want to assign object and not property in your controller you need to add the following mutator
public function setUserAttribute($user)
{
$this->attributes['user_id'] = $user->id;
}
to your Friend object.
However it could be quite risky, because relationship name is also user, so it's better to use other name (for example friend_user and then method name setFriendUserAttribute) or to use Eloquent associate method instead:
$friend->user()->associate(\Auth::user());

Laravel seed issue, laravel is looking for plural table name

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

Laravel: renaming database table breaks functionality

I'm still quite new to Laravel, Eloquent and Artisan.
What I'm trying to do is pretty easy: I want to create a new Eloquent model AboutUs, along with a migration file to create the table about_us.
I run the following command:
PHP artisan make:model AboutUs -m
This generates the model and migration file, however, the migration file is named '2017_07_18_211959_create_about_uses_table.php', automatically adding the unnecessary 'es' to 'us', and creating a table 'aboutuses' instead of 'about_us'.
If I manually change the migration file like so:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAboutUsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('about_us', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->boolean('active');
$table->string('title')->nullable();
$table->text('text')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('about_us');
}
}
The model like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AboutUs extends Model
{
protected $fillable = ['id', 'active', 'title', 'text'];
public static function getAboutUs()
{
return AboutUs::find(1);
}
public function postAboutUs($session, $active, $title, $text)
{
$aboutUs = $session->get('about_us');
array_push($aboutUs, ['active' => $active, 'title' => $title, 'text' => $text,]);
$session->put('about_us', $aboutUs);
}
}
Then run the migration:
PHP artisan migrate
The database table 'about_us' is created correctly, but when I insert a row in the table and attempt to use getAboutUs, it crashes, the laravel.log stating that:
local.ERROR: exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'ID226233_db.aboutuses' doesn't exist' in C:\PHP Projects\xxx\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOConnection.php:77
I can see that there are still references to "aboutuses" in the autoload_classmap and autoload_static files. Changing this manually doesn't fix the issue, nor does running:
composer dump autoload
Next, I tried to simply not rename the table, but run the migration to create the initial "aboutuses" table. This fixed the functionality, as the model now works correctly. However, if I now add a new migration with:
Schema::rename('aboutuses', 'about_us');
This renames the table in the DB, but not in the autoload files or wherever else, resulting in broken functionality.
Surely there must be an easier way to either:
create a model with migration file with a FIXED name, instead of it
automatically changing the name by adding an unnecessary suffix.
rename a model and change the necessary files to prevent the model
from breaking.
Could anyone point me in the right direction before I lose my mind over this? :)
You can specify a custom table name in your Eloquent model class. Here is the example from the docs:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'my_flights';
}
Source: https://laravel.com/docs/5.4/eloquent#eloquent-model-conventions
Hope that helps.

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

Get incorrect table when tried to insert

I have a bizarre problem with my insert. So my migration is :
class CreatePhotoCategoryTable extends Migration {
public function up()
{
Schema::create('photo_category',function($table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('photo_category');
}
}
My Model :
class PhotoCategory extends Eloquent {
protected $fillable = array('name');
public static $rules = array(
'name' => 'required',
);
}
And my controller:
class PhotoCategory extends BaseController{
public function getAddPage(){
return View::make('admin.photo_category.addPhotoCategory');
}
public function postCreate(){
$validator = Validator::make(Input::all(), \PhotoCategory::$rules);
if($validator->passes()){
$oPhotoCategory = new \PhotoCategory();
$oPhotoCategory->name = Input::get('name');
$oPhotoCategory->save();
$iLastId = $oPhotoCategory->id;
return Redirect::to('/administration/category_photo/edit/'.$iLastId)
->with('message_succes','Succes');
}
return Redirect::to('/administration/category_photo/add')
->with('message_error','Error')
->withErrors($validator)
->withInput();
}
Evident my table in database is called photo_category but when I tried to save into this table I get en sql error :
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'photo_categories' doesn't exist. So why my save() method get table photo_categories instead of photo_category. Please help me.
The naming convention for database tables in Laravel is plural. So Laravel assumes from your model name PhotoCategory that your table is called photo_categories. You have two options:
Change the name of your table to photo_categories
Specify the table name in your model by adding:
protected $table = 'photo_category';
Make sure you name your controllers with different names from your models, as this might bring you some issues since both are classes and both have the same name.
And also your Model class represents your database table so you need to specify your table name as
protected $table = 'photo_category';

Resources