質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Docker

Dockerは、Docker社が開発したオープンソースのコンテナー管理ソフトウェアの1つです

Blade

Bladeとは、 PHPフレームワークのLaravelで使用することができるテンプレートエンジンです。テンプレートの継承とエスケープ機能を提供します。

Q&A

解決済

2回答

4933閲覧

Laravel Undefined variable:posts エラーの改善方法

neomana-39

総合スコア11

Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Docker

Dockerは、Docker社が開発したオープンソースのコンテナー管理ソフトウェアの1つです

Blade

Bladeとは、 PHPフレームワークのLaravelで使用することができるテンプレートエンジンです。テンプレートの継承とエスケープ機能を提供します。

0グッド

0クリップ

投稿2020/02/26 10:01

編集2020/02/26 11:21

前提・実現したいこと

前提
Laravel6.0で画像投稿機能付きの簡単なWebアプリを制作しています。
写真投稿機能を2つ(アカウントのプロファイール画像用、タイムラインの画像用)作成しています。

実現したいこと

複数のページ(プロフィール画像投稿用ページ、タイムライン画像投稿用ページ)から投稿した写真を一つのメインページ(該当のソースコード)に表示したいです。

発生している問題・エラーメッセージ

Undefined variable: posts (View: /work/resources/views/stories/index2.blade.php)

該当のソースコード

ここに画像を表示したい。(始めの項目のメインページに該当するページ)

resources/views/stories/index2.blde.php

php

1@extends('layouts.front2') 2@section('title','mainpage') 3 4@section('content') 5<div class="profile"> 6 7 <div class="profileimg"> 8 @foreach ($posts as $post) 9 <img src="/storage/{{ $post->path . $post->name }}" style="height: 210px; width: 210px; border-radius: 50%;"> 10 @endforeach 11 </div> 12 13 <div class="name"> 14 @guest 15 <a class="nav-link2" href="{{ route('register')}}">{{ __('Create Accout!')}}</a> 16 @else 17 <a id="navbarDropdown" class="nav-link2" href="#" role="button"> 18 {{Auth::user()->name}}<span class="caret"></span></a> 19 20 21 22 <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> 23 @csrf 24 </form> 25 </div> 26 @endguest 27 28 29 <div class="aboutme"> 30 You can write your profile here!You can write your profile here!You can write your profile here! 31 You can write your profile here!You can write your profile here!You can write your profile here! 32 You can write your profile here!You can write your profile here!You can write your profile here! 33 You can write your profile here!You can write your profile here!You can write your profile here! 34 You can write your profile here!You can write your profile here!You can write your profile here! 35 </div> 36 37</div> 38 39<div class="new"> 40 41 <div class="newtitle"> 42 <h1>New</h1> 43 </div> 44 45 <div class="container1"> 46 47 @foreach ($images as $image) 48 <img src="/storage/{{ $image->path . $image->name }}" class="images" style="height: 150px; width: 150px; border-radius: 50%;"> 49 @endforeach 50 <div class="more"> 51 more... 52 </div> 53 </div> 54 55</div> 56 57<div class="stories"> 58 59 <div class="titlestories"> 60 <h1>Stories</h1> 61 </div> 62 63 <div class="container2"> 64 65 <div class="titleclose"> 66 <h2>#CloseFriends</h2> 67 </div> 68 69 @foreach ($images as $image) 70 <img src="/storage/{{ $image->path . $image->name }}" class="images" style="height: 150px; width: 150px; border-radius: 50%;"> 71 @endforeach 72 73 <div class="titlefollow"> 74 <h2>#Follows</h2> 75 </div> 76 77 @foreach ($images as $image) 78 <img src="/storage/{{ $image->path . $image->name }}" class="posts" style="height: 150px; width: 150px; border-radius: 50%;"> 79 @endforeach 80 81 82 83 84 </div> 85</div> 86 87{{ csrf_field() }} 88@endsection

上から6行目の

php

1@foreach($posts as $post) 2~() 3@endforeach

の部分に問題があると指摘されました。

試したこと

下から7行目の

php

1@foreach($images as $image) 2~() 3@endforeach

部分は理想通り実装されているので、$images(タイムラインの画像)のControllerと投稿用ページのbladeエンジンを問題のある$postsのControllerとbladeエンジンを見比べました。

補足情報(FW/ツールのバージョンなど)

画像を投稿するファーム

resources/views/profile/create2.blade.php

blade

1@extends('layouts.front2') 2@section('title','createprofile') 3 4@section('content') 5 6 7<link rel="stylesheet" href="{{ asset('css/main21.css') }}"> 8 9<div class="title1"> 10 <h1>Create Account</h1> 11</div> 12 13<div class="user-details"> 14 15 <div class="form1"> 16 <label class="h1">FirstName</label> 17 <div class="t1"> 18 <input type="text" class="form" name="firstname" value="{{ old('title') }}"> 19 </div> 20 </div> 21 22 <div class="form1"> 23 <label class="h1">FamilyName</label> 24 <div class="t2"> 25 <input type="text" class="form" name="familyname" value="{{ old('title') }}"> 26 </div> 27 </div> 28 29 <div class="form1"> 30 <label class="h1">UserName</label> 31 <div class="t3"> 32 <input type="text" class="form" name="username" value="{{ old('title') }}"> 33 </div> 34 </div> 35 36 <div class="form1"> 37 <label class="h1">E-Mail Address</label> 38 <div class="t4"> 39 <input type="text" class="form" name="e-mail" value="{{ old('title') }}"> 40 </div> 41 </div> 42 43@if ($errors->any()) 44<ul> 45 @foreach($errors->all() as $error) 46 <li>{{ $error }}</li> 47 @endforeach 48</ul> 49@endif 50<form action="{{ url('/') }}" method="POST" enctype="multipart/form-data"> 51 <input type="file" class="here" name="posts[]"> 52 <input type="submit" value="post"> 53 54 55 56 <div class="create"> 57 <div class="btn createbtn"> 58 <h2>Create!</h2> 59 </div> 60 </div> 61 62</div> 63 64 @endsection

