I have got these three models with relations:
class Comment
class Comment extends Eloquente {
use UserTrait, RemindableTrait;
protected $table = 'comments';
public function user()
{
return $this->belongsTo ('User');
}
public function post()
{
return $this->belongsTo('Post');
}
}
class User
class User extends Eloquent {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public function post()
{
return $this->hasMany('Post');
}
public function comment()
{
return $this->hasMany('Comment');
}
}
class Post
class Post extends Eloquent {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'posts';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public function comment()
{
return $this->hasMany('Comment');
}
public function user()
{
return $this->belongsTo('User');
}
}
In controller Simply
return View::make('viewfile',['feed'=> Post::all()]);
view file:
@foreach($feed as $post)
@foreach($post->comment as $comment)
{{$comment->user->username}}
@endforeach
@endforeach
In view file it returns that is undefined property if var_dump() ;
return only true but if I put this foreach
loops in controller function and return value $comment->user->username
, it return name of user so my question is what should I do to be able to use this property in view file
Controller
<?php
class BoardController extends \BaseController {
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
if(Auth::check())
{
$followers_count = sizeof(unserialize(Auth::user()->Followers));
$following_count = sizeof(unserialize(Auth::user()->Following));
$following_groups_count = sizeof(unserialize(Auth::user()->GroupsFollowing));
$feed = Post::all();
foreach ($feed as $post) {
foreach($post->comment as $comment)
{
return $comment->user->username;
}
}
/*
return View::make('board.index',[
'FollowersCount' => $followers_count,
'FollowingCount' => $following_count,
'FollowingGroupsCount' => $following_groups_count,
'feed' => $feed,
'nick' => Auth::user()->username
]);
*/
}
else
{
Redirect::to('/login');
}
}
}
try to create dataCollection using function collect($yourArray) then send to view with "with" function
i didnt using hasOne or anything, i'm using model::find($id) to search the same id
example: $dataCollection = collect($array1);
that function is used to match the default format of laravel
btw i'm using laravel 5.4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.