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

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

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

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

PHP

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

Q&A

2回答

3054閲覧

PHP must be a valid array offset typeと表示された原因を教えてください

kpby2751

総合スコア19

Laravel

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

PHP

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

0グッド

0クリップ

投稿2022/11/08 02:40

編集2022/11/08 06:40

前提

PHP Laravelを使用。
フォロー一覧ページを作っているところです。フォローしたユーザーをprofile/myfollowに表示し、そこに表示されたユーザーをクリックするとそのユーザーのプロフィールに飛べるようにしたいです。ProfileController.phpで全フォローを$followingsと定義し、profile/myfollowでforeachで各フォローユーザーごとに表示しようと思います。しかしfollowingsの定義で配列に誤りがあるのか以下のエラーメッセージが出ます。

実現したいこと

エラーメッセージが表示される原因を教えてください。a valid array offset typeとはどこのことを指しているのでしょうか。

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

array_key_exists(): Argument #1 ($key) must be a valid array offset type

該当のソースコード

follow.php

1<?php 2 3namespace App\Models; 4 5use Illuminate\Database\Eloquent\Factories\HasFactory; 6use Illuminate\Database\Eloquent\Model; 7 8 9class Follower extends Model 10{ 11 use HasFactory; 12 13 protected $primaryKey = [ 14 'following_id', 15 'followed_id' 16 ]; 17 protected $fillable = [ 18 'following_id', 19 'followed_id' 20 ]; 21 public $timestamps = false; 22 public $incrementing = false; 23}

User.php

1<?php 2 3namespace App\Models; 4 5// use Illuminate\Contracts\Auth\MustVerifyEmail; 6use Illuminate\Database\Eloquent\Factories\HasFactory; 7use Illuminate\Foundation\Auth\User as Authenticatable; 8use Illuminate\Notifications\Notifiable; 9use Laravel\Sanctum\HasApiTokens; 10 11class User extends Authenticatable 12{ 13 use HasApiTokens, HasFactory, Notifiable; 14 15 /** 16 * The attributes that are mass assignable. 17 * 18 * @var array<int, string> 19 */ 20 protected $fillable = [ 21 'name', 22 'avatar', 23 'email', 24 'password', 25 'message', 26 'url' 27 ]; 28 29 /** 30 * The attributes that should be hidden for serialization. 31 * 32 * @var array<int, string> 33 */ 34 protected $hidden = [ 35 'password', 36 'remember_token', 37 ]; 38 39 /** 40 * The attributes that should be cast. 41 * 42 * @var array<string, string> 43 */ 44 protected $casts = [ 45 'email_verified_at' => 'datetime', 46 ]; 47 48 public function posts() { 49 return $this->hasMany(Posts::class); 50 } 51 public function comments() { 52 return $this->hasMany(Commentart::class); 53 } 54 public function roles() { 55 return $this->belongsToMany(Role::class); 56 } 57 public function nices() { 58 return $this->hasMany(Nice::class); 59 } 60 public function followers() 61 { 62 return $this->belongsToMany(User::class, 'followers', 'followed_id', 'following_id'); 63 } 64 public function follows() 65 { 66 return $this->belongsToMany(User::class, 'followers', 'following_id', 'followed_id'); 67 } 68}
<?php namespace App\Http\Controllers; use App\Models\User; use App\Models\Role; use App\Models\Follower; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\Rule; use Illuminate\Support\Facades\Storage; use Illuminate\Pagination\Paginator; class ProfileController extends Controller { public function followings(User $user) { $follower = auth()->user(); $followings = Follower::where('following_id', $follower->id)->get(); return view('profile.myfollow', compact('followings')); } }

試したこと

取り敢えず試しにwhereではなく、findとしてみたら

str_contains(): Argument #1 ($haystack) must be of type string, array given

となりました。全く関係なかったみたいです。

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

migrations\Y_m_d_t_create_followers_table.php

1<?php 2 3use Illuminate\Database\Migrations\Migration; 4use Illuminate\Database\Schema\Blueprint; 5use Illuminate\Support\Facades\Schema; 6 7return new class extends Migration 8{ 9 /** 10 * Run the migrations. 11 * 12 * @return void 13 */ 14 public function up() 15 { 16 Schema::create('followers', function (Blueprint $table) { 17 $table->unsignedInteger('following_id')->comment('フォローしているユーザID'); 18 $table->unsignedInteger('followed_id')->comment('フォローされているユーザID'); 19 20 $table->index('following_id'); 21 $table->index('followed_id'); 22 23 $table->unique([ 24 'following_id', 25 'followed_id' 26 ]); 27 }); 28 } 29 30 /** 31 * Reverse the migrations. 32 * 33 * @return void 34 */ 35 public function down() 36 { 37 Schema::dropIfExists('followers'); 38 } 39};

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

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

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

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

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

