Laravel getting class on view without passing from controller - php

I have a pivot table post_profile that contains the hearts (likes) of each post.
Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function profilesHearted()
{
return $this->belongsToMany(Profile::class);
}
}
Profile.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $guarded = [];
public function profileImage()
{
$imagePath = ($this->image) ? $this->image : 'profile/czyhBQu2YWX6gvBivZrnEs2ORoBwr3d9mzkwxk8k.png';
return $imagePath;
}
public function followers()
{
return $this->belongsToMany(User::class);
}
public function heartedPosts()
{
return $this->belongsToMany(Post::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
The main view which shows all posts of followed users is working along with the heart button but underneath I want to show liked by <x> and 30 others, where x is first follower of the user if any of the user's follower hearted the post. I tried many ways to get x but I am a bit lost.
This is PostsController.php index function which leads to the view:
public function index()
{
$users = auth()->user()->following()->pluck('profiles.user_id');
$posts = Post::whereIn('user_id', $users)->with('user')->latest()->paginate(5);
return view('posts.index', compact('posts', 'users' ));
}
What I tried to do but deleted eventually after failing is get each post in foreach loop and check if each $post->heartedProfiles(contains($users)), but this doesn't work this way. So another way I tried is in my view ie, index.blade.php
#foreach($users as $userid)
User::select('id')->where('profile_id', $userid)->first()
->profile->profilesHearted->find($post->id)
#endforeach
Which doesn't work because User class cannot be used directly in view without passing.
I'm sure there is a simple and cleaner way to do this in Laravel. This is my first time using Laravel and ORM programming so really felt lost. Took the FreeCodeCamp Instagram clone tutorial and understood the basics. All I need is to give me some idea to get started.

When dealing with many to many you need to use the pivot functions, so you would do like so
Post::profilesHearted()->wherePivotIn('profile_id', $users)->first()
Not checked the code but hopefully it will give you the idea.

Related

Property [posts] does not exist on this collection instance

Hope you're all having a good day. I'm working on a blogs page and reached a part where I want to display the certain blogs a user has posted. I added relations to the Post model and User model but i can't seem to get the specific posts of the logged in user and it gives me the error above in the title. Here are my models and Profile controller.
The users schemaThe posts schema
Post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
Posts function in User model
public function posts(){
return $this->hasMany(Post::class);
}
The ProfileController
<?php
namespace App\Http\Controllers;
use App\Reviews;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$user_id=auth()->user()->id;
$user = User::where('id', $user_id)->get();
$posts= $user->posts;//Gets all details of the user with id 123
return view('profile')->with(['users' => $user ],['posts', $posts]);
}
}
$user = User::where('id', $user_id)->get(); // return a collection so it is multiple items and would have to be accessed as so
This should be
$user = User::where('id', $user_id)->first();
Or rather
$user = User::find($user_id);
But better
$user = auth()->user()
Be mindful that you are doing some unnecessary work, auth()->user() is the user instance there is no need to use that to then get it from the database. As it stands you would have access to the User in the blade template for profile using Auth::user() So there may be no reason just yet to even do any database queries in the controller. This may change as you build out the page of course

Get the morphMany relationship to a model from the user

