using 'foreach' in first() not working Laravel Eloquent - laravel

I'm trying to add an custom attribute unto the retrieved collection
$category = categories::where('cat_id',$id)->first();
foreach($category as $c):
dd(var_dump($c->cat_id))
$c->custom_attr = $c->cat_id;
endforeach;
but it throws me this error
Trying to get property of non-object
not unless if I use 'get()' instead of 'first()' then it worked. If I do
$category = categories::where('cat_id',$id)->first();
foreach($category as $c):
dd(var_dump($c))
endforeach;
it returns me
bool(true)
null
if I do
$category = categories::where('cat_id',$id)->first();
foreach($category as $c):
dd(var_dump('xx'))
endforeach;
Sure the dump returns 'xx'. Any ideas, help please?

You should use get() instead of first().
first() gives you an object, get() will give you a collection of objects.
If you want to get properties, do not use foreach() or for(), just get properties like this:
$category->name;

Related

Laravel 6: trying to get property of non-object

Error: Trying to get property 'gender_id' of non-object
Controller:
public function printreports(Request $request)
{
$id = $request->get('select2'); //eg. id=1
$teachers = DB::table('teachers')->find($id);
return view('teachers.report1',compact('teachers'));
}
View:
#foreach($teachers as $teacher)
{{$teacher->gender_id}}
#endforeach
while if i do it with Eloquent by replacing following query it works, but i want to do it with DB query as stated above.
$teachers = Teacher::find($id);
you need use where, and after it you will have collection.
$teachers = DB::table('teachers')->where('id', $id)->get();
when you use find, you have single item
You don't need to use foreach while you use find().
#if(sizeof($teachers))
{{$teachers->gender_id}}
{{$teachers->gender_id}}//whatever field you need to display
{{$teachers->gender_id}}//whatever field you need to display
#endif
If you use get(),
$teachers = DB::table('teachers')->where('id','=',$id)->get();
#if(sizeof($teachers))
#foreach($teachers as $teacher)
{{$teacher->gender_id}}
{{$teacher->gender_id}}//whatever field you need to display
{{$teacher->gender_id}}//whatever field you need to display
#endforeach
#endif
$teachers = DB::table('teachers')->find($id); will return a single Model or  null, try using $teachers = DB::table('teachers')->get();
If you want to return collection to view then use get() method like this:-
public function printreports(Request $request)
{
$id = $request->get('select2');
$teachers = DB::table('teachers')->where('id', $id)->get();
return view('teachers.report1',compact('teachers'));
}

How to check data in Array by using eloquent method in Laravel

I am working on a quiz. Below is a method and I am trying to get an array that can work in in_array function:
public function mcq($id)
{
$questions = Chapter::find($id)->questions()->inRandomOrder()->limit(1)->first();
$question_check = TestsResultsAnswer::where('user_id', auth::id())->pluck('question_id')->toArray();
$sponsors = Sponsor::All();
return view('pages.mcq', compact('questions', 'sponsors', 'question_check'));
}
Below is blade code where I am passing the question_check variable by using in_array function:
#foreach ($questions as $key => $question)
#if(in_array($key, $question_check))
{{'Question Already Attempted'}}
#endif
#endforeach
But I am getting following error:
(2/2) ErrorException
Trying to get property of non-object (View: E:\xampp\htdocs\laravel\lea\resources\views\pages\mcq.blade.php)
My goal is to check if question was already attempted then print something. Please Help me to resolve this problem.
Using first() will return a Model and not a collection, so you can't loop through. Use get() to fetch the result as a collection.
I.e: Instead of this
$questions = Chapter::find($id)->questions()->inRandomOrder()->limit(1)->first();
do this
$questions = Chapter::find($id)->questions()->inRandomOrder()->limit(1)->get();
This should fix your current problem.
Considering this,
My Target is to make a check if question already attempted then print something.
I think this is what you really want to do.
In Controller
$questions = Chapter::find($id)->questions()->inRandomOrder()->get()
In Blade
#foreach ($questions as $question)
#if(in_array($question->id, $question_check))
{{'Question Already Attempted'}}
#endif
#endforeach

