简体   繁体   中英

Challenge with Laravel Checkbox to Publish or Not Publish Post

I have a question about Laravel. I am creating a blog that allows the user to upload a new post to the page. Below is the picture about how the form looks like when the user clicks the button Create New Post on the page.

In the form, there is a checkbox called Publish which allows the user to choose if they want to publish the post or not.

  1. If the user checks "Publish", the post will be displayed on the page with the word published on the column "Published".
  2. If the user checks "No Publish", when they click the button "Save", the post won't be displayed on the page.

Does anyone know how to do it? I am new to Laravel so I have no idea how to do it. I did a search on gg and people talking about something called Controller. Do I need it to do the Publish and No Publish feature?

Picture of page:

The main page where the post will be displayed (in the "Published" field should have the word "Published" in it)

后面板

The form when user clicks on the button Create New Post

模态形式新帖子

Post Schema

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->string('body');
        $table->string('author');
        $table->boolean('published')->default(0);
        //create the relationship between a task and the user that created it
        $table->integer('user_id')->unsigned()->index();
        $table->timestamps();
    });
}

Post Model

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'body', 'author', 'published'
    ];

    public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->user_id = Auth::id();
        });

        static::updating(function ($model) {
            $model->user_id = Auth::id();
        });
    }
}

app/Http/Livewire/Posts.php

class Posts extends Component
{
    public $posts, $title, $body, $post_id, $author, $published;
    public $isOpen = 0;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function render()
    {
        $user = auth()->user();

        $this->posts = $user->posts;
        return view('livewire.posts');
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function create()
    {
        $this->resetInputFields();
        $this->openModal();
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function openModal()
    {
        $this->isOpen = true;
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function closeModal()
    {
        $this->isOpen = false;
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    private function resetInputFields()
    {
        $this->title = '';
        $this->body = '';
        $this->post_id = '';
        $this->author = '';
        $this->published = '';
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function store()
    {
        $this->validate([
            'title' => 'required',
            'body' => 'required',
            'author' => 'required',
            'published' => 'required'
        ]);

        Post::updateOrCreate(['id' => $this->post_id], [
            'title' => $this->title,
            'body' => $this->body,
            'author' => $this->author,
            'published' => $this->published
        ]);

        session()->flash('message',
            $this->post_id ? 'Post Updated Successfully.' : 'Post Created Successfully.');

        $this->closeModal();
        $this->resetInputFields();
    }
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function edit($id)
    {
        $post = Post::findOrFail($id);
        $this->post_id = $id;
        $this->title = $post->title;
        $this->body = $post->body;
        $this->author = $post->author;
        $this->published = $post->published;
        $this->openModal();
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function delete($id)
    {
        Post::find($id)->delete();
        session()->flash('message', 'Post Deleted Successfully.');
    }
}

This is the.blade code I use to create checkbox for 'Publish'

<div class="mb-4">
    <label for="check" class="form-check-label">Publish:</label>
    <input class="form-check-input" id="check" value="publish" type="checkbox" name="published" wire:model="published">Publish</input>
    <input class="form-check-input" id="check" value="no-publish" type="checkbox" name="published" wire:model="published">No Publish</input>
</div>

First, if you're using checkbox don't need have two for that, check-boxes are optional things...this way is logical that if the user want to publish the post select the checkbox, if not just doesn't select it. in modal blade

<div class="mb-4">
    <label for="check" class="form-check-label">Publish:</label>
    <input class="form-check-input" id="check" value="publish" type="checkbox" name="published" wire:model="published">Publish</input>
</div>

By default, in component, $this->published = 0. But change to 1 if the user mark checkbox as selected, that way you can store this value in post model db and retrieve it. When the data is listed in blade, like your table you can do this

<table>
   <thead>
    // ...
   <tr>
     <th>Published</th>
     //....
   <tbody>
   @foreach(...)
     <tr>
      //.....
       <td>
           @if($posts->published) Published @endif
       </td>  
   //....

Hope this help you. Greetings

you can return only published post by adding query into list method

$user->posts->where("published",1)->get();

also use global scope which will let you only deal with posts with your condition https://laravel.com/docs/8.x/eloquent#global-scopes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM