I have a comments table and user table with the relationship: user->hasMany('comments') and comment->belongsTo('user'). For some reason with which eludes me, I keep getting this
FatalErrorException in Comment.php line 22: Call to undefined function App\belongsTo()
My other models have no issue whatsoever with the HasMany relations, however, the comments model has a problem with every single thing i try (even if i use HasMany just to see if it will have a different error).
Here is the Comment model.
use Illuminate\Database\Eloquent\Model;
class Comment extends Model {
protected $table = 'comments';
protected $fillable = [
'anime_id',
'user_id',
'user_comment'
];
public function postedOnAnime($query)
{
$query->where('anime_id', '=', $this.id);
}
public function user()
{
return $this.belongsTo('App\User', 'user_id', 'id');
}
public function anime()
{
return $this.belongsTo('App\Anime');
}
}
Here is the Users table:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->integer('role');
$table->string('name')->unique();
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
Here is the Comments table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCommentsTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('comments', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('anime_id')->unsigned();
$table->text('user_comment');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('anime_id')
->references('id')
->on('animes')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('comments');
}
}
Finally, when I call $comment->user() it fails with the error. Does anyone know where this error comes from?
Thanks.
Well, this error occurred because I had '.' in place of '->'. I couldn't figure out why it was always throwing the exact same error regardless if I did $this.belongsTo('App\User'); or $this.hasMany('App\User'); or even $this.thecakeisalie('App\User'); until I sat staring at the text between my many models yet again. Then, lo and behold, its another dumb, tiny and really hard to locate mistake of mine(as it usually is).
return $this.belongsTo('App\User', 'user_id', 'id');
to
return $this->belongsTo('App\User');
I think this is a common mistake coming from other languages where . is used to access properties. In PHP, it should be ->.
$this.belongsTo('...')
should be rewritten as
$this->belongsTo('...')
Related
Now I have two Models: user.php and Trx.php. I have created a one to many relationships as below:
User Model:
public function transactions()
{
return $this->hasMany('App\Trx');
}
Trx Model:
public function user()
{
return $this->belongsTo('App\User');
}
And this is the controller method for process data from Trx.php model and sending data to the views:
public function purchasedPlan()
{
$page_title = 'Purchased Plan';
$transactions = Trx::where('type', 7)->orderBy('id', 'DESC')->paginate(config('constants.table.default'));
$empty_message = 'No data found.';
// dd($transactions);
return view('admin.reports.transactions', compact('page_title', 'transactions', 'empty_message'));
}
Now the problem is that when I try accessing the data from the model, that's the $transactions, everything is working well except when I try getting the user in the relationship established like this in the blade template:
transactions.blade.php
<td> {{ $trx->user->username }}</td>
With that, I get this error:
Error:
[2020-05-24 05:35:40] production.ERROR: Trying to get property 'id' of non-object (View: /home/icashers/public_html/acc/core/resources/views/admin/reports/transactions.blade.php) {"exception":"[object] (ErrorException(code: 0): Trying to get property 'id' of non-object (View: /home/icashers/public_html/acc/core/resources/views/admin/reports/transactions.blade.php)
What am I doing wrong please? Anyone who's seeing what I am not please help. Thank you in advance😂
Trx.php Migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTrxesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('trxes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->nullable();
$table->string('amount',50)->nullable();
$table->string('main_amo',50)->nullable();
$table->string('charge',50)->nullable();
$table->string('type',50)->nullable();
$table->string('title')->nullable();
$table->string('trx')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('trxes');
}
}
User.php Migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('firstname');
$table->string('lastname');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('mobile')->unique();
$table->decimal('balance', 11, 2)->default(0);
$table->string('password');
$table->string('image')->nullable();
$table->text('address')->nullable()->comment('contains full address');
$table->tinyInteger('status')->default(1)->comment('0: banned, 1: active');
$table->tinyInteger('ev')->default(0)->comment('0: email unverified, 1: email verified');
$table->tinyInteger('sv')->default(0)->comment('0: sms unverified, 1: sms verified');
$table->string('ver_code')->nullable()->comment('stores verification code');
$table->dateTime('ver_code_send_at')->nullable()->comment('verification send time');
$table->tinyInteger('ts')->default(0)->comment('0: 2fa off, 1: 2fa on');
$table->tinyInteger('tv')->default(1)->comment('0: 2fa unverified, 1: 2fa verified');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Your migration has an error.... no foreign key defined>
public function up()
{
Schema::create('trxes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->string('amount',50)->nullable();
$table->string('main_amo',50)->nullable();
$table->string('charge',50)->nullable();
$table->string('type',50)->nullable();
$table->string('title')->nullable();
$table->string('trx')->nullable();
$table->timestamps();
});
}
I just deployed on Heroku yesterday and connected to a Postgresql db and since then I have this fun error showing up on my screen (and terminal) on Heroku:
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "categories" does not exist LINE 1: select * from "categories" ^ (SQL: select * from "categories")
In my terminal, below this error, I have an Undefined table error stating that my categories table doesn't exist. This so frustrating because it does exist and it's right there! Can someone help with this? Has anyone had a similar Issue?
Tried:
Rollback tables: heroku run php artisan migrate:rollback
migrate fresh: heroku run php artisan migrate:fresh
migrate reset: heroku run php artisan migrate:reset
The migrations run up until the stories table where the relationship is located and then stop running. Right below stories is the categories table. I don't know how much this helps in fining a solution.
stories table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('story');
$table->date('published_on');
$table->integer('count_views')->default(0);
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger("category_id");
$table->foreign('category_id')->references('id')->on('categories')->ondDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('stories');
}
}
categories table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('category');
$table->string('title')->nullable();
$table->string('img')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
Story model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Reviews;
use App\User;
use App\Category;
use App\ReadingList;
class Story extends Model
{
protected $guarded = [];
public function readingList()
{
return $this->belongsTo(ReadingList::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function reviews() {
return $this->hasMany(Reviews::class);
}
public function user() {
return $this->belongsTo(User::class);
}
}
Category model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Story;
class Category extends Model
{
protected $guarded = [];
public function story()
{
return $this->hasMany(Story::class);
}
}
Been fixated on this for days, maybe you guys can see something I don't. Thank you so much in advance.
You should change date in migration file names
Example
2019_07_29_113341_create_categories_table
2019_07_30_113341_create_stories_table
the older date time would be the first to run,
you should migrate categories table then stories
Hope help you
That's because your categories table migration runs after stories table however stories table depends on categories because of the foreign keys. What you have to do is :
Rename the categories table migration and move it to top of the stories table migration
Drop all tables in the the DB
Run your migration again
you have to consider that first the Parent migration should be created and then the relationship should be established.
Create the "categories" migration first Then create the "stories" migration.
I hope it is useful..
You can create a single migration file in these scenarios.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('category');
$table->string('title')->nullable();
$table->string('img')->nullable();
$table->timestamps();
});
Schema::create('stories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('story');
$table->date('published_on');
$table->integer('count_views')->default(0);
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger("category_id");
$table->foreign('category_id')->references('id')->on('categories')->ondDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories');
Schema::dropIfExists('stories');
}
}
I'm new to laravel and have been pondering with this issue for a short while now. The main reason that I'd like to use eloquent is so that the datetime stamps work as the DB method ignores the created_at and updated_at fields. I am trying to reproduce the following query to eloquent:
$user_results = DB::table('users')->
leftJoin('roles', 'users.role_id','=', 'roles.id')->
get();
I have the following database setup
user migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('role_id')->unsigned()->index();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
roles migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRolesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('rolename');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('roles');
}
}
and the user model contains
public function role() {
return $this->belongsTo('App\Role');
}
Any help would be much appreciated.
thanks.
Simply you can replace DB::table('users') with App\User
App\User::leftJoin('roles', 'users.role_id','=', 'roles.id')->get();
I have created two tables, First is Posts table and seconds is Comments table.
I'm using sqlite database.
I'm getting null as result for comment function using hasMany method in Post Model.
Posts table migration file:
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('Posts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('Posts');
}
}
Comments table migration file:
class CreateCommentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('Comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned()->index();
$table->text('body');
$table->timestamps();
});
Schema::table('Comments', function (Blueprint $table) {
$table->foreign('post_id')->refrences('id')->on('Posts');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('Comments');
}
}
Post Model:
class Post extends Model
{
//
public function comment(){
return $this->hasMany(Comment::class);
//I have also tried: return $this->hasMany(Comment::class,'post_id','id');
}
}
The data has been entered in both the tables and I'm getting results when I do
$post=new App\Post;
$post->get();
But when I try to get all the comments for a post using
$post->comment;
I'm getting
=>Illuminate\Database\Eloquent\Collection {#633
all:[],
}
Why am I getting null as a result?
You're not. You're getting an empty Collection object. This means there are no results for your post found.
You can do $post->comment->count() === 0 and get true.
Your relationship appears wrong. You said you tried something else; that one looks more correct, going by the documentation.
https://laravel.com/docs/5.0/eloquent
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
With this, if you are still getting an empty set as a return, I would encourage you to install the Laravel debug bar and check out the raw SQL being ran. Your data is either incorrect or there is some problem that isn't being explained in your post.
Edit: You can also try setting up a belongsTo relationship on the Comment for good measure.
I have two types of workbench migrations: creating regular tables and creating pivot tables for Many-to-Many relationships.
Sample of regular migration:
<?php
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function(\Illuminate\Database\Schema\Blueprint $table)
{
$table->increments('id')->unsigned();
$table->string('login')->unique();
$table->string('username')->unique();
$table->string('password');
$table->string('email');
$table->boolean('active')->default(true);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Above migration can be rolled back
<?php
use Illuminate\Database\Migrations\Migration;
class CreatePivotRoleUser extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('role_user', function(\Illuminate\Database\Schema\Blueprint $table)
{
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->primary(['role_id', 'user_id']);
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
While this cannot, because it gives
"Class 'CreatePivotPermissionRole' not found"
error.
How to fix it?
Your code looks correct.
If CreatePivotPermissionRole is not found, it means it had been deleted before. Check the content of all your down() methods, there must be something wrong there.