Access followers data Laravel 5.8 and Eloquent - laravel

I have a base table setup for followers and the Follower model has the relationship belongsTo with User model. User model has the relationship belongsToMany with the Follower model. The followers table has "id, follower_id, leader_id"
I'm trying to access the followers table through the User model but it won't let me do it. I must be doing something wrong, but I have worked with Eloquent relationships before and I have always had it working then. Can someone take a look at the code snippets below and point out what is wrong?
User Model
public function followers(){
return $this->belongsToMany(User::class, 'followers', 'leader_id', 'follower_id')->withTimestamps();
}
public function followings(){
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'leader_id')->withTimestamps();
Follower model
protected $table = 'followers';
public $primaryKey = 'id';
public $timestamps = true;
public function user(){
$this->belongsTo('App\User');
}
FollowerController
Old controller for old relationship
// public function followUser($id){
// $user = User::find($id);
// if(!$user){
// return redirect()->back()->with('error', 'User does not exist.');
// }
// $user->followers()->attach(auth()->user()->id);
// return redirect()->back()->with('success', 'You now follow the user!');
// }
//New controller
public function followUser($id){
$user = User::find($id);
if(!$user){
return redirect()->back()->with('error', 'User does not exist.');
}
$follow = new Follower;
$follow->follower_id = Auth::user()->id;
$follow->leader_id = $user;
$follow->save();
return redirect()->back()->with('success', 'You now follow the user!');
}
UserController
// This is a test function
public function index($id){
$userid = Auth::user();
$user = User::find($id)->followers;
$recipe = Recipe::find(5);
$savedRecipes = Save::where('user_id', '=', $userid);
return view('welcome')->with('recipe', $recipe)->with('user', $user)->with('savedRecipes', $savedRecipes);
}
Test View
<div class="content">
<div class="title m-b-md">
Welcome to the TestLab: {{$user->followers->follower_id}}
<br>
This throws an error of "Property not found on this instance".
All the namespacing is all in order so that is not the issue either.
What is the problem here?

If you have a One To Many relationship between users and followers you defined your relationship wrong, if a follower belongs to a User, a User hasMany followers:
public function followers(){
return $this->hasMany('App\Follower','user_id');
}
Take a look at the docs
Your controller:
public function index($id){
$user = User::find($id);
return view('welcome')->with('user', $user);
}
You could access each follower from a user using a foreach loop:
#foreach($user->followers as $follower)
{{$follower->anyAttributeFromTheFollower}}
#endforeach

Related

i am trying to rate user but user only able to rate himself

There are two users in my users table user1 and user2
the user2 wants to rate user1
i have created a Rating table
which is as
Schema::create('ratings', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->string('rating')->nullable();
$table->string('review')->nullable();
$table->integer('rated_user_id');
$table->timestamps();
});
i have also created a model named Rating and defined a realtionship to the user
such as
public function user()
{
return$this->hasMany(User::class);
}
the code in my user model is as follow
public function Rating()
{
return $this->hasOne(Rating::class);
}
the code inside Ratingcontroller store function is as follow
public function store(Request $request)
{
//
$rating = new Rating;
$rating->fill($request->all());
$rating->user_id = Auth::id();
$rating->save();
return redirect()->back();
}
the problem is that in the rating table
every things looks fine
user_id is getting the id who is trying to post comment
and rated_user_id is givving the id to which the user is giving rating too
but the user is only able to rate himself not other users ..
The image in db is correct and Your store method in RatingsController is also works as expected.
So You want from us to give You code example to ProfileController method to get ratings provided by user and provided to user.
1) You've to add to User model following relation:
public function ratingsProvidedByMe()
{
return $this->hasMany(Rating::class, 'user_id', 'id');
}
public function ratingsProvidedToMe()
{
return $this->hasMany(Rating::class, 'rated_user_id', 'id')
}
2) in Rating model:
public function ratedBy()
{
return $this->belongsTo(User::class, 'user_id');
}
public function ratedTo()
{
return $this->belongsTo(User::class, 'rated_user_id');
}
3) in Your ProfileController:
public function view(Request $request)
{
$ratingsProvidedByMe =
Rating::with('ratedTo')
->where('user_id', Auth::id())
->all();
$ratingsProvidedToMe =
Rating::with('ratedBy')
->where('rated_user_id', Auth::id())
->all();
$me = $user = Auth::user();
return view(
'profiles.view',
compact(
'ratingsProvidedByMe',
'ratingsProvidedToMe',
'user', 'me'
)
);
}
P.S. it's just an example, adapt my example to Your project Yourself.

