Call to undefined method Illuminate\Database\Query\Builder::withTrashed() - php

Not sure what im doing wrong but im getting this error, and im not sure how to solve it.
i referenced this, but im still unsure, maybe its my schema migration
im using laravel 5.5
laravel 5.2 Call to undefined method Illuminate\Database\Query\Builder::associate()
Call to undefined method
Illuminate\Database\Query\Builder::withTrashed()
PostController.php
public function isLikedByMe($id)
{
$post = Post::findOrFail($id)->first();
if (Like::whereUserId(auth()->id())->wherePostId($post->id)->exists()){
return 'true';
}
return 'false';
}
public function like(Post $post)
{
$existing_like = Like::withTrashed()->wherePostId($post->id)->whereUserId(auth()->id())->first();
if (is_null($existing_like)) {
Like::create([
'post_id' => $post->id,
'user_id' => auth()->id()
]);
} else {
if (is_null($existing_like->deleted_at)) {
$existing_like->delete();
} else {
$existing_like->restore();
}
}
Likes Model
class Like extends Model
{
//
}
User model condensed to whats important
public function likes()
{
return $this->belongsToMany('App\Post', 'likes', 'user_id', 'post_id');
}
Post model
public function likes()
{
return $this->belongsToMany('App\User', 'likes');
}
Migration:
likes migration
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->foreign('user_id')->references('id')->on('users');
$table->softDeletes();
$table->timestamps();
});
}
Posts migration
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}

Your Eloquent model should use the Illuminate\Database\Eloquent\SoftDeletes trait to make use of the withTrashed() method.
Like::class
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Like extends Model
{
use SoftDeletes;
}

Had the same issue, the problem was that I used DB::table($table_name) instead of calling the model, using the model helped.
Regards

Related

Laravel: Order a model by "Has One Of Many" relationship

I have a customer model that has many contacts. I defined a relationship to get the most recent contact of the customer using the "Has One Of Many" relationship in Laravel 8:
Models
class Customer extends Model
{
use HasFactory;
public function contacts()
{
return $this->hasMany(Contact::class);
}
public function latestContact()
{
return $this->hasOne(Contact::class)->ofMany('contacted_at', 'max')->withDefault();
}
}
class Contact extends Model
{
use HasFactory;
protected $casts = [
'contacted_at' => 'datetime',
];
public function customer()
{
return $this->belongsTo(Customer::class);
}
}
Migration (contact model)
class CreateContactsTable extends Migration
{
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->softDeletes();
$table->foreignID('customer_id');
$table->string('type');
$table->dateTime('contacted_at');
});
}
}
In my view, I want to show all customers and order them by their latest contact. However, I can't figure out how to do that.
I tried to achieve it via the join method but then I obviously get various entries per customer.
$query = Customer::select('customers.*', 'contacts.contacted_at as contacted_at')
->join('contacts', 'customers.id', '=', 'contacts.customer_id')
->orderby('contacts.contacted_at')
->with('latestContact')
Knowing Laravel there must be a nice way or helper to achieve this. Any ideas?
I think the cleanest way to do this is by using a subquery join:
$latestContacts = Contact::select('customer_id',DB::raw('max(contacted_at) as latest_contact'))->groupBy('customer_id');
$query = Customer::select('customers.*', 'latest_contacts.latest_contact')
->joinSub($latestContacts, 'latest_contacts', function ($join){
$join->on([['customer.id', 'latest_contacts.customer_id']]);
})
->orderBy('latest_contacts.latest_contact')
->get();
More info: https://laravel.com/docs/8.x/queries#subquery-joins
I suspect there is an issue with your migration, the foreign key constraint is defined like this:
Check the documentation:
https://laravel.com/docs/8.x/migrations#foreign-key-constraints
Method 1: define foreign key constraint
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->foreignId('consumer_id')->constrained();
$table->string('type');
$table->dateTime('contacted_at');
$table->timestamps();
$table->softDeletes();
});
}
Method 2: define foreign key constraint
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('customer_id');
$table->foreign('customer_id')->references('id')->on('customers');
$table->string('type');
$table->dateTime('contacted_at');
$table->timestamps();
$table->softDeletes();
});
}

Laravel paginate polymorphic relationship, topic->comments()

