Livewire blog (an open source blog built with laravel 8 + jetstream)

Time:2020-10-30

background

Laravel 8 has been released for nearly a month, and this change is more attractive to meJetstreamFamily bucket. I didn’t touch it before it was releasedLivewireAnd the front endTailwindcssalpinejs。 But I’m a person who prefers to try new technologies. It is obviously not advisable to practice in commercial projects. So I plan to make use of the holiday time to try my blog at the beginning of national day to understand its characteristics. Then go to the corresponding project to use. After a period of time, I found this thing very fragrant. Of course, there are also some pits that I will share.

Livewire-Blog

GitHub code addressStar, please

Blog online address

PC interface effect

Livewire blog (an open source blog built with laravel 8 + jetstream)

Livewire blog (an open source blog built with laravel 8 + jetstream)

Livewire blog (an open source blog built with laravel 8 + jetstream)

Mobile interface effect

Livewire blog (an open source blog built with laravel 8 + jetstream)

Livewire blog (an open source blog built with laravel 8 + jetstream)

functional analysis

Search cases

The biggest advantage of livewire is the dynamic interaction with the front-end interface. For example, when I search larravel, it can cooperate with the front-end to listen to my input. The data in the background is called by API in real time and returned to the front end. These APIs don’t need to be written by you. Its core documentLivewireServiceProviderAlready registered. Interested students can take a look at this core document.

php artisan make:livewire searchgeneratesearch.blade.php Search.phpfile

  • search.blade.php

Livewire blog (an open source blog built with laravel 8 + jetstream)

  • Search.php

Livewire blog (an open source blog built with laravel 8 + jetstream)

  • View effects

Livewire blog (an open source blog built with laravel 8 + jetstream)

Comment on cases

It will be used in the commentsLivewireComponent global events communicate with each other

  • requirement analysis

Livewire blog (an open source blog built with laravel 8 + jetstream)

  • code implementation

php artisan make:livewire AddComment
php artisan make:livewire ShowComment

  • AddComment
<?php

namespace App\Http\Livewire;

use App\Models\CommentModel;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Str;
use Illuminate\View\View;
use Livewire\Component;
class AddComment extends Component
{
    /**
     * @var string
     */
    public $content;
    /**
     * @var int
     */
    public $post_id;
    /**
     * @var int
     */
    public $parent_id;
    /**
     * @var string
     */
    public $comment_composing_box_id;
    /**
     * @var string
     */
    public $preview_box_id;
    /**
     * @var string
     */
    public $target_id;

    /**
     * @var array
     */
    protected $rules = [
        'content' => 'required',
    ];
    /**
     * @var array
     */
    protected $messages = [
        ' content.required '= >' comment cannot be empty! ',
    ];

    public function mount(int $postId, CommentModel $comment, int $time = 0): void
    {
        $this->post_id = $postId;
        $this->parent_id = empty($comment->id) ? 0 : ($comment->parent_id ? $comment->parent_id : $comment->id);
        $this->target_id = empty($comment->id) ? 0 : $comment->id;
        $this->content = ($time > 0 && ! empty($comment->user)) ? '@'.$comment->user->name.':' : '';
        $this->comment_composing_box_id = 'comment-composing-box-'.Str::random(10);
        $this->preview_box_id = 'preview-box'.Str::random(10);
    }

    public function submit(): void
    {
        if ($this->check()) {
            $validatedData = $this->validate();
            $data = [
                'content'   => $validatedData['content'],
                'user_id'   => Auth::user()->id,
                'parent_id' => $this->parent_id,
                'post_id'   => $this->post_id,
                'target_id' => $this->target_id,
            ];

            CommentModel::create($data);

            $this->reset('content');

            $this->emitTo('show-comment', 'create', $this->post_id);

            Session () - > flash ('message ','comment added successfully! ).
        }
    }

    public function userCommentLimit(MessageBag &$messageBag): void
    {
        $time = Cache::get(user_comment_limit_key()) ?? 0;
        $limit_day_time = config('cache.user_comment_limit.day_time', 10);

        if ($limit_day_time < $time) {
            $messageBag->add('content', Str::replaceFirst('?', $limit_ day_ Time, 'users can only reply to comments at most every day');
        } else {
            Cache::put(user_comment_limit_key(), $time + 1, Carbon::today()->addDay());
        }
    }

    /**
     * @param MessageBag $messageBag
     */
    public function mustLogin(MessageBag &$messageBag): void
    {
        Auth:: guest() & - $message bag - > Add ('content ','user needs to log in! ).
    }

    /**
     * @return bool
     */
    public function check(): bool
    {
        $messageBag = $this->getErrorBag();
        $this->userCommentLimit($messageBag);
        $this->mustLogin($messageBag);

        return $messageBag->count() === 0;
    }

    /**
     * @return View
     */
    public function render(): View
    {
        return view('livewire.add-comment');
    }
}
  • ShowComment
<?php

namespace App\Http\Livewire;

use App\Models\PostModel;
use App\Repositories\BlogRepository;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Livewire\Component;

class ShowComment extends Component
{
    /**
     * @var int
     */
    public $postId;
    /**
     * @var Collection
     */
    public $comments;
    /**
     * @var int
     */
    public $comments_count = 0;
    /**
     * @var array
     */
    protected $listeners = ['create' => 'getCommens'];

    /**
     * @param $postIds
     */
    public function mount(PostModel $post): void
    {
        $this->postId = $post->id;
        $this->comments = $post->comments;
        $this->comments_count = $post->comments->count() ?? 0;
    }

    /**
     * $params.
     */
    public function getCommens(int $postId): void
    {
        $post = BlogRepository::getPostById($postId);
        $this->comments = $post->comments;
        $this->comments_count = $post->comments->count() ?? 0;
    }

    /**
     * @return View
     */
    public function render(): View
    {
        return view('livewire.show-comment');
    }
}
  • analysis

What’s more important is thatemitTo This means to whom you need to notify when the processing of this component is completed, such as notificationShowCommentThat is $this->emitTo('show-comment', 'create', $this->post_id)The component name can be printedShowComment::getName()get.

  • The pit I met

    • Comments I want to loop nested. If eachshow-comment.blade.phpGo and nest yourself,emitToMany will be informedShowComment, I don’t see the component can be used according toName + IDTo notify synchronized. I used it in the backincludeNested loop template. Interested people can look at my code.
  • Addcomment component I want to verify whether the user logs in or not, which cannot be implemented through middleware. I will verify it in the component method later. If you have a good way, you can also tell me.