Undefined table: 7 ERROR: relation "expenses" does not exist - php

Since i am a spanish speaker, i wrote the controllers and models of income and expense in spanish; while all the rest were on english..
I renamed and changed manually Routes, Controllers, Migrations and even Models.
And when i run php artisan migrate:reset this is my error.
Undefined table: 7 ERROR: relation "expenses" does not exist (SQL: alter table "expenses" drop column "location_id")**
I use psgql and laravel 5.3
This is my code:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Expense extends Model
{
protected $fillable = ['id', 'description', 'quantity'];
public function locations()
{
return $this->hasMany('App\Location');
}
public function icons()
{
return $this->hasMany('App\Icon');
}
public function types()
{
return $this->hasMany('App\Type');
}
public function stores()
{
return $this->hasMany('App\Store');
}
}
Migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateExpensesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('expenses', function (Blueprint $table) {
$table->increments('id');
$table->float('quantity');
$table->string('description');
$table->integer('location_id')->unsigned();
$table->integer('icon_id')->unsigned();
$table->integer('type_id')->unsigned();
$table->integer('store_id')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('expenses');
}
}
Location Migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLocationsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('locations', function (Blueprint $table) {
$table->increments('id');
$table->string('address');
$table->float('lat');
$table->float('long');
$table->integer('store_id')->unsigned();
$table->timestamps();
$table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade');
});
Schema::table('expenses', function (Blueprint $table) {
$table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('expenses', function (Blueprint $table) {
$table->dropColumn('location_id');
});
Schema::dropIfExists('locations');
}
}
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Location extends Model
{
protected $fillable = ['id', 'address', 'lat', 'long'];
public function expenses()
{
return $this->belongsTo('App\Expense');
}
public function stores()
{
return $this->hasOne('App\Store');
}
}
Hope you can help me.

When it says
relation "expenses" does not exist
It usually happens when your expenses table must have been dropped before migration:reset rolled back CreateLocationsTable.
Check the order of execution of your migrations.
As you were trying to reset, to fix it now, open your database, drop all tables manually and execute migrate again.

Schema::table('expenses', function (Blueprint $table) {
$table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');
});
change this to
Schema::alter('expenses', function (Blueprint $table) {
$table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');
});

I had this error. I had to resolve it by adding the prefix of the database to my model. There is a way to change this in the database, and it is supposed to be changed. it's something, like $user, public. It's the schema profile. Mine is changed when I login, but for some reason the model is not binding to schema. So I had to specify it in the model. Instead of
protected $table = 'table_name';
I had to do
protected $table = 'schema_name.table_name';
Note: By schema_name or table_name, I'm not referring for you to put schema_ then the name. That is just so it's easier to read.
The model is located in the model folder under the App/Models folder depending on which version of Laravel you using and how your Models are organized. If your model name is not the same as the table name, then you will need to put the protected $table. But if the schema is not there, then you will need to add that.
I do have this set in my DB_DATABASE_SECOND= in .env file. But it somehow still doesn't pick up the prefix.
But yeah. Pretty much I couldn't find the answer anywhere, but I

Solution found in:
Laravel assumes the database table is the plural form of the model name
https://laravel.com/docs/8.x/eloquent#table-names
you need to declare the singularity name of your table.
add this line
protected $table = 'expense'
at the end of your model file
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Expense extends Model
{
protected $fillable = ['id', 'description', 'quantity'];
public function locations()
{
return $this->hasMany('App\Location');
}
public function icons()
{
return $this->hasMany('App\Icon');
}
public function types()
{
return $this->hasMany('App\Type');
}
public function stores()
{
return $this->hasMany('App\Store');
}
protected $table = 'expense';
}

Related

Eloquent relation query returning null value