I'm building a basic forum, there are many topics and each topic has comments, a comment or "commentable" can be a a comment or a reply (commented a comment), this is because I want to have nested comments, that's where parent_id is useful. I'm wondering if my polymorphic relationship is the best way to achieve this so I'm open to any suggestions. The first issue I came up with is I don't know hw to do ajax pagination of topic->comments ..., I thought with something like Comment::whereHas('topic') ... but my comments dont' have a topic relationship defined in the model.
I'm using laravel advanced ajax pagination, how can I paginate comments?
Topic model:
class Topic extends Model
{
protected $table = 'topics';
public function author()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function comments()
{
return $this->morphMany('App\Models\Comment', 'commentable')->whereNull('parent_id');
}
public function up()
{
Schema::create('topics', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index();
$table->foreign('user_id')->references('id')->on('users');
$table->string('title');
$table->text('body');
$table->string('url')->unique();
$table->string('slug')->unique();
$table->boolean('isVisible')->default(false);
$table->timestamps();
});
}
}
Comment model:
class Comment extends Model
{
protected $table = 'comments';
public function author()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function replies()
{
return $this->hasMany('App\Models\Comment', 'parent_id');
}
}
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->integer('parent_id')->unsigned();
$table->integer('commentable_id')->unsigned();
$table->string('commentable_type');
$table->text('body');
$table->timestamps();
});
}
This is where I took inspiration:

App\Tasks::first()->projects; in artisan tinker returns null, no matter what :(

The following code in tinker returns a null value while it should return the project to which the first task is linked.
App\Task::first()->projects;
Already tried renaming the method names, column names in migrations, tried exiting tinker and logging back in
Project Migration
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('title');
$table->string('description');
$table->timestamps();
});
}
Task Migration
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('project_id');
$table->string('description');
$table->boolean('completed')->default(false);
$table->timestamps();
});
}
Project.php
use App\Task;
class Project extends Model
{
protected $fillable = ['title','description'];
public function tasks(){
return $this->hasMany(Task::class);
}
}
Task.php
use App\Project;
class Task extends Model
{
protected $fillable = [
'completed'
];
public function projects(){
return $this->belongsTo(Project::class);
}
}
If anyone could just review this piece of code and let me know where I have made any conventional\idiotic mistakes (since Im new to route model binding) it would be of great help!
A task belongs to a project, so rename projects to project as it is singular. If you keep projects then provide the column name as second parameter:
public function projects(){
return $this->belongsTo(Project::class, 'project_id');
}
// I suggest this
public function project(){
return $this->belongsTo(Project::class);
}
Your column types are different, for the id of the project you use Big Integer and for the reference you use Integer, so this:
$table->unsignedInteger('project_id');
should be this:
$table->unsignedBigInteger('project_id');
// also good to make the relationship on the Database level:
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');

Undefined property: Illuminate\Database\Eloquent\Relations\MorphMany::$title

Sorry for bad English at first )
I'm new to laravel5 and trying to use polymorphic relations
here is the code
class Post extends Model
{
public function seo()
{
return $this->MorphMany('App\Seo' , 'seoable');
}
}
class Seo extends Model
{
public function seoble()
{
return $this->morphTo();
}
}
and in the view I try to retrieve post seo data like this
$post->seo()->title;
here is my DB
Schema::create('seos', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('keywords');
$table->text('description');
$table->string('og_type');
$table->string('og_title');
$table->text('og_description');
$table->integer('seoable_id');
$table->string('seoable_type');
$table->timestamps();
});
but I got the error
Undefined property:
Illuminate\Database\Eloquent\Relations\MorphMany::$title (View: /Applications/MAMP/htdocs/lblog/resources/views/posts/form.blade.php)
Try this:
$post->seo->first()->title; or $post->seo()->get()->first()->title;
the reason why it doesn't work because the the seo() function until now is just a query, you need to execute that query like above

laravel eloquent for hasMany relation does not work

I have these relations in my database
Schema::create('my_users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('fullName');
$table->string('userName');
$table->string('password');
$table->string('photo');
$table->string('email');
});
and
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('photo');
$table->text('caption');
$table->integer('like');
$table->integer('my_user_id');
});
my models :
class myUser extends Model
{
public function post()
{
return $this->hasMany('App\post');
}
}
class post extends Model
{
public function user()
{
return $this->belongsTo('App\myUser');
}
}
now I'm trying to get a user's data using the following code :
$post = post::find(1);
$user = $post->user;
but it doesn't work and $user is NULL.
I'm sure that in posts table there is a record with id 1.
the weird part is this that I get no error when I change the method's name like this :
$post = post::find(1);
$user = $post->somethingBullshit;
I'm using laravel 5.3.
help please.
Confirm that you are naming your class files starting with upper case letters, and modify your class declarations accordingly, such as:
class MyUser extends Model
{
public function post()
{
return $this->hasMany('App\Post');
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo('App\MyUser');
}
}
You can then select the user when you obtain the post by utilizing eloquent's with() method, and obtain your $user variable from your $post variable, OR just use the user property of post as follows:
$post = Post::with('user')->find(1);
$user = $post->user;

Categories