|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Pharaonic\Laravel\Menus\Models; |
| 4 | + |
| 5 | +use Illuminate\Database\Eloquent\Model; |
| 6 | +use Pharaonic\Laravel\Translatable\Translatable; |
| 7 | + |
| 8 | +/** |
| 9 | + * @property integer $id |
| 10 | + * @property string $section |
| 11 | + * @property string $url |
| 12 | + * @property integer $sort |
| 13 | + * @property integer $visible |
| 14 | + * @property Carbon $created_at |
| 15 | + * @property Carbon $updated_at |
| 16 | + * @property MenuTranslation $translations |
| 17 | + * |
| 18 | + * @author Moamen Eltouny (Raggi) <raggi@raggitech.com> |
| 19 | + */ |
| 20 | +class Menu extends Model |
| 21 | +{ |
| 22 | + use Translatable; |
| 23 | + |
| 24 | + /** |
| 25 | + * Fields List |
| 26 | + * |
| 27 | + * @var array |
| 28 | + */ |
| 29 | + protected $fillable = ['section', 'url', 'sort', 'visible']; |
| 30 | + |
| 31 | + /** |
| 32 | + * Translatable attributes names. |
| 33 | + * |
| 34 | + * @var array |
| 35 | + */ |
| 36 | + protected $translatableAttributes = ['title']; |
| 37 | + |
| 38 | + /** |
| 39 | + * The attributes that should be cast. |
| 40 | + * |
| 41 | + * @var array |
| 42 | + */ |
| 43 | + protected $casts = [ |
| 44 | + 'data' => 'array', |
| 45 | + 'sort' => 'integer', |
| 46 | + 'visible' => 'boolean', |
| 47 | + ]; |
| 48 | + |
| 49 | + /** |
| 50 | + * Get section'items. |
| 51 | + * |
| 52 | + * @param \Illuminate\Database\Eloquent\Builder $query |
| 53 | + * @param string $section |
| 54 | + * @param string|null $locale |
| 55 | + * @return \Illuminate\Database\Eloquent\Builder |
| 56 | + */ |
| 57 | + public function scopeSection($query, string $section, string $locale = null) |
| 58 | + { |
| 59 | + return $query->translated($locale)->where('section', $section)->where('visible', true)->orderBy('sort', 'ASC'); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Create a localized menu. |
| 64 | + * |
| 65 | + * @param string $section |
| 66 | + * @param string $title |
| 67 | + * @param string $url |
| 68 | + * @param integer $sort |
| 69 | + * @param boolean $visible |
| 70 | + * @param string $locale |
| 71 | + * @return Menu |
| 72 | + */ |
| 73 | + public static function create(string $section, string $title, string $url, int $sort = 0, bool $visible = true, string $locale = null) |
| 74 | + { |
| 75 | + $menu = new self; |
| 76 | + $menu->section = $section; |
| 77 | + $menu->url = $url; |
| 78 | + $menu->sort = $sort; |
| 79 | + $menu->visible = $visible; |
| 80 | + $menu->save(); |
| 81 | + |
| 82 | + $menu->translateOrNew($locale ?? app()->getLocale())->title = $title; |
| 83 | + $menu->save(); |
| 84 | + |
| 85 | + return $menu; |
| 86 | + } |
| 87 | +} |
0 commit comments