NewsResource.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. namespace App\Filament\Resources;
  3. use App\Filament\Resources\NewsResource\Pages;
  4. use App\Models\News;
  5. use App\Models\NewsCategory;
  6. use Filament\Forms\Components\Actions\Action;
  7. use Filament\Forms\Components\Group;
  8. use Filament\Forms\Components\Repeater;
  9. use Filament\Forms\Components\RichEditor;
  10. use Filament\Forms\Components\TextInput;
  11. use Filament\Forms\Components\Textarea;
  12. use Filament\Forms\Components\Select;
  13. use Filament\Forms\Components\Radio;
  14. use Filament\Forms\Components\Section;
  15. use Filament\Forms\Components\Toggle;
  16. use Filament\Forms\Components\DatePicker;
  17. use Filament\Forms\Components\FileUpload;
  18. use Filament\Forms\Get;
  19. use Filament\Forms\Form;
  20. use Filament\Resources\Resource;
  21. use Filament\Tables;
  22. use Filament\Tables\Columns\IconColumn;
  23. use Filament\Tables\Columns\ImageColumn;
  24. use Filament\Tables\Columns\TextColumn;
  25. use Filament\Tables\Filters\SelectFilter;
  26. use Filament\Tables\Table;
  27. use Illuminate\Database\Eloquent\Builder;
  28. use Illuminate\Support\Facades\DB;
  29. use Illuminate\Support\Str;
  30. use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
  31. use RalphJSmit\Filament\SEO\SEO;
  32. class NewsResource extends Resource
  33. {
  34. protected static ?string $model = News::class;
  35. protected static ?string $modelLabel = "文章管理";
  36. protected static ?string $navigationIcon = 'heroicon-o-newspaper';
  37. protected static ?string $navigationGroup = '上稿內容管理';
  38. protected static ?string $navigationLabel = "文章管理";
  39. public static function form(Form $form): Form
  40. {
  41. return $form
  42. ->schema([
  43. //
  44. Section::make("新增 文章")->schema([
  45. Group::make()->schema([
  46. Select::make("news_category_id")
  47. ->options(NewsCategory::get()->pluck("name","id"))
  48. ->label("文章分類")
  49. ->columnSpan(1)
  50. ->native(false)
  51. ->afterStateHydrated(function ($component, $state) {
  52. // ✅ 如果沒有值,設定為第一項
  53. if (empty($state)) {
  54. $firstCategoryId = NewsCategory::first()?->id;
  55. if ($firstCategoryId) {
  56. $component->state($firstCategoryId);
  57. }
  58. }
  59. })
  60. ->required(),
  61. ])->columnSpanFull()->columns(2),
  62. Group::make()->schema([
  63. DatePicker::make('post_date')
  64. ->label("發布日期")
  65. ->closeOnDateSelection(),
  66. ])->columnSpanFull()->columns(2),
  67. FileUpload::make('news_img_pc')->label("列表圖(desktop)")
  68. ->disk("public")
  69. // ->helperText('建議寬高限制為:1280*720px,檔案大小限制為1M以下')->maxSize('1024')
  70. ->directory("news"),
  71. FileUpload::make('news_img_mobile')->label("列表圖(mobile)")
  72. ->disk("public")
  73. // ->helperText('建議寬高限制為:600*896px,檔案大小限制為1M以下')->maxSize('1024')
  74. ->directory("news"),
  75. Translate::make()->schema(fn (string $locale) => [
  76. TextInput::make('title')
  77. ->label("標題")
  78. ->columnSpan(1),
  79. TextInput::make('written_by')
  80. ->label("發佈者")->columnSpan(1),
  81. Textarea::make("description")->rows(5)->columnSpanFull()->label("短文"),
  82. ])->locales(["zh_TW", "en"])
  83. ->id("main")
  84. ->columnSpanFull()->columns(3),
  85. TextInput::make('order')->label("排序")->integer()->default(0),
  86. ])->columns(3),
  87. Section::make("SEO")->schema([
  88. // SEO::make(),
  89. Translate::make()->schema(fn (string $locale) => [
  90. TextInput::make('meta_title')->label("SEO 標題")->columnSpan(1),
  91. Textarea::make("meta_keyword")->rows(5)->columnSpanFull()->label("SEO 關鍵字"),
  92. Textarea::make("meta_description")->rows(5)->columnSpanFull()->label("SEO 短文"),
  93. ])
  94. ->locales(["zh_TW", "en"])
  95. ->id("seo"),
  96. FileUpload::make('meta_img')->label("放大預覽圖")->disk("public")
  97. // ->helperText('建議寬高限制為:1200*630px,檔案大小限制為1M以下')->maxSize('1024')
  98. ->directory("seo/news"),
  99. ])->columnSpanFull(),
  100. Section::make("文章內容")->schema([
  101. Repeater::make("paragraphs")->schema([
  102. TextInput::make('item_key')
  103. ->default(fn () => Str::random())
  104. ->hidden()
  105. ->afterStateHydrated(function (TextInput $component, $state) {
  106. if (empty($state)) {
  107. $component->state(Str::random());
  108. }
  109. }),
  110. Radio::make("paragraph_type")->options([
  111. 1 => "圖片",
  112. 2 => "文字",
  113. 3 => "影音",
  114. ])->label("")->default(1)->Live(),
  115. Group::make()->schema([
  116. Section::make('')->schema([
  117. Repeater::make("multiple_images")->schema([
  118. TextInput::make('para_img_item_key')
  119. ->default(fn () => Str::random())
  120. ->hidden()
  121. ->afterStateHydrated(function (TextInput $component, $state) {
  122. if (empty($state)) {
  123. $component->state(Str::random());
  124. }
  125. }),
  126. Translate::make()->schema(fn (string $locale) => [
  127. TextInput::make('image_alt')->label("圖片註文"),
  128. ])->locales(["zh_TW", "en"])
  129. ->id(fn ($get) => "para_img_mul_" . $get('para_img_item_key')),
  130. FileUpload::make('image_url')->label("")->disk("public")
  131. // ->helperText('建議寬高限制為:1080*675px,檔案大小限制為1M以下')->maxSize('1024')
  132. ->directory("news/extraPhoto")
  133. ->maxFiles(10),
  134. ])
  135. ->relationship("photos")
  136. ->label("")
  137. ->orderColumn('order')
  138. ])
  139. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 1),
  140. Group::make()->schema([
  141. Translate::make()->schema(fn (string $locale) => [
  142. RichEditor::make('text_content')
  143. ->toolbarButtons([
  144. 'blockquote',
  145. 'bold',
  146. 'bulletList',
  147. 'h2',
  148. 'h3',
  149. 'italic',
  150. 'link',
  151. 'orderedList',
  152. 'redo',
  153. 'strike',
  154. 'underline',
  155. 'undo',
  156. ])
  157. ->disableToolbarButtons([
  158. 'blockquote',
  159. 'strike',
  160. 'attachFiles',
  161. ])
  162. ->fileAttachmentsDirectory('attachments')
  163. ->fileAttachmentsVisibility('private'),
  164. ])
  165. ->locales(["zh_TW", "en"])
  166. ->id(fn ($get) => "para_text_" . $get('item_key')),
  167. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 2),
  168. Group::make()->schema([
  169. Section::make("")->schema([
  170. FileUpload::make('video_img')->label("影片底圖")
  171. ->disk("public")
  172. ->directory("news/paragraph/video"),
  173. // ->helperText('建議寬高限制為:2000*720px,出血寬度720px,主要圖像範圍為:1280*720px,檔案大小限制為1M以下')->maxSize('1024'),
  174. Translate::make()->schema(fn (string $locale) => [
  175. TextInput::make('video_img_alt')->label("圖片註文")->columnSpan(1),
  176. ])->locales(["zh_TW", "en"])
  177. ->id(fn ($get) => "para_video_img_alt_" . $get('item_key')),
  178. Radio::make("video_type")->label("")->options([
  179. 1 => "網址",
  180. 2 => "檔案"
  181. ])->columnSpanFull()->default(1)->Live(),
  182. Group::make()->schema([
  183. TextInput::make('link')->label("網址")->nullable(),
  184. ])->visible(fn (Get $get):bool => $get("video_type") == 1)->columnSpanFull(),
  185. Group::make()->schema([
  186. FileUpload::make('video_url')->label("")->disk("public")->directory("news/paragraph/video")
  187. // ->helperText('建議影片寬高限制為:1920*1080px,出血寬度720px,大小限制為:100M以下')
  188. // ->maxSize(102400)
  189. ->nullable(),
  190. ])->visible(fn (Get $get):bool => $get("video_type") == 2)->columnSpanFull(),
  191. ]),
  192. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 3),
  193. ])
  194. ->relationship("paragraphs")
  195. ->label("段落")
  196. ->collapsible()
  197. ->reorderableWithButtons()
  198. ->orderColumn('order')
  199. ->cloneable()
  200. ]),
  201. ]);
  202. }
  203. public static function table(Table $table): Table
  204. {
  205. return $table
  206. ->columns([
  207. //
  208. TextColumn::make("newsCategory.name")->label("分類")->alignCenter(),
  209. TextColumn::make("title")->label("標題")->alignCenter(),
  210. TextColumn::make("written_by")->label("發佈者")->alignCenter(),
  211. TextColumn::make("post_date")->label("發佈時間")->dateTime('Y/m/d')->alignCenter(),
  212. ImageColumn::make("news_img_pc_url")->label("列表圖")->alignCenter(),
  213. TextColumn::make("list_audit_state")->label("狀態")->badge()
  214. ->color(fn (string $state): string => match ($state) {
  215. '暫存' => 'warning',
  216. '已發佈' => 'success',
  217. }),
  218. IconColumn::make("on_top")->label("置頂")
  219. ->color(fn (string $state): string => match ($state) {
  220. 1 => 'success',
  221. default => ''
  222. })
  223. ->icon(fn (string $state): string => match ($state) {
  224. 1 => 'heroicon-o-check-circle',
  225. default => ''
  226. })
  227. ->action(function ($record): void {
  228. $record->on_top = !$record->on_top;
  229. $record->save();
  230. }),
  231. TextColumn::make("created_at")->label("建立時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
  232. TextColumn::make("updated_at")->label("更新時間")->dateTime()->alignCenter(),
  233. ])
  234. ->filters([
  235. SelectFilter::make('news_category_id')->label("分類")
  236. ->options(NewsCategory::orderBy("order")->pluck("name", "id"))
  237. ->attribute('news_category_id'),
  238. SelectFilter::make('post_date')->label("年份")
  239. ->options(News::select(DB::raw("DATE_FORMAT(post_date, '%Y') as year"))->whereNotNull("post_date")->distinct()->pluck("year","year")->toArray())
  240. ->query(
  241. fn (array $data, Builder $query): Builder =>
  242. $query->when(
  243. $data['value'],
  244. fn (Builder $query, $value): Builder => $query->where('post_date', 'like', $data['value']. "%")
  245. )
  246. ),
  247. SelectFilter::make('visible')->label("狀態")
  248. ->options([
  249. 0 => "暫存",
  250. 1 => "已發佈",
  251. ])
  252. ->query(
  253. fn (array $data, Builder $query): Builder =>
  254. $query->when(
  255. $data['value'],
  256. fn (Builder $query, $value): Builder => $query->where('visible', $data['value'])
  257. )
  258. ),
  259. ])
  260. ->actions([
  261. Tables\Actions\EditAction::make(),
  262. Tables\Actions\DeleteAction::make(),
  263. \Filament\Tables\Actions\Action::make("audit")
  264. ->label(fn ($record) => match ($record->visible) {
  265. 0 => '發佈',
  266. 1 => '下架',
  267. })
  268. ->color(fn ($record) => match ($record->visible) {
  269. 0 => 'warning',
  270. 1 => 'gray',
  271. })
  272. ->icon(fn ($record) => match ($record->visible) {
  273. 0 => 'heroicon-m-chevron-double-up',
  274. 1 => 'heroicon-m-chevron-double-down',
  275. })
  276. ->action(function ($record): void {
  277. $record->visible = !$record->visible;
  278. $record->save();
  279. })
  280. ->outlined()
  281. ->requiresConfirmation(),
  282. ])
  283. ->bulkActions([
  284. Tables\Actions\BulkActionGroup::make([
  285. Tables\Actions\DeleteBulkAction::make(),
  286. ]),
  287. ])
  288. ->defaultSort('order', 'desc')
  289. ->defaultSort('created_at', 'desc');
  290. }
  291. public static function getRelations(): array
  292. {
  293. return [
  294. //
  295. ];
  296. }
  297. public static function getPages(): array
  298. {
  299. return [
  300. 'index' => Pages\ListNews::route('/'),
  301. 'create' => Pages\CreateNews::route('/create'),
  302. 'edit' => Pages\EditNews::route('/{record}/edit'),
  303. 'view' => Pages\ViewNews::route('/{record}/view'),
  304. ];
  305. }
  306. }