simple One to many relationship laravel

i have a user(ADMIN) and a student i want them to be in one table that is on the dashboard controller i cant find and exact answer in the searching please help me
Student model
public function user()
{
return $this->belongsTo("App\User", 'User_id', 'id');
}
User model
public function student()
{
return $this->hasMany("App\Student");
}
DashboardController
$users = User::with('user_id');
return view('superadminpage.admin_table')->with('users', $users);
Edit Student model code like this:
public function user(){
return $this->belongsTo("App\User");
}
Also edit User model:
public function students(){
return $this->hasMany("App\Student");
}
then use in DashboardController
$users = User::query()->with("students")->all();
return view('superadminpage.admin_table')->with('users', $users );
then you can do this:
foreach($users as $user){
$students = $user->students;
// use
}
first change the User_id to user_id at student model
public function user()
{
return $this->belongsTo("App\User", 'user_id');
}
second change at DashboardController
$users = User::with('user_id'); to $users = User::with('student')->all();
first change the User_id to user_id at student model
public function user()
{
return $this->belongsTo("App\User", 'user_id' , 'id');
}
second change at DashboardController
$users = User::with('user_id'); to $users = User::with('student')->all();
it's also good to change at user model public function student() to public function students() and call at DashboardController $users = User::with('students')->all();
public function users()
{
return $this->hasMany('App\User');
}
public function role()
{
return $this->belongsTo('App\Role');
}

Eloquent Relationship. Has Many relation with different keys

Background
I have a model, Contract that belongs to the User model through two keys, user_id and recipient_id. How would I be able to query all the contracts for a user using $user->contracts keeping the two key into consideration.
\App\Contract model has this
$protected $fillable = [
...
'user_id',
'recipient_id',
...
];
public function user ()
{
return $this->belongsTo(User::class);
}
public function recipient()
{
return $this->belongsTo(User::class, 'recipient_id', 'id');
}
\App\User model has this
public function contracts ()
{
return $this->hasMany(Contract::class);
}
To get the user contracts, I have to do this
$contracts = Contract::where('user_id', $user->id)
->orWhere('recipient_id', $user->id)
->get();
What I would like is something like this. \App\Contract
public function user () {
return $this->belongsTo([User::class, User::class], ['user_id', 'recipient_id']);
}
I am aware of https://github.com/staudenmeir/eloquent-has-many-deep and it doesn't solve my problems.
How do I go about it?
I couldn't find a way, so, I ended doing this in ContractController.php
public function index()
{
$user = Auth::user();
if ($user->isAdmin()) {
return Contract::latest()->get();
}
$contracts = Contract::where('user_id', $user->id)
->orWhere('recipient_id', $user->id)
->get();
return $contracts;
}

Laravel relations pivot table name trouble

