Laravel 変数の受け渡し
解決したいこと
Laravelにてツイッターの模擬サイトをつくろうとしています。
その中でお気に入り機能を追加したいのですが、うまくいかないのでご教授いただきたいです。
具体的な内容は下記の通りです。
やりたいこととしては
1.User.phpでfeed_favoriteMicroposts()を定義。
2.MicropostsControllerのfavoriteIndex()を用いて変数をnavtabs.blade.phpへ
3.navtabs.blade.php⇨favorites.blade.php⇨favoriteUsers.blade.phpへ
発生している問題・エラー
Undefined variable: favoritePosts (View: /home/ubuntu/environment/microposts/resources/views/users/favorites.blade.php)
User.php
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* このユーザが所有する投稿。( Micropostモデルとの関係を定義)
*/
public function microposts()
{
return $this->hasMany(Micropost::class);
}
/**
* このユーザに関係するモデルの件数をロードする。
*/
public function loadRelationshipCounts()
{
$this->loadCount(['microposts', 'followings', 'followers','favorites']);
}
/**
* このユーザがフォロー中のユーザ。( Userモデルとの関係を定義)
*/
public function followings()
{
return $this->belongsToMany(User::class, 'user_follow', 'user_id', 'follow_id')->withTimestamps();
}
/**
* このユーザをフォロー中のユーザ。( Userモデルとの関係を定義)
*/
public function followers()
{
return $this->belongsToMany(User::class, 'user_follow', 'follow_id', 'user_id')->withTimestamps();
}
/**
* $userIdで指定されたユーザをフォローする。
*
* @param int $userId
* @return bool
*/
public function follow($userId)
{
// すでにフォローしているかの確認
$exist = $this->is_following($userId);
// 相手が自分自身かどうかの確認
$its_me = $this->id == $userId;
if ($exist || $its_me) {
// すでにフォローしていれば何もしない
return false;
} else {
// 未フォローであればフォローする
$this->followings()->attach($userId);
return true;
}
}
/**
* $userIdで指定されたユーザをアンフォローする。
*
* @param int $userId
* @return bool
*/
public function unfollow($userId)
{
// すでにフォローしているかの確認
$exist = $this->is_following($userId);
// 相手が自分自身かどうかの確認
$its_me = $this->id == $userId;
if ($exist && !$its_me) {
// すでにフォローしていればフォローを外す
$this->followings()->detach($userId);
return true;
} else {
// 未フォローであれば何もしない
return false;
}
}
/**
* 指定された $userIdのユーザをこのユーザがフォロー中であるか調べる。フォロー中ならtrueを返す。
*
* @param int $userId
* @return bool
*/
public function is_following($userId)
{
// フォロー中ユーザの中に $userIdのものが存在するか
return $this->followings()->where('follow_id', $userId)->exists();
}
public function feed_microposts()
{
// このユーザがフォロー中のユーザのidを取得して配列にする
$userIds = $this->followings()->pluck('users.id')->toArray();
// このユーザのidもその配列に追加
$userIds[] = $this->id;
// それらのユーザが所有する投稿に絞り込む
return Micropost::whereIn('user_id', $userIds);
}
/**
* このユーザがお気に入りの投稿。( Userモデルとの関係を定義)
*/
public function favorites()
{
// 第一引数:得られるmodelクラス、第二引数:中間テーブル、第三引数:自分のidを示すカラム、第四引数:相手のidを示すカラム
return $this->belongsToMany(Micropost::class, 'favorite', 'user_id', 'micropost_id')->withTimestamps();
}
public function favorite($userId)
{
// すでにフォローしているかの確認
$exist = $this->is_favorite($userId);
// 相手が自分自身かどうかの確認
$its_me = $this->id == $userId;
if ($exist || $its_me) {
// すでにフォローしていれば何もしない
return false;
} else {
// 未フォローであればフォローする
$this->favorites()->attach($userId);
return true;
}
}
public function unfavorite($userId)
{
// すでにフォローしているかの確認
$exist = $this->is_favorite($userId);
// 相手が自分自身かどうかの確認
$its_me = $this->id == $userId;
if ($exist && !$its_me) {
// すでにフォローしていればフォローを外す
$this->favorites()->detach($userId);
return true;
} else {
// 未フォローであれば何もしない
return false;
}
}
public function is_favorite($userId)
{
// フォロー中ユーザの中に $userIdのものが存在するか
return $this->favorites()->where('micropost_id', $userId)->exists();
}
public function feed_favoriteMicroposts()
{
// favoriteテーブに記録されているuser_idを取得
$userIds = $this->favorites()->pluck('favorite.user_id')->toArray();
// Micropostテーブルのデータのうち、$userIDs配列のいずれかと合致するuser_idをもつものを返す。
return Micropost::whereIn('user_id', $userIds);
// favoriteテーブに記録されているmicropost_idを取得
$postIds = $this->favorites()->pluck('favorite.micropost_id')->toArray();
// Micropostテーブルのデータのうち、$postIds配列のいずれかと合致するidをもつものを返す。
return Micropost::whereIn('id', $postIds);
}
}
MicropostsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MicropostsController extends Controller
{
〜省略〜
public function favorite_users()
{
// 第一引数:得られるmodelクラス、第二引数:中間テーブル、第三引数:自分のidを示すカラム、第四引数:相手のidを示すカラム
return $this->belongsToMany(User::class, 'favorite', 'micropost_id', 'user_id' )->withTimestamps();
}
public function favoriteIndex()
{
$data = [];
if (\Auth::check()) { // 認証済みの場合
// 認証済みユーザを取得
$user = \Auth::user();
// お気に入り投稿の一覧を作成日時の降順で取得
$favoritePosts = $user->feed_favoriteMicroposts()->orderBy('created_at', 'desc')->paginate(10);
$data = [
'user' => $user,
'favoritePosts' => $favoritePosts,
];
}
// Welcomeビューでそれらを表示
return view('users.navtabs', $data);
}
}
navtabs.blade.php
<ul class="nav nav-tabs nav-justified mb-3">
{{-- ユーザ詳細タブ --}}
<li class="nav-item">
<a href="{{ route('users.show', ['user' => $user->id]) }}" class="nav-link {{ Request::routeIs('users.show') ? 'active' : '' }}">
TimeLine
<span class="badge badge-secondary">{{ $user->microposts_count }}</span>
</a>
</li>
{{-- フォロー一覧タブ --}}
<li class="nav-item">
<a href="{{ route('users.followings', ['id' => $user->id]) }}" class="nav-link {{ Request::routeIs('users.followings') ? 'active' : '' }}">
Followings
<span class="badge badge-secondary">{{ $user->followings_count }}</span>
</a>
</li>
{{-- フォロワー一覧タブ --}}
<li class="nav-item">
<a href="{{ route('users.followers', ['id' => $user->id]) }}" class="nav-link {{ Request::routeIs('users.followers') ? 'active' : '' }}">
Followers
<span class="badge badge-secondary">{{ $user->followers_count }}</span>
</a>
</li>
{{-- お気に入り一覧タブ --}}
<li class="nav-item">
<a href="{{ route('users.favorites', ['id' => $user->id]) }}" class="nav-link {{ Request::routeIs('users.favorites') ? 'active' : '' }}">
Favorite
<span class="badge badge-secondary">{{ $user->favorites_count }}</span>
</a>
</li>
</ul>
favorites.blade.php
@extends('layouts.app')
@section('content')
<div class="row">
<aside class="col-sm-4">
{{-- ユーザ情報 --}}
@include('users.card')
</aside>
<div class="col-sm-8">
{{-- タブ --}}
@include('users.navtabs')
{{-- お気に入り一覧 --}}
@include('users.favoriteUsers')
</div>
</div>
@endsection
favoriteUsers.blade.php
@if (count($favoritePosts) > 0)
<ul class="list-unstyled">
@foreach ($favoritePosts as $favoritePost)
<li class="media">
<div class="media-body">
<div>
{{-- 投稿の所有者のユーザ詳細ページへのリンク --}}
{!! link_to_route('users.show', $favoritePost->user->name, ['user' => $favoritePosts->user->id]) !!}
<span class="text-muted">posted at {{ $favoritePosts->created_at }}</span>
</div>
<div>
{{-- ユーザ詳細ページへのリンク --}}
<p>{!! link_to_route('users.show', 'View profile', ['user' => $user->id]) !!}</p>
</div>
</div>
</li>
@endforeach
</ul>
{{-- ページネーションのリンク --}}
{{ $users->links() }}
@endif
自分で試したこと
エラー内容がfavoritePostsが未定義とのことだったので、値の受け渡し方について試行錯誤したのですが、どこで問題が発生しているのか特定できません。