LoginSignup
replica410
@replica410 (陽 有村)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Laravelでの画像投稿サイト作成でのバリデーションの設定について

解決したいこと

create.bladeのビューページにて、新規投稿する際の条件として設定しているバリデーションをクリアしているのに、引っかかってエラーメッセージが出てしまい投稿できない問題を解決したい。

発生している問題・エラー

The image must 〇〇といういくつかのバリデーションに関するエラーメッセージ

該当するソースコード

web.php(ルーティング)
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();

Route::get('/', function () {
    // return view('welcome');
    return view('top');
});
// 投稿一覧
// Route::get('/posts', 'PostController@index');
// // 投稿追加フォーム
// Route::get('/posts/create', 'PostController@create');
// // 投稿追加
// Route::post('/posts', 'PostController@store');
// // 投稿詳細
// Route::get('/posts/{id}', 'PostController@show');
// // 投稿更新フォーム
// Route::get('/posts/{id}/edit', 'PostController@edit');
// // 投稿更新
// Route::patch('/posts/{id}', 'PostController@update');
// // 投稿削除
// Route::delete('posts', 'PostController@destroy');

// 上記の7つのルーティングを下の一つで同じ効果にできる
// postsに関するリソースルーティングを行い、
// PostControllerの各アクションに紐づける
Route::resource('posts', 'PostController');

Route::resource('likes', 'LikeController')->only([
    'index', 'store', 'destroy'
]);
    
Route::resource('follows', 'FollowController')->only([
    'index', 'store', 'destroy'
]);

Route::get('/folloow', 'FollowController@folloowerIndex');

Route::resource('comments', 'CommentController')->only([
    'store', 'destroy'    
]);
Route::get('/posts/{post}/edit_image', 'PostController@editImage')->name('posts.edit_image');

Route::patch('/posts/{post}/edit_image', 'PostController@updateImage')->name('posts.update_image');

Route::get('/users/{id}/edit', 'UserController@edit')->name('users.edit');
Route::patch('/users/{id}', 'UserController@update')->name('users.update');
Route::get('/users/{id}/edit_image', 'UserController@editImage')->name('users.edit_image');
Route::patch('/users/{id}/edit_image', 'UserController@updateImage')->name('users.update_image');

Route::resource('users', 'UserController')->only([
  'show',
]);
PostController.php(コントローラー)
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use App\User;
use App\Http\Requests\PostRequest;
use App\Http\Requests\PostImageRequest;

class PostController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    
     // 投稿一覧
    public function index()
    {
        // ログインユーザーを取得
        // $user = \Auth::user();
        // ログインユーザーに紐づく投稿一覧を取得
        // $posts = $user->posts;
        // latest は最新のという意味
        $user = \Auth::user();
        return view('posts.index',[
            'title' => '投稿一覧',
            'posts' => $user->posts()->latest()->get(),
            'recommended_users' => User::recommend($user->id)->get()
        ]);
    }

     // 新規投稿フォーム
    public function create()
    {
        return view('posts.create',[
            'title' => '新規投稿'
        ]);
    }

     // 投稿追加処理
    public function store(PostRequest $request)
    {
        //画像投稿処理
        $path = '';
        $image = $request->file('image');
        if( isset($image) === true ){
            // publicディスク(storage/app/public/)のphotosディレクトリに保存
            $path = $image->store('photos', 'public');
        }
        
        //投稿追加処理
        Post::create([
            'user_id' => \Auth::user()->id,
            'comment' => $request->comment,
            'image' => $path, // ファイルパスを保存
        ]);
        session()->flash('success', '投稿を追加しました');
        return redirect()->route('posts.index');
    }

     // 投稿詳細
    public function show($id)
    {
        $post = Post::find($id);
        return view('posts.show',[
            'title' => '投稿詳細',
            'post' => $post,
        ]);
    }
PostRequest.php(フォームリクエスト)
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'comment' => ['required', 'max:200'],
            'image' => [
                'file', // ファイルがアップロードされている
                'image', //画像ファイルである
                'mimes:jpeg,jpg,png', // 形式はjpegかpng
                'dimensions:min_width=50,min_height=50,max_width=1000,max_height=1000', // 50*50 ~ 1000*1000まで
            ],
        ];
    }
}
Post.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function comments(){
        return $this->hasMany('App\Comment');
    }
    
    protected $fillable = ['user_id', 'comment', 'image'];
    
    public function user(){
        return $this->belongsTo('App\User');
    }
    
    public function scopeRecommend($query){
        // ランダムに3つの投稿を取得
        return $query->latest()->limit(3);
    }
}
create.blade.php(新規投稿ページのビュー)
@extends('layouts.logged_in')
 
@section('title', $title)
 
@section('content')
  <h1>{{ $title }}</h1>
  <form method="POST" action="{{ route('posts.store') }}">
      @csrf
      <div>
          <label>
              コメント:
              <input type="text" name="comment">
          </label>
      </div>
      <div>
        <label>
          画像:
          <input type="file" name="image">
        </label>
      </div>
      
        <input type="submit" value="投稿"> 
  </form>
@endsection

自分で試したこと

誤字などの確認、作成手順やバリデーションの見直し

0

1Answer

フォームからファイルをアップロードするときはformタグにenctype="multipart/form-data"が必要です。

<form method="POST" enctype="multipart/form-data">
    <input name="image" type="file" />
</form>

enctype
method 属性の値が post であるとき、この属性はフォームをサーバーに送信する際に使用する、コンテンツの MIME タイプを示します。以下の値が指定可能です。

  • application/x-www-form-urlencoded: 既定値。属性を指定していない場合、この値が使用されます。
  • multipart/form-data: フォームが のtype=fileを含む場合に使用してください。
  • text/plain: HTML5 でデバッグ用に導入されました。

1

Comments

  1. @replica410

    Questioner
    ありがとうございます。そちらを入力したところ、無事バリデーションを通過して更新する事ができました!

Your answer might help someone💌