LoginSignup
0
0

More than 3 years have passed since last update.

laravel 簡単な画像アップロードの方法

Last updated at Posted at 2020-07-17

laravelで掲示板の機能の一つとして画像をアップロードする機能を実践してみます。

・Laravel 7.1
・PHP7.3

テーブルを作る

~~~post.table.php
public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigincrements('id');
            $table->string('title');
            $table->text('body');
            $table->string('path');
            $table->timestamps();
        });
    }

タイトル、内容、画像のpathを保存するためのカラムを追加します。

form

PostController.php
{{ Form::open(['action' => 'PostController@index', 'method' => 'post' , 'enctype' => 'multipart/form-data']) }}
        <p>タイトル<br/>{{ Form::text('title', '', ['id' => 'title', 'size' => 50]) }}</p>
        <p>内容<br/>{{ Form::textarea('body', '', ['id' => 'body', 'size' => '50x3']) }}</p>
        {{ Form::file('path') }}
        <div>
            {{ Form::submit('投稿', ['class' => 'btn btn-success btn-lg']) }}
        </div>
{{ Form::close() }}

タイトル、内容、画像選択のformを作りました。

formタグに enctype='multipart/form-data' を忘れずn記述しましょう。これは、複合データ型であることを示し、1回のHTTP通信で、複数の種類のデータ形式を扱う事でできるようになります。

Route

route.php
Route::resource('/post', 'PostController');

controller

PostController.php
public function index()
    {
        $items = Post::all();
        return view('post.index', ['items' => $items]);
        // DBから取得した値($itemの内容)をpost.indexに渡してblade側で使用
    }

public function store(PostRequest $request)
    {
        $post = new Post;

        $post->title = $request->title;
        $post->body = $request->body;
        if ($request->file('path')->isValid()) {
                                                //publicに保存、ファイル名指定
            $image_path = $request->path->store('public/post_image');
            $post->path = basename($image_path);

        }
        //DB書き込み
        $post->save();
        return redirect('/post')->with('success', '投稿しました!');
    }

storeメソッドには、保存したいパス(ディレクトリ)を指定します。
(任意のファイル名を指定したい場合はstoreAsメソッドを使用)

public/post_imageと画像ファイルの保存場所を指定します。
ファイルが保存されつ場所は、storage/app/public/post_imageディレクトリに保存されます。

basename()を使用して、画像名のみ保存します。

viewで表示する際にはasset()を使用して、<img src="{{ asset('storage/post_image/' . $item->path) }}">と指定します。

シンボリックリンクを張る

最後にシンボリックリンクを張りましょう。

php artisan storage:link

リンクが貼られていれば、 public/storageの右上に矢印が表示されます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0