ArticleController.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Http\Controllers\Controller;
  4. use App\Http\Requests\Admin\ArticleRequest;
  5. use App\Models\Article;
  6. use Exception;
  7. use Illuminate\Http\UploadedFile;
  8. use Log;
  9. class ArticleController extends Controller
  10. {
  11. // 文章列表
  12. public function index()
  13. {
  14. return view('admin.article.index', ['articles' => Article::orderByDesc('sort')->paginate(15)->appends(request('page'))]);
  15. }
  16. // 添加文章页面
  17. public function create()
  18. {
  19. return view('admin.article.create');
  20. }
  21. // 添加文章
  22. public function store(ArticleRequest $request)
  23. {
  24. $data = $request->validated();
  25. // LOGO
  26. if ($data['type'] !== '4' && $request->hasFile('logo')) {
  27. $path = $this->fileUpload($request->file('logo'));
  28. if (is_string($path)) {
  29. $data['logo'] = $path;
  30. } else {
  31. return $path;
  32. }
  33. }
  34. if ($article = Article::create($data)) {
  35. return redirect(route('admin.article.edit', $article))->with('successMsg', '添加成功');
  36. }
  37. return redirect()->back()->withInput()->withErrors('添加失败');
  38. }
  39. // 图片上传
  40. public function fileUpload(UploadedFile $file)
  41. {
  42. $fileName = Str::random(8).time().'.'.$file->getClientOriginalExtension();
  43. if (! $file->storeAs('public', $fileName)) {
  44. return redirect()->back()->withInput()->withErrors('Logo存储失败');
  45. }
  46. return 'upload/'.$fileName;
  47. }
  48. // 文章页面
  49. public function show(Article $article)
  50. {
  51. return view('admin.article.show', compact('article'));
  52. }
  53. // 编辑文章页面
  54. public function edit(Article $article)
  55. {
  56. return view('admin.article.edit', compact('article'));
  57. }
  58. // 编辑文章
  59. public function update(ArticleRequest $request, Article $article)
  60. {
  61. $data = $request->validated();
  62. $data['logo'] = $data['logo'] ?? null;
  63. // LOGO
  64. if ($data['type'] !== '4' && $request->hasFile('logo')) {
  65. $path = $this->fileUpload($request->file('logo'));
  66. if (is_string($path)) {
  67. $data['logo'] = $path;
  68. } else {
  69. return $path;
  70. }
  71. }
  72. if ($article->update($data)) {
  73. return redirect()->back()->with('successMsg', '编辑成功');
  74. }
  75. return redirect()->back()->withInput()->withErrors('编辑失败');
  76. }
  77. // 删除文章
  78. public function destroy(Article $article)
  79. {
  80. try {
  81. $article->delete();
  82. } catch (Exception $e) {
  83. Log::error('删除文章失败:'.$e->getMessage());
  84. return response()->json(['status' => 'fail', 'message' => '删除失败:'.$e->getMessage()]);
  85. }
  86. return response()->json(['status' => 'success', 'message' => '删除成功']);
  87. }
  88. }