Laravel 5.2 geting Trying to get property of non-object

2 and I am getting some strange problem I am using model inject in blade for example when I am using this code:
<?php $b = $model1->where('id', '=', $product->user_id)->first(); ?>
{{$b->first_name}}
I am getting what I want as a result but when I do the same thing wiht this code:
<?php $b1 = $model2->select('name','number')->where('device_id', '=', $product->imception_id)->distinct()->first(); ?>
{{$b1}}
This gives me :
{"name":"jan","number":"447515485475"}
But when I am doing this :
{{$b1->name}}
I am getting Trying to get property of non-object I don't know how this will work what do I need to do please answer thanks in advance.

Filter the collections and remove a collection eloquent laravel

I want to remove a filtered collection from a collections like I have this returned collections.
$products = items::where('item_id',$request->item_id)->with('product_reviews')->with('product_reviews.profile')->get();
foreach($products->product_reviews as $r):
if($r->status==='unapproved'):
//remove this from 'products' collections because its not approved yet
$this->remove($this);
endif;
endforeach;
but this
$this->remove($this);
does not work, neither a valid syntax to remove the collection, I just don't know how to remove the filtered collection e.g. if column status contains 'unapproved'. Any ideas, help please?
You can add a condition in your relation. This is not tested but most likely will solve your problem.
items::where('item_id',$request->item_id)->with([
'product_reviews' => function ($query) {
$query->where('status', 'approved')->with('profile');
}
])->get();
Hmm.. a little bit strange since the other 2 solutions should work for your case.
Have you tried to filter and pass the objects to other array and show them inside your view? Like:
$productWithReviews = items::where('item_id',$request->item_id)->with('product_reviews')->get();
$products = [];
foreach($productWithReviews->product_reviews as $r):
if($r->status!=='unapproved'):
$products[] = $r;
endif;
endforeach;

htmlentities() expects parameter 1 to be string, array given? Laravel

I've found many question realated to my problem but couldn't found an answer yet. It's about my foreach loop in my blade.
I want to print all product-names in my blade but I couln't figure out how to do that.
thats how I'm getting the products:
--- current code:
// controller
$id_array = Input::get('id');
$products= Products::whereIn('id', $id_array)->get();
$product_name = [];
foreach($products as $arr)
{
$product_name= $arr->lists('name');
}
returning $product_name gives me this as a output:
["football","cola","idontknow","freshunicorn","dummy-data"]
In my blade is just a simple:
#foreach($products as $product)
{{ $product}}
#endforeach
Error: htmlentities() expects parameter 1 to be string, array given
Thanks for your help and time.
It seems you are getting an object in an array in an array.
Like this:
array(
array(
object
)
)
It happens because you use the get() function to retrieve you model. The get() function always "wants" to retrieve multiple models. Instead you will have to use the first() function.
Like this:
foreach($id_array as $arr)
{
$want2editarray[] = Product::where('id', $arr)->first();
}
Hope it helps :)
Edit after #Wellno comment
That's probably because Product::where('id', $arr)->first(); returns null because it did not find anything.
I forgot to add a check after the retrieving of the product.
This can be done like this:
foreach($id_array as $arr)
{
// First try to get model from database
$product = Product::where('id', $arr)->first();
// If $product insert into array
if ($product) $want2editarray[] = $product;
}
Why do you use loop with IDs? You can find all products by IDs:
$products = Product::whereIn('id', $id_array)->get();
And then use $products in the blade template
#foreach($products as $product)
{{ $product->name }}
#endforeach
try to use Model/Eloquent to fetch data.
View should only display the data and not fetching directly from DB or do heavy calculations.

Resources