Let say i have the following;
User Model;
class User extends Authenticatable
{
public function posts()
{
return $this->hasMany('App\Models\Socials\Post');
}
}
Post Model;
class Post extends Model
{
public function comments()
{
return $this->morphMany('App\Models\Socials\Comment', 'commentable');
}
Comment model;
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
When i used $user = User::find($id); and $user->posts(), it returns all the post of the user, but if i used this method $user->posts()->comments() It return this message Method Illuminate\Database\Query\Builder::comments does not exist.
The question is how can i get all the comments of the user on the said post?
Change:
$user->posts()->comments();
to:
$user->posts->pluck('comments')->collapse();
The method itself returns an instance of Eloquent's query builder allowing you to add to or edit the query if you want. However, if you don't want to edit the query you can access the relationships as properties and Laravel will handle to execution of the query.
Essentially, $user->posts is actually turning into $user->posts()->get() in the background.
Credit to #JonasStaudenmeir.

Laravel relationship not working: getConnectionName() Error

I have two tables users and user_details. I have linked users table as
public function userDetails()
{
return $this->hasOne('App\Repositories\Models\UserDetails', 'id', 'user_id');
}
and linked user_details table as
public function user()
{
return $this->belongsTo('App\Repository\Models\User');
}
While from UserController for accessing users data with details, if I try to access the data
return $this->user->with('userDetails')->get();
I get this type of error
FatalErrorException in HasRelationships.php line 488: Call to undefined method
App\Repositories\Models\UserDetails::getConnectionName()
Is there anything wrong?
Make sure UserDetails class extends Model class:
use Illuminate\Database\Eloquent\Model;
class UserDetails extends Model
You can also clean up your code like this. Having neat code will make your code more valuable and it will be easier for other developers to understand or you to remember when you get back to your code later on.
use Illuminate\Database\Eloquent\Model;
use App\Repository\Models\User;
use App\Repository\Models\UserDetails;
public function user()
{
return $this->belongsTo('User');
}
public function userDetails()
{
return $this->hasOne('UserDetails', 'id', 'user_id');
}

Laravel - Call to undefined method Illuminate\Database\Query\Builder::user()

I am busy with Laravel From Scratch: Updating Records and Eager Loading. I have followed the tut but I am getting this error when trying to add user data in CardsController. I am assuming that I've missed a step in the card user relationship somewhere but I've watched the video 3 times and my database queries for User, Card & Note matches the video exactly.
Is there another step I need to perform after creating the Users table via the migration perhaps?
Error
BadMethodCallException in Builder.php line 2345:
Call to undefined method Illuminate\Database\Query\Builder::user()
CardsController code
<?php
namespace App\Http\Controllers;
use App\Card;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CardsController extends Controller
{
public function index()
{
$cards = Card::all();
return view('cards.index', compact('cards'));
}
public function show(Card $card)
{
$card = Card::with('notes.user')->get();
return $card;
return view('cards.show', compact('card'));
}
}
Your note model is lacking the relationship definition for it's associated user, it looks like.
You should just be able to add the relationship in the Notes model like this:
public function user()
{
return $this->belongsTo(User::class);
}
That video does have some problems, so I also encountered the same problem.
You should just be able to add the relationship in the Note model like this:
public function user()
{
//return $this->belongsTo(User::class);
return $this->belongsTo('App\User');
}
and in the User model like this:
public function notes()
{
return $this->hasMany(Note::class);
//return $this->belongsTo('App\Note');
}
bless you !

Class Comment not found Laravel 4

Im trying to add a comment system to my laravel app.
But I can't seem to get it working.
I have two models
class Post extends \Eloquent {
protected $table = 'posts';
public function comments()
{
return $this->hasMany('Comment','postId');
}
}
and my Comment model
class Comment extends \Eloquent {
protected $table = 'comments';
public function post()
{
return $this->belongsTo('Post');
}
}
in my DashBoardController I'm trying to get the output from the models
use App\Models\Post;
use App\Models\Comment;
use Input, Redirect, Sentry, Str, View, Notification;
class DashboardController extends \BaseController {
public function index()
{
$post = Post::find(3)->comments()->comment;
print_r($post);die;
}
}
I think my database is properly linked, but now I'm getting the error
'Class Comment not found'.
Any advice on this one?
First try this: composer dump-auto (as commented by user1669496)
if this didn't helped then change your model...
Change this:
return $this->belongsTo('Post');
to smth like this:
$this->belongsTo('App\Models\Post');
Do the similar for Post model.
Just change App\Models\XXXX to your namespace where you have Post model saved.
I had similar problem and this helped me, hope it will help you.

Categories