Get all posts from users that are not blocked in Laravel? - laravel

I have a Laravel 5.8 application where one user can block another user.
User model:
public function blockedUsers()
{
return $this->belongsToMany(User::class, 'blocked_user', 'user_id', 'blocked_id');
}
Now every user can post articles. How to get all articles that are posted by non blocked users in users feed.
If I do:
$posts = Post::all();
Obviously I will get all posts, so how to make a where conditin and say all posts that are created by a user which is not blocked by Auth::user()?
$user = Auth::user();
$posts = Post::where(function($q) use ($user){
// Can't figure out this part
})->get();

You can first get your blocked user ids and use it later in the query to check if the creator of the post is one of the blocked ids using whereNotIn()
$user = Auth::user();
// Get list of blocked user ids
$blockedIds = $user->blockedUsers->pluck('id')->toArray();
// NOTE: I am assuming the field that hold the post creator id is user_id
// Get all post where the creator id is not in the blocked ids array
$posts = Post::whereNotIn('user_id',$blockedIds)->get();
Alternatively you can also write it like this
$user = Auth::user();
$posts = Post::where(function($q) use ($user){
$q->whereNotIn('user_id', $user->blockedUsers->pluck('id'))
})->get();

$user_id = Auth::id();
// get all blocked users by auth user
// note: you need to create BlockedUser model for blocked_user table
$blocked_users=BlockedUser::where('user_id',$user_id)->pluck('blocked_id');
// get all posts without posts that created by blocked users
Post::whereNotIn('user_id',$blocked_users)->get();

Related

Get records from two relations (one is pass through accessor) with paginate

Laravel 7.x
I need to get posts from two relations. Look:
User has Posts;
User has Friends (accessor);
Friends has Posts;
How can I get all own (User) posts and all posts by each Friend, and paginated?
Which the best way to do that?
Only to pass the idea that I want to say:
$user = User::find(1);
$posts = $user->with('posts','friends.posts')->paginate(15); // I wanna get only the Posts collection
I would suggest query your Post model and then apply filter for user and related friends filter.
$user = User::with('friends')->find(1);
$userIds = $user->friends->pluck('id')->toArray();
array_push($userIds, $user->id);
$posts = Post::whereIn('user_id', $userIds)->paginate(15);
You can use hasManyThrough, this relationship is a bit complicated to understand a provide shortcut way to access data of another mode relation.
In your User model make relationship like this way :
public function posts()
{
return $this->hasManyThrough(
Post::class,
Friend::class,
'user_id', // Foreign key on friends table...
'friend_id', // Foreign key on posts table...
'id', // Local key on users table...
'id' // Local key on friends table...
);
}
Now you can get all posts from User model like this way :
$user = User::find(1);
$posts = $user->with('posts')->paginate(15);

Show all posts exept of users that you follow Laravel 7

I have made an Instagram like web-application with laravel 7.
The $posts are displayed in DESC order like so: (This is in the PostController)
public function index()
{
// All the users that are followed
$users = auth()->user()->following()->pluck('profiles.user_id');
// All the posts from those users
$posts = Post::whereIn('user_id', $users)->with('user')->latest()->paginate(5);
return view('posts.index', compact('posts'));
}
I want to create a new view named explore.blade.php. The content needs to be the latest post from all the users that are not being followed.
This $posts = Post::whereIn('user_id', $users)->with('user')->latest()->paginate(5); needs to be inversed so that these get left out.
You can use whereNotIn():
$posts = Post::whereNotIn('user_id', $users)->with('user')->latest()->paginate(5);

Auth::user() works but Auth::user()->id breaks within a where query in eloquent?

