[英]Laravel 8 - can't get data from database
我想从名为 follower_id 的数据库中获取数据,但是当我尝试获取数据时出现错误。 当我尝试使用 foreach 时,我返回 null 我正在使用具有关系的数据库,如果我输入{{$follows}}
,我可以获得数据。 另一方面,如果我输入{{$follows->follower_id}}
我得到这个错误:
此集合实例上不存在属性 [follower_id]。
那么我该如何解决这个问题呢? 顺便说一下,我是 Laravel 和数据库关系的初学者。
我的 controller 是:
public function getProfile($username){
$follow = Follow::all();
$user = User::where('username', $username)->first();
if(isset($user)){
return view('design2.profile', ['user'=>$user,'follow'=>$follow]);
}else{
return redirect()->route('home');
}
}
我的刀片是:
<h6><span class="text-secondary"><strong>{{$follow->follower_id}} follower</strong></span></h6>
我关注 model:
public $table = "follow";
protected $fillable = [
'follower_id',
'user_id',
];
public function user(){
return $this->belongsTo('App\Models\User');
}
我的用户 model:
protected $fillable = [
'name',
'email',
'username',
'password',
'info',
'twitter_name',
'instagram_name',
'photo'
];
public function follows(){
return $this->hasMany('App\Models\Follow');
}
您需要的是获得用户的所有关注者。 让我为您编写代码,以便您拥有比现在更标准的代码。
在你用户 Model
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The followers that belong to the User
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function followers()
{
return $this->belongsToMany(User::class, 'follow', 'user_id', 'follower_id');
}
}
在您的 controller 中。
/**
* Gets the user with all his followers.
*
* @param string $username
* @return \Illuminate\Http\Response
*/
public function getProfile($username){
$user = User::with('followers')->where('username', $username)->firstOrFail();
return view('design2.profile', [
'user' => $user,
]);
}
在你的刀片中。
@foreach($user->followers as $follower)
<h6>
<span class="text-secondary">
<strong>{{$follower->name}}</strong>
</span>
</h6>
@foreach
仅此而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.