Q&A
実現したいこと
ブログサイトのフォロー機能の作成中にエラーが起きたのでそれの解決。
前提
PHP Laravelでブログサイトのフォロー機能を作っていました。
その際、エラーが出てしまったのでそれの解決方法が知りたい。
発生している問題・エラーメッセージ
index.blade.php11行目
Call to a member function isFollowing() on null
該当のソースコード
index.blade.php
php
1@extends('layouts.logged_in') 2 3@section('content') 4 <h1>{{ $title }}</h1> 5 <a href="{{route('posts.create')}}">新規投稿</a> 6 7 <ul class="recommend_users"> 8 @forelse($recommended_users as $recommended_user) 9 <li> 10 <a href="{{ route('users.show', $recommended_user) }}">{{ $recommended_user->name }}</a> 11 @if(Auth::user()->isFollowing($recommended_user)) 12 <form method="post" action="{{route('follows.destroy', $recommended_user)}}" class="follow"> 13 @csrf 14 @method('delete') 15 <input type="submit" value="フォロー解除"> 16 </form> 17 @else 18 <form method="post" action="{{route('follows.store')}}" class="follow"> 19 @csrf 20 <input type="hidden" name="follow_id" value="{{ $recommended_user->id }}"> 21 <input type="submit" value="フォロー"> 22 </form> 23 @endif 24 </li> 25 @empty 26 <li>おすすめユーザーはいません。</li> 27 @endforelse 28 </ul> 29 30 <ul> 31 @forelse($user->posts as $post) 32 <li> 33 {{ $post->user->name }}: 34 {!! nl2br($post->comment) !!}<br> 35 ({{ $post->created_at }}) 36 @if($user->isEditable($post)) 37 [<a href="{{ route('posts.edit', $post) }}">編集</a>] 38 @endif 39 <form action="{{ url('posts/'.$post->id) }}" method="post"> 40 @csrf 41 @method('delete') 42 <button type="submit">削除</button> 43 </form> 44 </li> 45 @empty 46 <li>投稿はありません。</li> 47 @endforelse 48 </ul> 49@endsection
User.php
php
1<?php 2 3namespace App; 4 5use Illuminate\Contracts\Auth\MustVerifyEmail; 6use Illuminate\Foundation\Auth\User as Authenticatable; 7use Illuminate\Notifications\Notifiable; 8use Illuminate\Database\Eloquent\Model; 9use App\Follow; 10 11class User extends Model 12{ 13 protected $fillable = ['name','email', 'password', 'description', 'profile', 'admin']; 14 15 public function posts(){ 16 return $this->hasMany('App\Post')->latest(); 17 } 18 19 public function isEditable($post){ 20 return $this->isAdmin() || $this->id === $post->user->id; 21 } 22 23 public function scopeRecommend($query, $self_id){ 24 return $query->where('id', '!=', $self_id)->latest()->limit(3); 25 } 26 27 public function isAdmin(){ 28 return $this->admin === 1; 29 } 30 31 public function follows(){ 32 return $this->hasMany('App\Follow'); 33 } 34 35 public function follow_users(){ 36 return $this->belongsToMany('App\User', 'follows', 'user_id', 'follow_id'); 37 } 38 39 public function followers(){ 40 return $this->belongsToMany('App\User', 'follows', 'follow_id', 'user_id'); 41 } 42 43 public function isFollowing($user){ 44 $result = $this->follow_users->pluck('id')->contains($user->id); 45 return $result; 46 } 47}
試したこと
調べてみたが解決の糸口にはならなかった。
補足情報(FW/ツールのバージョンなど)
よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
退会済みユーザー
2023/03/21 01:14
2023/03/21 02:09
退会済みユーザー
2023/03/21 02:11