Skip to content

Instantly share code, notes, and snippets.

@NandoKstroNet
Created May 31, 2022 23:08
Show Gist options
  • Save NandoKstroNet/367ef1089d92310bbb79888eb57ba164 to your computer and use it in GitHub Desktop.
Save NandoKstroNet/367ef1089d92310bbb79888eb57ba164 to your computer and use it in GitHub Desktop.
Componente Botão Favorito Livewire - Laravel Mastery https://laravelmastery.com.br
<button wire:click="toggleFavorite">
@if(!$this->favoriteByUser)
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
</svg>
@else
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-red-800" fill="currentColor" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
</svg>
@endif
</button>
<?php
//Model Content
protected $fillable = ['user_id'];
public function favoriteable()
{
return $this->morphTo();
}
<?php
namespace App\Http\Livewire;
use App\Models\Content;
use App\Models\User;
use Livewire\Component;
class FavoriteButton extends Component
{
public $model;
public function mount($model)
{
$this->model = $model;
}
public function toggleFavorite()
{
/** @var User $user */
$user = auth()->user();
$contentFavorites = Content::find($this->model)->favorites();
if(!$contentFavorites->where('user_id', $user->id)->count()) {
$contentFavorites->create(['user_id' => $user->id]);
}else {
$contentFavorites->where('user_id', $user->id)->delete();
}
}
public function getFavoriteByUserProperty()
{
return Content::find($this->model)->favorites()->whereUserId(auth()->id())->count();
}
public function render()
{
return view('livewire.favorite-button');
}
}
<?php
Schema::create('favorites', function (Blueprint $table) {
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->morphs('favoriteable');
$table->timestamps();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment