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
Related
I have a controller method which retrieves data from a Queue, the queue can have a relationship to either a Guest or a Customer model.
In my blade template I iterate over the Queue and need to display either Guest.Name or Customer.Name depending on which column is populated.
Controller
$queue = Queue::where('business_id', '=', $business_id);
$customer_bag = $queue->pluck('user_id');
$guest_bag = $queue->pluck('guest_id');
$customers = User::whereIn('id', $customer_bag)->get();
$guests = Guest::whereIn('id', $guest_bag)->get();
return view('myqueue', compact(['queue', 'customers', 'guests']));
Blade Template
#foreach($queue as $quee)
{{ $customers->find($quee->user_id) ? $customers->find($quee->user_id)->name : $guests->find($quee->guest_id)->name }}
#endforeach
When I use this and the guest_id is blank I get an error stating "Trying to get property 'name' of non-object". How can I correctly detect which one to use?
I think so many problems with your code.
Firstly, $queue is findOrFail() which returns a single object data(not array or collection that can be used for foreach.) I think you need to change to get()
Also $customers and $guests are a collection, so you can not use find() method.
Then you didn't define $quee in the #foreach, so it's will give error result.
I think this code will return as you expected if you fix above problems:
#foreach($queue as $quee)
{{ \App\Customer::find($quee->user_id)->name ?? \App\Guest::find($quee->guest_id)->name ?? "no name" }}
#endforeach
But a better approach is using relation from your queue model:
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function guest()
{
return $this->belongsTo(Guest::class);
}
public function getNameAttribute()
{
return $this->customer?$this->customer->name:($this->guest->name??"no name");
}
and in the blade view
#foreach($queue as $quee)
{{ $quee->name }}
#endforeach
The issue turned out to be that one of my test data records didn't have a value in the guest_id when it should have, this caused the blade template to fail render.
i have a problem with my FAQ views. i want to display FAQ by categories like this:
Category1
FAQ1
FAQ2
FAQ3
Category2
FAQ1
FAQ2
FAQ3
Here is my Controller
public function faq()
{
$faq_category_vendor = DB::table('faq_categories')->where('categories_for','1')->get();
$faq_vendor = DB::table('faqs')
->join('faq_categories', 'faq_categories.id', '=', 'faqs.category')
->select('faqs.*','faq_categories.*', 'faq_categories.id as idcategory', 'faqs.id as id')
->where('faq_for','1')->get();
return view('owner.faq',['faq_category_vendor' => $faq_category_vendor,'faq_vendor' => $faq_vendor]);
}
Here is my Views :
#foreach($faq_category_vendor as $item)
For ({{$item->name}}) :
#foreach($faq_vendor as $item2)
#if ($item->id == $item2->category)
- {{$item2->ask}} : {{$item2->answer}}<br>
#else
#endif
#endforeach
<br>
#endforeach
The output is :
Facade\Ignition\Exceptions\ViewException
Trying to get property 'category' of non-object (View: C:\xampp\htdocs\weddinc\weddinc\weddinc_beta\resources\views\owner\faq.blade.php)
Can anyone help me?
Check if your faq_categories has id in faqs,becouse if don't you will get empty join so trying get
$item2->category
will throw exception.My proposition is do something like this in .blade
#php
try{
$testData=$item2->category;
} throw (\Exception $e) {
dd($item2);
}
#endphp
That will give you dd in blade so you will see if all records has joins
So there's a couple of points here which will help you out.
Your controller implies that you don't have relationships set up. Having relationships between your data will help you out massively; from what I can make out, you have a 1 to many relationship between faq_categories and faq (one faq_category has many faqs).
So, in your FaqCategory model:
public function faqs()
{
return $this->hasMany('app\faq');
}
In your Faq model:
public function category()
{
return $this->belongsTo('app\faq_category`);
}
Okay, so you said that you want to display each category, and then each FAQ under every category. In your controller, you can get all categories like so:
$categories = FaqCategory::all();
And in your blade, you can do this:
#foreach($categories as $category)
#foreach($category->faqs as $faq)
{{ $faq }}
#endforeach
#enforeach
I'm trying to get name of a user using the following code, but i'm getting an error. please help. The error is
"Trying to get property 'name' of non-object (View: /var/www/html/laravel/imarker/resources/views/student/exams/available.blade.php)"
#foreach($availableExams as $exam)
#foreach($exam->user as $user)
{{($user->name)}}
#endforeach
#endforeach
Exam Model
public function user(){
return $this->belongsTo('App\User');
}
User Model
public function exams(){
return $this->hasMany('App\Exam');
}
Controller
public function availableExams(){
$users = User::all();
$availableExams = Exam::all();
return
view('student/exams/available',compact('availableExams', 'users'));
}
Each Exam has one User and that User has a name? Try this:
#foreach($availableExams as $exam)
{{$exam->user->name }}
#endforeach
Got it. One user was missing. using an if statement to check if the object exists solves it. Using 2 arrows risks finding an empty item/object and that causes problems, hence the need for the condition clause. Thank you guys.
#foreach($availableExams as $exam)
{{$exam->user->name ?? 'No tutor found'}}
#endforeach
Update your blade file.
#foreach($availableExams as $exam)
{{ $exam->user()->first()->name }}
#endforeach
I use encrypt. I can display all table data. However I can'T get one record. I don't encrypt 'id'. I tried another column but same.
Here is my error
Trying to get property 'id' of non-object
Here is my code
blade file (I click this link first )
{{ $val->id }}
blade file (display page I got error at this page)
#foreach ($data as $val)
{{ $val->id }}
#endforeach
Trying to get property 'id' of non-object
web.php
Route::get('/one','MailController#onerecord');
Route::post('/one','MailController#onerecord');
Controller
public function onerecord(Request $request)
{
$id = $request['id'];
$data = Contact::where('id',$id)->get();
return view('mail.one', ['data' => $data]);
}
Could you teach me what is wrong my code please?
Use dd($data) after retrieving your Contact with Contact::where('id',$id)->get(); in order to investigate the content of $data. Most likely an object is returned and not an array, so looping through $data inside your blade #foreach will loop through the object's properties. Therefore $val->id isn't valid but the direct access of $data->id would be, without the need of looping through $data.
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.