I'm very confused by this!
In a laravel controller:
$user = Auth::user();
return $user;
returns the entire user object
$user = Auth::user()->id;
return $user;
returns the id of $user as expected
however if I put that exact thing into a query such as:
$user = Auth::user();
$query = Model::where('user_id', $user->id)->get();
return $query;
I get an error that I'm trying to get an 'id' property of a non-object!!!
How can this be possible?
I've also checked 100 times that I'm logged in when testing this.
Editing to add that I've also tried:
$query = Model::where('user_id', 1)->get();
and that works fine
edit to show the function:
$user = Auth::id();
$result = Lesson::where('user_id', $user)
->whereNotNull('notes')
->get();
return response()->json($result, 200);
Expected results: A list of objects with a filled in "notes" column.
Actual results: an empty [] and an error saying can't get id of a non-object
Don't use Auth in Models.
You can set a relation between User and your Model and do query like:
Auth::user()->relation()->get();
This error occurs if the Model doesn't contain any raw with that user id. Make sure you have the raw in the Model where you are querying to get data by user id.
You should try this
$user = Auth::user();
$result = Model::where('user_id', $user['id'])->get();
The error occurs because of you passed property of non-object.
Even after error not solve then restart your xampp or wamp.
If possible, upload the screenshot of error.
Your code should work if you are authed, it seems your are not based on the error message. Since you return json, i assume this is an api request. Api-routes uses another auth driver as default in Laravel (token vs. session). Either change the driver/guard or move your route(s) from routes/api.php to routes/web.php.
See docs for auth
You can change the driver in config/auth.php.
try this
$user_id = Auth::user()->id;
$query = Model::where('user_id', $user_id)->get();
return $query;

Laravel am I doing multiple queries by calling the Auth::user() multiple times in my controller

In my controller I get the logged in user id and username like this:
$userId = Auth::user()->id;
$username = Auth::user()->user_name;
But will the above code produce two queries?
I dont understand how Auth::user() works behind the scene
If your code generates 2 query save user in another variable.
Like this:
$user = Auth:user();
$userId = $user->id;
$username = $user->user_name;
Laravel does not store all user in session, it stores only user id. And when call user() function laravel will get user from database with saved user id.
Auth::user() return an object with your user data from the users table.
So, if you want just one query, use :
$user = Auth::user();
echo $user->user_name;
Have a look on official doc, at Validation section.
Be sure that your user is logged before call Auth method :
if (Auth::check()) {
// User logged
}
If you want reduce database query, fetch Authenticated user like this:
$user = Auth::user():
$id = $user->id;
$name = $user->name;
dd($user);
In laravel Auth::user() has all data of current authenticated user.

How to query relationships in Laravel 4 with Eloquent?

Coming from CodeIgniter's Datamapper ORM I am still trying to get my head around Laravel's Eloquent ORM.
Given the fact that I have an ACCOUNT and a USER table (simplified):
ACCOUNT
- id
- name
USER
- id
- account_id
- username
One account has many users. One user belongs to one account. So we're dealing with a one-to-many relationship. Everything is already set-up in the models.
In CodeIgniter's Datamapper I would have done the following to get the user from any given ID and at the same time check if that user is related to the current account:
$u = new User();
$u->where('username', $username);
$u->where_related_account('id', $account_id);
$u->get();
if ( ! $u->exists()) exit; // or do something...
// otherwise continue to use the "$u" user object
This syntax is very logical and easy to understand. In Eloquent I have a hard time to achieve the same with a similar easy syntax. Does anyone have any suggestions?
Very simply (ignoring the relationship between the user and the account), it could just be:
$u = User::where('username', $username)
->where('account_id', $id)
->get();
That will return you your user's details.
Otherwise, assuming that you have your User and Account classes and DB tables are set up correctly (as per the Laravel docs), you should be able to just do:
$user_exists = Account::find($account_id)
->users()
->where("username", "=", $username)
->first()
->exists;
if ($user_exists)
{
doThings();
}
If you've correctly set up your models and database tables (as #msturdy said) you should actually be able to return your user account by simply going:
$user = User::whereUsername($username)
->first(); // or User::where('username', $username)->first();
if ($user) {
$account = $user->accounts()
->whereId($account_id)
->first(); // or $user->accounts()->where('id', $account_id)->first();
}
This gives you the ability to access the user and account models
you could even extend your User model to include the following methods:
class User extends Eloquent {
...
public static function byUsername($username) {
return static::whereUsername($username)->first();
}
public function getAccount($id) {
return $this->accounts()->whereId($id)->first();
}
...
}
and then simply go
$user = User::byUsername($username);
if ($user) {
$account = $user->getAccount($account_id);
}
which might be better for you if you are using the code in multiple controllers.

Resources