Advertisement
Guest User

Untitled

a guest
Feb 18th, 2018
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App;
  4.  
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Support\Facades\Session;
  7.  
  8. class Book extends Model
  9. {
  10. protected $fillable = ['title', 'author_id', 'amount'];
  11.  
  12. public static function boot()
  13. {
  14. parent::boot();
  15.  
  16. self::updating(function ($book)
  17. {
  18. if ($book->amount < $book->borrowed) {
  19. Session::flash("flash_notification", [
  20. "level" => "danger",
  21. "message" => "Jumlah buku $book->title harus >= " . $book->borrowed
  22. ]);
  23.  
  24. return false;
  25. }
  26. });
  27.  
  28. self::deleting(function ($book)
  29. {
  30. if ($book->borrowLogs()->count() > 0) {
  31. Session::flash("flash_notification", [
  32. "level" => "danger",
  33. "message" => "Buku $book->title sudah pernah dipinjam."
  34. ]);
  35. return false;
  36. }
  37. });
  38. }
  39.  
  40. public function getBorrowedAttribute()
  41. {
  42. return $this->borrowLogs()->borrowed()->count();
  43. }
  44.  
  45. public function author()
  46. {
  47. return $this->belongsTo('App\Author');
  48. }
  49.  
  50. public function borrowLogs()
  51. {
  52. return $this->hasMany('App\BorrowLog');
  53. }
  54.  
  55.  
  56. public function getStockAttribute()
  57. {
  58. $borrowed = $this->borrowLogs()->borrowed()->count();
  59. $stock = $this->amount - $borrowed;
  60.  
  61. return $stock;
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement