Search code examples
laravellaravel-blade

Draft posts who supposed to not show in a view


i have a method in a controller, who have the work to display all the posts by user by ID. Every post have a user_id (relation 1/M). Every post have a ENUM (status) with 3 choices (active/inactive/draft)

my idea with the controller method is ONLY DISPLAY all the posts who the status as draft and the user_id must be the same as the post user_id.

this is the method (Controller):

public function draft(Post $post, User $user)
{
    $drafts = Post::where('status', __('draft'))
        ->where($post->user_id == auth()->user()->id)
        ->paginate(8);

    return view('post.draft', compact('drafts'));
}

The idea is to display all matching posts as draft and the logged user (id) equals user_id which comes to posts user_id.

This is the way how i display in the blade:

@forelse ($drafts as $draft)
    <div class="bg-white p-2">
        <h2 class="text-black">
            {{ $draft->title }}
        </h2>
    </div>
@empty
    <p>{{ __('There is no posts') }}</p>
@endforelse

in the models i have:

POST:

protected $guarded = ['id', 'created_at', 'updated_at'];

public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

USER:

public function posts(): HasMany
{
    return $this->hasMany(Post::class);
}

Solution

  • Your draft method should be as below,

    public function draft(User $user)
    {
        $drafts = Post::where('status', 'draft')
            ->where('user_id', auth()->user()->id)
            ->paginate(8);
    
        return view('post.draft', compact('drafts'));
    }
    

    There are 2 issues in your draft method

    1. You are using __('draft'), which will return the translation value of string draft. Check the usage of __() here.

    2. where($post->user_id == auth()->user()->id). In where() you need to provide the column name i.e.user_id