in my app I have 2 conversations types: normal private conversations between users and conversations for people which are interested of user product.
In my User model I declared relations like:
public function conversations()
{
return $this->belongsToMany('App\Conversation', 'conversation_user');
}
public function conversationsProduct()
{
return $this->belongsToMany('App\ConversationProduct', 'conversation_product_user', 'user_id', 'product_id');
}
Where 'conversation_user' and 'conversation_product_user' are pivot tables between 'users'-'conversations' and 'users'-'conversations_product' tables.
My conversation_user pivot table has conversation_id and user_id table properties, but conversation_product_user pivot table has additional property product_id.
In my Conversation Model I have:
public function users()
{
return $this->belongsToMany('App\User');
}
public function messages()
{
return $this->hasMany('App\Message');
}
In ConversationProduct Model I wrote:
protected $table = 'conversations_product';
public function users()
{
return $this->belongsToMany('App\User', 'conversation_product_user');
}
public function messages()
{
return $this->hasMany('App\MessageProduct');
}
In my ConversationProductController I have method to find user conversations:
public function showUserConversationsProduct(Request $request){
$user_id = $request->user_id;
//var_dump($user_id);
$userData = User::where('id', $user_id)->with('conversationsProduct')->first();
}
And there is my problem: In controller ->with('conversationsProduct') don't take relation for conversation_product_user, but for conversation_user pivot table. I can't handle it why its happen if I add second parameter as 'conversation_product_user' in my relation:
public function conversationsProduct()
{
return $this->belongsToMany('App\ConversationProduct', 'conversation_product_user', 'user_id', 'product_id');
}
I need protected $table = 'conversations_product'; to point my ConversationsProductController#store where to save conversation, but I think that can be problem with recognise proper relation.
I really appreciate any help. I attach photo of my db relations.

Saving related records in laravel

I have users, and users belong to a dealership.
Upon user registration, I'm trying to save a new user, and a new dealership.
User database has a dealership_id column, which I want to be populated with the ID of the newly created dealership.
This is my current code in the UserController store method.
public function store()
{
$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$dealership = new Dealership();
$dealership->name = Input::get('dealership_name');
$user->push();
return "User Saved";
}
Trying to use $user->push(); User data gets updated, but dealership is not created or updated.
Eloquent's push() saves the model and its relationships, but first you have to tell what you want to be involved in the relationsship.
Since your user-model/table holds the id of the dealership, I assume that a user can belong to only one dealership, so the relationship should look like this:
User Model:
public function dealership()
{
return $this->belongsTo('Dealership');
}
Dealership Model:
public function users()
{
return $this->hasMany('User');
}
To save a User from the Dealership perspective, you do this:
$dealership->users()->save($user);
To associate a dealership with a user, you do this:
$user->dealership()->associate($dealership);
$user->save();
Please check this answer to see the difference of push() and save()
You will need to define correctly your models relationships as per documentation
If this is done correctly, it should work .
This is what push() does :
/**
* Save the model and all of its relationships.
*
* #return bool
*/
public function push()
{
if ( ! $this->save()) return false;
// To sync all of the relationships to the database, we will simply spin through
// the relationships and save each model via this "push" method, which allows
// us to recurse into all of these nested relations for the model instance.
foreach ($this->relations as $models)
{
foreach (Collection::make($models) as $model)
{
if ( ! $model->push()) return false;
}
}
return true;
}
In your case, you have a one (dealership) belongs to many (users)
In your Users model :
class Users extends Eloquent {
public function dealership()
{
return $this->belongsTo('Dealership');
}
}
In the example above, Eloquent will look for a dealership_id column on the users table.
In your Dealership Model :
class Dealership extends Eloquent {
public function users()
{
return $this->hasMany('User');
}
}
In your store function :
public function store()
{
$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->dealership = new Dealership();
$user->dealership->name = Input::get('dealership_name');
$user->push();
return "User Saved";
}
Learn here more about eloquent relationships
Also please take a look at my answer here
By using push on the User model, Laravel is basically recursively calling save on all the related models (which, in this case, is none, since you haven't associated any other models to it yet).
Therefore, in order to accomplish what you're trying to do, you can do first create the user then associate the dealership with it by doing the following:
$user = new User();
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
$dealership = new Dealership();
$dealership->name = Input::get('dealership_name');
$user->dealerships()->save($dealership);
return "User Saved";
However, prior to doing this, you must ensure your User and Dealership models have their relationships set up correctly:
User Model:
public function dealership()
{
return $this->belongsTo('Dealership');
}
Dealership Model:
public function users()
{
return $this->hasMany('User');
}
This is how I manage to do it.
In your controller: (Laravel 5)
use Auth;
$dealership->user = Auth::user()->ref_user->staff_id;

Resources