How to query data from laravel relationship using vue.js? [ laravel, vue ] - laravel

I want to query my data in relationship using vue.js and still, I cant make it work.
Also, I got an errors like below.
[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"
When I changed my code like this
<span v-for="user in users">
{{ user.address.city }}
</span>
And in my Controller
public function index(Request $request)
{
$query = Customers::with('address')
->with('purchases')
->paginate(10);
return CustomersResource::collection($query);
}

<div v-for="user in users">
<span v-if="user.address && user.address.name">{{ user.address.name }}</span>
</div>
Always check if your object exists before accessing it.

Add withDefault after your relationship.
public function address(){
return $this->belongsTo('App\Address','user_id','id')->withDefault([
'name' => '-'
]);
}
There is existing code that depends on the result of any Eloquent relationship to either be null, a Model instance, or a Collection of Model instances. However, the current functionality of the withDefault() method opens up the potential for returning an object that is not one of those three expected values.

Related

How to fix Laravel resource is not working properly in blade view?

I'm confused why casted props are inaccessible in the blade file. When I try to check it in the controller its showing properly.
Here's the JSON shown in the browser: return $users; (here status is string)
But when I tried to show it in the view, the status goes back to int which is the original value.
#foreach ($users as $user)
<h1>{{ $user->status }}</h1>
#endforeach
And when I tried to dd in the blade view it shows the original model values.
Here's my resource file (shortened version):
public function toArray($request)
{
return [
'status' => StatusEnum::value($this->status),
...
];
}
Here's my controller look like:
public function index()
{
$record = User::all();
$users = UserResource::collection($record);
return view('pages.user.index', compact('users'));
}
I already tried solutions from other related QA e.g. ->resolve() but not working properly.
Make sure user model doesn't has getStatusAttribute() function nor status() if it returns a related model.
Keep in mind that this may be due to inherited or imported classes and traits in User model

How to dynamically switch between two arrays for attribute in my blade template

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.

How to get name from eloquent model classes to my view

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

How to display single encrypt record?

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.

Retrieving data from belongsToMany relationship in Laravel

I have some problems with getting data from my relationship. I need the tags of some domains.
$domains = Domains::where('customer_id', Auth::user()->customers_id)->get();
There are all the domains I need. On my Domains model I have this belongsToMany relation to my pivot table.
public function tags() {
return $this->belongsToMany('App\Models\Tags_Domains', 'domain_tag', 'domains_id', 'tags_id');
}
I was able to get all the datas from my relation with this:
dd($domains[0]->tags);
That gave me all the data I wanted but only for the very first domain. But I want this for every domain, to pass this new array to my Blade template. I tried many things out but couldn't make it work. ( $collection error, trying to get properly of non-object ... )
Can someone help me there?
Controller Code:
$domains = Domains::where('customer_id', Auth::user()->customers_id)->get();
return view('defaultLayout.domains.tagsdelete', [
'domains' => $domains
]);
This is because you use $domains[0] and you get the first domain.
You must loop through them:
foreach($domains as $domain) {
foreach($domain->tags as $tag) {
var_dump($tag);
}
}
Edit:
If you need the tags in your view here is how:
#foreach($domains as $domain)
<p>{{ $domain->name }}</p> //where name could be any field that $domain has
#foreach($domain->tags as $tag)
<p>{{ $tag->name }}</p> //where name could be any field that $tag has
#endforeach
#endforeach
Glad I was helpful :)

Resources