Trying to get property of non-object error in laravel - php

ive been trying to match User_id from my users with Creator_id to display the creators username in my post
but im getting the trying to get property from non-object error and i cant get arround it
the function in my controller
postcontroller.php:
public function index()
{
$allusers = users::getusers();
$posts = DB::table('posts')->get();
foreach ($posts as $posts) {
foreach ($allusers as $allusers) {
if ($posts->creator_id == $allusers->user_id) {
array_push($posts,$allusers->username);
}
}
}
return view('blog',['posts'=>$posts]);
}
the functions in my model:
public static function getusers(){
$allusers = users::all();
return $allusers;
}

You are using the same variable names in your foreach loops :
foreach ($posts as $post) {
foreach ($allusers as $user) {
if ($post->creator_id == $user->user_id) {
array_push($post,$user->username);
}
}
}
But for your issue, you should try to add this in your Post Model
public function user(){
return $this->belongsTo(User::class, 'creator_id', 'user_id);
}
then in your view :
#foreach($posts as $post)
{{ $post->user->name }}
#endforeach
https://laravel.com/docs/5.4/eloquent-relationships#one-to-many-inverse

Does your users table has a column like user_id?
I think you have check with users table id with posts creator_id.

Related

Undefined Variable 'Comments' in Compact Laravel

I am getting 'undefined offset 1' error. It does returns everything I need -> the posts and the comments in the category. However, I believe the 'Undefined Offset 1' problem is probably due to some post which have no replies to them?? -> thus, help.
I have
1. Category Model
2. Post Model
3. Comment Model
This is the show function in my Category Model
public function show($id)
{
$category = Category::with('posts.comments')->find($id);
return view('categories.show', compact('category'));
}
I have made relation for 'Category hasMany Posts' -> 'Post hasMany Comments'.
You can try this
public function show($id)
{
$comments = []; // Empty array to initialize the variable. This variable will be filled once the foreach statement is ran.
$category = Category::find($id);
if($category !== null) {
$posts = $category->posts;
foreach($posts as $post) {
$comments = $post->comments;
}
}
return view('categories.show', compact('posts', 'category', 'comments'));
}
Alternative method
public function show(Category $category) //same as... public function show($id)
{
return view('categories.show', compact('category'));
/*
Render this content in the view.
#foreach($category->posts as $post)
{{-- Display Post Content --}}
#foreach($post->comments as $comment)
{{-- Display Comment Content --}}
#endforeach
#endforeach
*/
}
You are creating $comments variable inside foreach loop that make it's scope locally and will not be available outside foreach
To resolved this error you need to define your comments variable inside your function so that it is available in your function
public function show($id)
{
$comments = []; // define it here
$category = Category::find($id);
if($category !== null) {
$posts = $category->posts;
foreach($posts as $post) {
$comments = $post->comments;
}
}
return view('categories.show', compact('posts', 'category','comments'));
}

Laravel displaying many to many relationship items

I have set up a many to many relationship in Laravel and have the database table populated with data. The relationship setup looks like this...
users.php
---------
public function houses()
{
return $this->belongsToMany('App\House')
->withTimestamps();
}
house.php
---------
public function users()
{
return $this->belongsToMany('App\User')
->withTimestamps();
}
In my /house/show.blade.php I am trying to display the saved connections like this...
$houses = House::with('App\User')->all();
foreach ($houses as $house) {
echo 'Found House';
}
It is giving me an error saying that $houses can not be found. Where am I going wrong?
You should indicate the relationship in the with method like this :
$houses = House::with('users')->get();
And one more thing it's better to get houses in the controller and pass them to the view :
$houses = House::with('users')->get();
return view('someView')->withHouses($houses);
And in the view do it like this :
#foreach ($houses as $house)
{{ $house->addres }}
#endforeach
To get only the houses taht has the users try this :
$houses = House::has('users')->get();
And to add some conditions on the users you can do it like this :
$houses = House::whereHas('users', function ($query) {
$query->where('name', 'some user name'); // to add some conditions on the user :)
})->get();
You should try this:
$houses = House::with('users')->get();
foreach ($houses as $house) {
echo 'Found House';
}
OR
In controller:
use House;
$houses = House::with('users')->get();
return view('someView',compact('houses'));
In Blade file:
#foreach ($houses as $house)
{{ $house->name }}
#endforeach

Relationship not working. Foreach. Laravel

So I have defined relationship between OrderProduct.php and 'Product.php' models like this:
OrderProduct.php:
public function product()
{
return $this->belongsTo('App\Product');
}
Product.php
public function order()
{
return $this->belongsTo('App\OrderProduct');
}
OrderController function
public function orderShow($id)
{
//$order = Order::where('id', $id)->first();
$products = OrderProduct::where('id', 32)->first();
return view('admin.orders.show', compact('order', 'products'));
}
When I do this foreach:
#foreach($products as $product)
<?php dd($product) ?>
#endforeach
I get Invalid argument supplied for foreach() How to fix this ?
You've got only first record from set.
Try
public function orderShow($id)
{
//$order = Order::where('id', $id)->get();
$products = OrderProduct::where('id', 32)->get();
return view('admin.orders.show', compact('order', 'products'));
}
EDIT
If you need to retrieve particular record by id, use find() or even findOrFail() method (difference you can find in docs);
public function orderShow($id)
{
// this will retrieve record with id=32 from db if it exists,
// and throw Illuminate\Database\Eloquent\ModelNotFoundExceptio otherw
$product = OrderProduct::findOrFail(32);
return view( 'admin.orders.show', compact('product') );
}
then in your blade template you can access your $product info as an object, like so
{{ $product->name }}
{{ $product->otherProductProperty }}
You are giving
$products = OrderProduct::where('id', 32)->first();
which will fetch you only one record the result will not be a collection so you cannot do foreach for this
You can change it as
$products = OrderProduct::where('id', 32)->get();
to make it work
You need to even check the Relationship used. One will be belongs to and the other will be hasmany
you should try like this..
public function orderShow($id)
{
//$order = Order::where('id', $id)->get();
$products = OrderProduct::where('id', 32)->with('product')->get();
return view('admin.orders.show', compact('order', 'products'));
}

Laravel 5.1 get data from connected table

In my app admin users can create articles. Articles table is: ID | user_id | title ...
For every Article other user (which not admin) can post an offer and Offer table is: ID | user_id(not admin) | article_id | price ...
Now I need to get all users for an admin user which post Offer to their Article... I try:
public function userbase()
{
$id = Auth::user()->id;//get admin id
$articles = Article::where('user_id', $id)->get();//select all admin articles
foreach ($articles as $article) {
$users = Offer::where('article_id', $article['id'])->orderBy('created_at', 'desc')->get(); //get all admin users
}
return $users;
}
but I get just: []
also my Model is:
Article:
public function offers() {
return $this->hasMany('App\Offer');
}
Offer:
public function user() {
return $this->belongsTo('App\User');
}
public function article() {
return $this->belongsTo('App\Article');
}
So how I can get all user details which was posted offer to an admin user?
UPDATE
I also try this:
$articles = Article::with([
'offers' => function($query) {
$query->orderBy('created_at', 'desc');
$query->with('user'); // if you want to eager load users for each offer too...
}
])->where('user_id', Auth::id())->get();
and I get this data:http://i.imgur.com/0kBVGrx.png
but how to access user data? I try ->get('user') but dont work...
2. UPDATE:
I also try:
public function userbase()
{
$articles = Auth::user()->articles()->get();
foreach ($articles as $article) {
$offers = Offer::where('article_id', $article['id'])->orderBy('created_at', 'desc')->get();
}
foreach ($offers as $offer) {
$users = User::where('id', $offer['user_id'])->orderBy('created_at', 'desc')->get();
}
return $users;
}
but I get undefined variable users
Try this :
First, you may add an attribute 'isAdmin' in your User model.
public function userbase()
{
return Offer::select('users.*')
->where('users.isAdmin', false)
->join('articles','articles.id','=','offers.article_id')
->join('users','users.id','=','articles.user_id')
->where('articles.user_id', Auth::user()->id)
->orderBy('offers.created_at', 'desc')
->groupBy('users.id')
->get();
}
Updating Your solution :
public function userbase()
{
$articles = Auth::user()->articles;
foreach ($articles as $article) {
$offers = Offer::where('article_id',$article->id)->orderBy('created_at', 'desc')->get();
}
$users = array();
foreach ($offers as $offer) {
$users[] = User::where('id', $offer['user_id'])->orderBy('created_at', 'desc')->get();
}
return $users;
}

Laravel belongsTo returns, put can't save in var

I'm trying to get the username by a item with belongsTo.
I have this in my Item model:
public function user()
{
return $this->belongsTo('User', 'user_id', 'id');
}
And this in my controller:
$user = $item->user->username;
But I get:
Trying to get property of non-object
And when I do:
return $item->user->username;
In my controller it works.
What can be wrong?
Controller/Model: http://pastebin.com/qpAh8eFd
You have following function in your controller:
public function index($type)
{
$items = $this->item->where('type', '=', $type)->get();
foreach($items as $item):
$user = $item->user->username;
endforeach;
return View::make('items.index', ['items' => $items, 'user' => $user]);
}
You don't need to do a foreach look in the controller and whatever you are doing you are doing it wrong, instead make your index function like this:
public function index($type)
{
$items = $this->item->where('type', '=', $type)->get();
return View::make('items.index', ['items' => $items]);
}
Pass only $items to your items/index.blade.php view. You may do a foreach loop in your view if needed and within each iteration you may access the user related to the item using something like this:
#foreach($items as $item)
{{ $item->user->uername }}
#endforeach
You may get Trying to get property of non-object error message because each $item may don't have a related user. So, make sure each $item has a related user. You can also, use following to get items with user:
$items = $this->item->with('user')->where('type', '=', $type)->get();
return View::make('items.index', ['items' => $items]);
In your view you may check if the item has a related user:
#foreach($items as $item)
#if($item->user)
{{ $item->user->uername }}
#endif
#endforeach

Categories