I am trying to display all posts by a user and have this in my code that works only when a user is signed in and displays all the user's posts.
$id = Auth::getUser()->id;
$this['allproducts'] = Advert::where('user_id', $id)->orderby('created_at','desc')->get();
I want to make this visible to all signed in or not. when i logged out and try to access the url, it throws up an error
Trying to get property 'id' of non-object
try using: If there is no authenticated user it gives null and it should not fetch. (If user_id does not remain null on Advert model table)
$id = Auth::getUser()->id ?? null;
if (Auth::user()){
You should check whether your entries using the command.
I want to make this visible to all signed in or not. when i logged out and try to access the url, it throws up an error
It is not clear in this context who you refer to as a User.
If you want to make the posts of 'any user' accessible to 'any other user' then your implementation is not correct.
Auth::getUser()
- Retrieves the signed in User from the active session - See here - The error you posted is expected because after sign out, the Auth session is cleared and you cannot access the id
property anymore.
You are basically doing $id = null->id;
What you could do is list the registered users and let the site visitor / user decide which user's posts to display.