1 | <?php
|
---|
2 |
|
---|
3 | namespace App\Models;
|
---|
4 |
|
---|
5 | use Carbon\Carbon;
|
---|
6 | use Illuminate\Support\Str;
|
---|
7 | use Illuminate\Database\Eloquent\Model;
|
---|
8 |
|
---|
9 | class Post extends Model
|
---|
10 | {
|
---|
11 | protected $table = "posts";
|
---|
12 |
|
---|
13 | protected $fillable = ["title", "image_link", "content", "user_id", "category_id"];
|
---|
14 |
|
---|
15 | public function user() {
|
---|
16 | return $this->belongsTo(User::class);
|
---|
17 | }
|
---|
18 |
|
---|
19 | public function category() {
|
---|
20 | return $this->belongsTo(Category::class);
|
---|
21 | }
|
---|
22 |
|
---|
23 | public function tag()
|
---|
24 | {
|
---|
25 | return $this->belongsToMany(Tag::class, "posts_tags");
|
---|
26 | }
|
---|
27 |
|
---|
28 | public function comment() {
|
---|
29 | return $this->hasMany(Comment::class);
|
---|
30 | }
|
---|
31 |
|
---|
32 | public function like()
|
---|
33 | {
|
---|
34 | return $this->hasMany(Like::class);
|
---|
35 | }
|
---|
36 |
|
---|
37 | public function getConfirmedBy() {
|
---|
38 | return User::find($this->confirmed_by)->getFullName();
|
---|
39 | }
|
---|
40 |
|
---|
41 | public function ago() {
|
---|
42 | return Carbon::parse($this->created_at)->diffForHumans();
|
---|
43 | }
|
---|
44 |
|
---|
45 | public function createSlug($isEdit = false) {
|
---|
46 |
|
---|
47 | $newSlug = Str::slug($this->title);
|
---|
48 | $slugs = Post::pluck("slug");
|
---|
49 |
|
---|
50 | if($isEdit) {
|
---|
51 | return $newSlug;
|
---|
52 | }
|
---|
53 |
|
---|
54 | if($slugs->contains($newSlug)) {
|
---|
55 | $id = $this->latest("id")->first()->id + 1;
|
---|
56 | $newSlug = $newSlug . "-" . $id;
|
---|
57 | }
|
---|
58 |
|
---|
59 | return $newSlug;
|
---|
60 | }
|
---|
61 |
|
---|
62 | public function isLiked($ipAddress) {
|
---|
63 |
|
---|
64 | $likes = $this->like->all();
|
---|
65 |
|
---|
66 | foreach($likes as $like) {
|
---|
67 | if($this->id == $like->post_id && $ipAddress == $like->ip_address) {
|
---|
68 | return true;
|
---|
69 | }
|
---|
70 | }
|
---|
71 |
|
---|
72 | return false;
|
---|
73 | }
|
---|
74 | }
|
---|