Issue
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();
});
}
Solution
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;
}
Answered By - user6705732
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.