I am trying to get some relational data. All the methods work well but only one method is not working. I am trying to call App\ModeltestMcqQuestion::find(id)->chapterwiseMcqs from tinker, but it is returning null. My database is well populated. I have tried with many id, but nothing is working.
My Models are:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class ChapterwiseMcq extends Model
{
use SoftDeletes;
protected $fillable = [
'topic_id',
'question_type',
'question',
'question_description',
'question_resource',
'a',
'b',
'c',
'd',
'answer',
'answer_description',
'answer_resource',
];
public function topic(){
return $this->belongsTo(Topic::class);
}
public function modeltestMcqAnswers(){
return $this->hasMany(ModeltestMcqAnswer::class);
}
public function modeltestMcqQuestions(){
return $this->hasMany(ModeltestMcqQuestion::class);
}
}
Another Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class ModeltestMcqQuestion extends Model
{
use SoftDeletes;
protected $fillable = [
'modeltest_question_set_id',
'chapterwise_mcq_id',
];
public function modeltestQuestionSet(){
return $this->belongsTo(ModeltestQuestionSet::class);
}
public function chapterwiseMcqs(){
return $this->belongsTo(ChapterwiseMcq::class);
}
}
Migrations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateChapterwiseMCQSTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('chapterwise_mcqs', function (Blueprint $table) {
$table->id();
$table->foreignId('topic_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->integer('question_type');
$table->string('question');
$table->text('question_description')->nullable();
$table->string('question_resource')->nullable();
$table->string('a');
$table->string('b');
$table->string('c');
$table->string('d');
$table->string('answer');
$table->text('answer_description')->nullable();
$table->string('answer_resource')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('chapterwise_m_c_q_s');
}
}
Another migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateModeltestMcqQuestionsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('modeltest_mcq_questions', function (Blueprint $table) {
$table->id();
$table->foreignId('modeltest_question_set_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('chapterwise_mcq_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('modeltest_mcq_questions');
}
}
All the relational queries work well except App\ModeltestMcqQuestion::find(id)->chapterwiseMcqs. Can anyone help me what is wrong with the code? Here, id represents id of the model.
I have found a solution. Defining the funtion name caused the problem, I think.
public function chapterwiseMcqs()
Thu function name should be chapterwiseMcq(), not chapterwiseMcqs(). Changing the name worked for me.

user_id is not taking the value provided

The migrations file look like below
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title')->unique();
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
but the posts table in the database is having 0 as value.
The database is populated through the web.php code below. I need the user_id to have values 1 and 2 in the database posts.
Route::get('/create',function (){
$post=Post::create(['title'=>'lara vel','body'=>'laravel is good for php','user_id'=>1]);
$post=Post::create(['title'=>'spri ng','body'=>' spring is good for java','user_id'=>2]);
});
It's very Simple
just Go to your Post model
when you use create method to insert data you must be use fillable propery in your model.
so if you not have an Post model so create post Model and paste this code inside your Post Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
protected $fillable = [
'user_id', 'title','body'
];
}

Problem with seeding data in pivot table in Laravel

I have a problem while attempting to seed my pivot table in database in Laravel. I get error
Base table or view not found: 1146 Table 'user_cuisines' doesn't exist
And my table name is actually user_cuisine, so it is like for some reason laravel doesn't show that table. I added in my relationships that user_cuisine is pivot table because of alphabet order. Any help is appreciated. Here is my code.
UserCuisineTableSeeder.php
<?php
use App\UserCuisine;
use App\UserProfile;
use Illuminate\Database\Seeder;
class UserCuisineTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$cuisines = UserCuisine::all();
UserProfile::all()->each(function ($userProfile) use ($cuisines) {
$userProfile->cuisines()->attach(
$cuisines->random(rand(1, 12))->pluck('id')->toArray()
);
});
}
}
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(WhitelabelTableSeeder::class);
$this->call(CitiesTableSeeder::class);
$this->call(UserTableSeeder::class);
$this->call(UserProfilePropertiesSeeder::class);
$this->call(UserProfileTableSeeder::class);
$this->call(FieldTableSeeder::class);
$this->call(FieldValueTableSeeder::class);
$this->call(CuisineTableSeeder::class);
$this->call(LiteratureTableSeeder::class);
$this->call(MusicTableSeeder::class);
$this->call(SportTableSeeder::class);
$this->call(TvTableSeeder::class);
$this->call(UserCuisineTableSeeder::class);
$this->call(UserInterestTableSeeder::class);
}
}
UserCuisine.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCuisine extends Model
{
protected $fillable = [
'name'
];
public function userProfiles()
{
return $this->belongsToMany(UserProfile::class, 'user_cuisine');
}
}
UserProfile.php
<?php
namespace App;
class UserProfile
{
public function user()
{
return $this->belongsTo(User::class);
}
public function cuisines()
{
return $this->belongsToMany(UserCuisine::class, 'user_cuisine');
}
}
user_cuisine_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserCuisineTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_cuisine', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('cuisine_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('user_cuisine');
}
}
cuisine_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCuisineTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('cuisine', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('cuisine');
}
}
Laravel expect the table name to be user_cuisines but you named it user_cuisine without the "s"
You can fix that by changing your migration or adding protected $table = 'user_cuisine'; to your model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCuisine extends Model
{
protected $table = 'user_cuisine';
}
As naming convention goes, I would recommend changing the table name 👍
Seems user_cuisines table does not exist, You have created cuisine not user_cuisines
Just put below code in UserCuisine model.
protected $table= 'user_cuisine';
I would recommend always use -m flag while creating a model to avoid these types of errors, for example.
php artisan make:model ModelName -m

Laravel relationship design

I'm working on team management project.
I have a problem with doing relationships.
I want to display users in boards, but also want to look good and easy to read. I already designed relationships but when I saw JSON output of relationships, it was completely messed.
Is there some way how to display relationship data this way?
{
"id": 1,
"name: "Test",
"members": [
{
... user model here
"name": "Peter",
"email": "peter#peter.com",
}
]
}
My migrations:
Boards migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBoardsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('boards', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('boards');
}
}
Membership migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMembershipsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('memberships', function (Blueprint $table) {
$table->increments('id');
$table->integer('board_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('memberships');
}
}
EDIT:
Models
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Board extends Model
{
protected $fillable = ['name'];
public function members() {
return $this->hasMany(Membership::class)->with('user');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Membership extends Model
{
protected $fillable = ['board_id', 'user_id'];
protected $hidden = ['created_at', 'updated_at'];
public function user() {
return $this->hasOne(User::class, 'id', 'user_id');
}
}
You can try to define the relationships in the models as a Many to Many one, i.e.:
class User
{
public function boards()
{
return $this->belongsToMany('App\Board', 'memberships', 'user_id', 'board_id');
}
}
class Board
{
public function members()
{
return $this->belongsToMany('App\User', 'memberships', 'board_id', 'user_id');
}
}
With that relations defined you don't really need a Membership Model if it has not additional fields, and you can write code like that:
User::find($id)->boards
Board::find($id)->members
Board::with('members')->find($id)
You could read also the documentation on Many to Many Relationships

Save inserts empty row Laravel 5.3

I'm trying to make Laravel ORM working and it keeps inserting empty records in database. The ID created_at and updated_at are correctly inserted but the values are not. Here are the files:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TesterTest extends Model
{
protected $fillable = ['name','value'];
public $name;
public $value;
}
The migration file:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTestTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('my_tests', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('value');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('my_tests');
} }
And this is how Im calling it:
$flight = new TesterTest;
$flight->name = "Tester1";
$flight->save();
There is a something Im missing but can't figure it out.
I would say that adding in public $name; and public $value; in your model is causing problems. Try removing those two lines.

Categories