NewsResource.php 16KB

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