I want to get data from database that name is follower_id but when I try to get data I get error. And when I try with foreach I'm returning null I'm using database with relationships and I can get data if I type {{$follows}}
. On the other hand, if I type {{$follows->follower_id}}
I get this error:
Property [follower_id] does not exist on this collection instance.
So how can I solve this problem? I'm beginner in Laravel and database relationships by the way.
My controller is:
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');
}
}
My blade is:
<h6><span class="text-secondary"><strong>{{$follow->follower_id}} follower</strong></span></h6>
My follow model:
public $table = "follow";
protected $fillable = [
'follower_id',
'user_id',
];
public function user(){
return $this->belongsTo('App\Models\User');
}
My user model:
protected $fillable = [
'name',
'email',
'username',
'password',
'info',
'twitter_name',
'instagram_name',
'photo'
];
public function follows(){
return $this->hasMany('App\Models\Follow');
}
What you need is to get all the followers of a user. Let me do the coding for you so that you have a somewhat more standard code than you have now.
In you User 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');
}
}
In your 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,
]);
}
In your blade.
@foreach($user->followers as $follower)
<h6>
<span class="text-secondary">
<strong>{{$follower->name}}</strong>
</span>
</h6>
@foreach
And that is all.
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.