LaravelでCRUDの練習中です。
画像をpublic配下のimagesフォルダに保存しつつ、ファイルネームをデータベースに保存する感じで作りました。
新規投稿の方はうまくいったのに、更新がうまくいきません。
「dd();」で見てみるとバリデーションが通っていません。
新規投稿と同じ画像を使ってもダメなのですが、原因がわかりません。
よろしくお願いします。
環境
さくらレンタルサーバー
laravel5.7
apache
php7.2
mysql5.7
成功するstoreメソッド
PostsContlroller.php
1class PostsController extends Controller 2{ 3... 4public function store(Request $request) 5 { 6 $request->validate([ 7 'title' => 'required|max:50', 8 'body' => 'required|max:2000', 9 'image'=>'image|mimes:jpg,jpeg,png|max:5000', 10 ]); 11 12 $file = null; 13 $fileName = ''; 14 15 if($request->file('image') != null){ 16 17 $file=$request->file('image'); 18 $fileName=str_random(20).'.'.$file->getClientOriginalExtension(); 19 Image::make($file)->save(public_path('images/'.$fileName)); 20 } 21 22 $post=new Post; 23 $post->title=$request->title; 24 $post->body=$request->body; 25 $post->image=$fileName; 26 unset($post['_token']); 27 $post->save(); 28 29 return redirect()->route('top'); 30 } 31...
失敗するupdateメソッド
PostsContlroller.php
1 public function update($post_id, Request $request) 2 { 3 // dd($request); 4 // バリデート 5 $request->validate([ 6 'title' => 'required|max:50', 7 'body' => 'required|max:2000', 8 'image'=>'image|mimes:jpg,jpeg,png|max:5000', 9 ]); 10 11 dd($request); 12 13 $post = Post::findOrFail($post_id); 14 15 $oldImage = $post->image; 16 17 // dd($oldImage); 18 // \Debugbar::info($oldImage); 19 20 $file = null; 21 $fileName = ''; 22 23 if($request->file('image') != null){ 24 25 $file=$request->file('image'); 26 $fileName=str_random(20).'.'.$file->getClientOriginalExtension(); 27 Image::make($file)->save(public_path('images/'.$fileName)); 28 } 29 30 $post->title=$request->title; 31 $post->body=$request->body; 32 $post->image=$fileName; 33 unset($post['_token']); 34 $post->save(); 35 36 \File::delete(public_path('images/'.$oldImage)); 37 38 return redirect()->route('posts.show', ['post' => $post]); 39 }
なぜ同じバリデーションなのに通過できないのでしょうか?
追記
route/web.php
route/web.php
1<?php 2 3/* 4|-------------------------------------------------------------------------- 5| Web Routes 6|-------------------------------------------------------------------------- 7| 8| Here is where you can register web routes for your application. These 9| routes are loaded by the RouteServiceProvider within a group which 10| contains the "web" middleware group. Now create something great! 11| 12*/ 13Route::get('/', 'PostsController@index')->name('top'); 14Route::resource('comments', 'CommentsController', ['only' => ['store']]); 15Route::resource('posts', 'PostsController', ['only' => ['create', 'store', 'show', 'edit', 'update', 'destroy']]); 16
回答1件
あなたの回答
tips
プレビュー