guest

回答2

0

これで良くない?
なんのためにリレーション設定してるの?

php

1class ProfileController extends Controller 2{ 3 public function followings(User $user) 4 { 5 $followings = $user->follows; 6 7 return view('profile.myfollow', compact('followings')); 8 } 9}

投稿2022/11/08 06:09

phper.k

総合スコア3923

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

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

kpby2751

2022/11/08 06:36

回答ありがとうございます。そのまま書くとエラーメッセージ Method Illuminate\Database\Eloquent\Collection::links does not exist. が出てしまうのですが、どうしたら良いのでしょうか。 followersテーブルに'following_id'と'followed_id'カラムがあるのですが、 「ログインユーザーidとfollowing_id'が一致→そのidに対応する'followed_id'を全て取得」 を$followingsで定義したいのですが、どのように書けば良いのかよく分かりません。 テーブルの設定等は補足で書いておきます。
phper.k

2022/11/08 06:38

エラーメッセージそこしか見えてないんですかね? その後に、エラーが発生しているファイル名、行数までがエラーです。 そのファイル名部分が見えていれば、きっと blade ファイルも見せないと問題は解決しないと推測できませんか?
kpby2751

2022/11/08 06:49

C:\xampp\htdocs\laravel\techschools\vendor\laravel\framework\src\Illuminate\Macroable\Traits\Macroable .php  : 113 が下記の辺りです。 public function __call($method, $parameters) { if (! static::hasMacro($method)) { throw new BadMethodCallException(sprintf( 'Method %s::%s does not exist.', static::class, $method )); } 何が問題なのでしょうか。bladeファイルは以下の通りです。 <x-app-layout> <x-slot name="header"> <h2 class="font-semibold text-xl text-gray-800 leading-tight"> フォローしたユーザー </h2> <x-message :message="session('message')" /> </x-slot> {{-- 投稿一覧表示用のコード --}} @if ($followings->count() == 0) <p class="mt-4"> まだフォローをしていません。 </p> @else <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> @foreach($followings as $following) <div class="mx-4 sm:p-8"> <div class="mt-4"> <div class="bg-white w-full rounded-2xl px-10 py-8 shadow-lg hover:shadow-2xl transition duration-500"> <div class="mt-4"> <a href="{{route('profile.show',$following)}}"> <div class="flex hover:underline cursor-pointer"> <div class="rounded-full w-12 h-12"> <img src="{{asset('storage/avatar/'.($following->avatar??'user_default.jpg'))}}"> </div> <div class="ml-1">{{ $following->name??'削除されたユーザー' }}</div> </div> </a> </div> </div> </div> </div> @endforeach </div> @endif {{ $followings->links('vendor.pagination.tailwind2') }} </x-app-layout>
phper.k

2022/11/08 06:55 編集

links() メソッドがなんのために存在しているのかは理解してますかね?
kpby2751

2022/11/08 10:32

links()とあることからoffsetしてかつlimitするということでしょうか。そこで $followings = $user->follows()->paginate(5); としてみたところ、bladeファイルは見えました。しかしこれだけではbladeのcount()が機能されていないと思い、 if ($followings->count() == 0) を!=としたりそもそもifを外してみました。app-blade以外は何も表示されていないので、count()==0となっているわけではありません(実際に幾つかフォローしフォローされているので0ではありません)。多分follows()の中の引数を設定したり→に続けて記述したりする必要があるのかもしれません。
phper.k

2022/11/08 23:51

> しかしこれだけではbladeのcount()が機能されていないと思い、 何がどうなっているんでしょう。「機能していないと思い」の意味がわからん
guest

0

単純に評価しようとした変数(?)が配列ではなくオブジェクトかなにかだったからじゃないでしょうか?array_key_existsやstr_containsで評価している部分が欠如しているので提示されたソースではなんともいえません

参考

PHP

1<?PHP 2$a=[]; 3var_dump($a); 4var_dump(array_key_exists("test",$a)); 5$b=json_decode("{}"); 6var_dump($b); 7var_dump(array_key_exists("test",$b));

投稿2022/11/08 03:32

編集2022/11/08 03:34
yambejp

総合スコア114843

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問