routes/web.php

route

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*/ 13 14Route::get('login'); 15 16Route::group(['middleweare' => 'auth'], function () { 17 Route::get('/', 'StoriesController@index'); 18 Route::post('/stories/create', 'StoriesController@store'); 19 Route::get('/stories/create', 'StoriesController@add'); 20 Route::post('/stories/create', 'StoriesController@upload'); 21}); 22 23Route::group(['middleweare' => 'auth'], function () { 24 Route::get('/profile/edit', 'ProfileController@edit'); 25 Route::post('/profile/create', 'ProfileController@add'); 26 Route::get('/profile/create', 'ProfileController@add'); 27 Route::post('/profile/create', 'ProfileController@store'); 28 Route::post('/profile/create', 'ProfileController@upload'); 29}); 30 31Route::get('/home', 'HomeController@index')->name('home'); 32 33Auth::routes(); 34

app/Http/Controllers/ProfileController.php

controller

1<?php 2 3namespace App\Http\Controllers; 4 5use Illuminate\Http\Request; 6use App\Http\Controllers\Controller; 7 8use App\stories; 9use App\History; 10use App\Post; 11use Carbon\Carbon; 12use Storage; 13 14class ProfileController extends Controller 15{ 16 public function index(Request $request) 17 { 18 $posts = Post::all(); 19 20 return view('stories.index2', compact('posts')); 21 } 22 23 public function upload(Request $request) 24 { 25 $this->validate($request, [ 26 'file' => [ 27 // 必須 28 'required', 29 // アップロードされたファイルであること 30 'file', 31 // 画像ファイルであること 32 'image', 33 // MIMEタイプを指定 34 'mimes:jpeg,png', 35 ] 36 ]); 37 38 if ($request->file('file')->isValid([])) { 39 $path = $request->file->store('public'); 40 return view('stories.create2')->with('filename', basename($path)); 41 } else { 42 return redirect() 43 ->back() 44 ->withInput(); 45 // withErrors(); 46 } 47 } 48 49 public function store(Request $request) 50 { 51 52 $d = new \DateTime(); 53 $d->setTimeZone(new \DateTimeZone('Asia/Tokyo')); 54 $dir = $d->format('Y/m'); 55 $path = sprintf('public/posts/%s', $dir); 56 57 // postデータ取得 58 $data = $request->except('_token'); 59 60 foreach ($data['posts'] as $k => $v) { 61 62 $filename = ''; 63 64 //ID降順の1行だけ取得 65 $posts = Post::take(1)->orderBy('id', 'desc')->get(); 66 67 foreach ($posts as $post) { 68 //ファイル名 69 $filename = $post->id + 1 . '_' . $v->getClientOriginalName(); 70 } 71 unset($post); 72 73 //データベースが空の場合ファイル名が設定されない 74 if ($filename == false) { 75 $filename = 1 . '_' . $v->getClientOriginalName(); 76 } 77 78 //画像の保存 79 $v->storeAs($path, $filename); 80 81 $post_data = [ 82 'path' => sprintf('posts/%s/', $dir), 83 'name' => $filename 84 ]; 85 $a = new Post(); 86 $a->fill($post_data)->save(); 87 } 88 89 unset($k, $v); 90 91 return redirect('/'); 92 } 93 94 public function create(Request $request) 95 { 96 $this->validate($request, Profile::$rules); 97 98 $profile = new Profile; 99 $form = $request->all(); 100 101 102 unset($form['_token']); 103 104 $profile->fill($form); 105 $profile->save(); 106 107 return redirect('/'); 108 } 109 110 public function add() 111 { 112 return view('profile.create2'); 113 } 114 115 public function edit() 116 { 117 return view('profile.edit'); 118 } 119 120 121 122 123 124 125} 126

まだプログラミング初学者で説明不足や言葉足らずな箇所があるかもしれませんが、力を貸していただけたら幸いです。
不足事項などございましたら即座に対応させていただきます。

よろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

m.ts10806

2020/02/26 10:04

index()以外でpostsはviewに渡されていないようですが
退会済みユーザー

退会済みユーザー

2020/02/26 10:25

コードがそれぞれどのファイルなのか書いてないから読み解くのが面倒です
neomana-39

2020/02/26 11:15

@m.ts10806 もう一度確認してみます
neomana-39

2020/02/26 11:21

@Kosuke_Shibuya 大変失礼いたしました。 修正いたしました。
guest

回答2

0

ベストアンサー

Routeに書いているコントローラーがStoriesControllerです。

今編集されているのが、別のコントローラーなので、StoriesControllerのindexメソッドに変数postsがないのだと思います。

ちなみにcompact関数は使えるので問題ないと思います。

投稿2020/02/26 10:33

hayato7

総合スコア1135

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

neomana-39

2020/02/27 05:09

指摘していただいた通り、StoriesControllerに変数postsを記述することにより解決致しました。ありがとうございました。
guest

0

php

1return view('stories.index2', compact('posts'));

の部分

php

1return view('stories.index2', ['posts' => $posts]);

こうでは

投稿2020/02/26 10:12

sola-msr

総合スコア876

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2020/02/26 10:28

どちらも同じ意味です
sola-msr

2020/02/26 10:35

おお勉強になります php.net/manual/ja/function.compact.php > 各引数について、compact() は現在のシンボルテーブルにおいてその名前を有する変数を探し、 変数名がキー、変数の値がそのキーに関する値となるように追加します。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問