Laravel passing variable from multiple models - laravel-5

I have 2 models
User
Customer
Each user hasMany customers (aka Accounts)
the user model has
public function customer() {
return $this->hasMany('App\Customer', 'id','customer_id');
}
but when i try to output this:
$user->customer->name
i get an error saying:
Undefined property: Illuminate\Database\Eloquent\Collection::$name
When i use this one, i get the entire customers record output in JSON.
$user->customer
So the relationship is working, but obviously i am missing something. I was sure this was the right way to do it. I swear this worked in Laravel4.2 but now that I'm in Laravel 5 it doesn't.

As the error and the below link says, It is returning a collection (hasMany) not a single object, you need to either loop over the collection or do direct access in the collection based on the index.
that is to say... does doing this work?..
$user->customer[0]->name
http://laravel.io/forum/04-10-2014-undefined-property-illuminatedatabaseeloquentcollectionitem

You should loop over customers, if you want display customers in laravel view you can do the following
#foreach
($user->customer as $cust)
{{$cust->name}}
#endforeach

Related

How to Get Order Details per a single User in Laravel 7

I am making a multi-vendor ecommerce website using Laravel 7. I am trying to make an Order History page where in a single can user can view only his/her own orders. I am having a problem building the query on my OrderHistoryController. These are the codes on my controller:
$users = User::get();
$orders = Order::find($users);
return view('order-history', compact('orders'));
And I'm trying to loop $orders on my blade file. I have:
#foreach ($orders as $order)
<div>{{ $order->id}}</div>
<div>{{ $order->grand_total}}</div>
#endforeach
I am trying to pass the order id and order grand total to my view. I don't get any error however it shows a different order details from a different customer. How do I do this?
You should use MySQL (or any other database you are using) table relationships and foreign keys.
So, your orders table, should have columns id, user_id, date, and so on. The important thing is user_id column. You want to make that column a foreign key. That basically means that user_id will hold an id value from another table, in this case user. See how to make foreign key columns in laravel migrations here.
Next up is to use Laravel's built in model relationships. You can read more about them here. Basically, in your orders model you want to have a function user which returns $this->belongsTo(App\Models\User::class) and in your user model you want to have a function orders which returns $this->hasMany(App\Models\Order::class) (or whatever the namespace is for both of them).
That way, you can call $user->orders and get a collection of Order models which will contain only the orders of that particular user.
Definitely read the documentation carefully and learn basic concepts of the framework first and how relational databases function!
You can get a lot of this information just by googling it or reading the documentation of Laravel or any other framework you plan on using! Good luck learning :)

Query builder on hasMany relation

Problem
I'm creating an API with Laravel. Every server can have more than one contact, and every contact belongs to one server - as such, contacts are set up with a belongsTo relationship, and servers have a hasMany relationship to the contacts.
A user can have many servers via its hasMany relationship. Thus, when creating a server, we simply invoke $user->server()->create([values]), which works just fine.
The issue is that when we try to invoke it further, as with contacts - we hit a wall where we get:
Call to undefined method Illuminate\Database\Query\Builder::contacts()
When using: $user->server()->contacts()->create([]).
The method does exist in the server model.
We also have a hasManyThrough relationship on the user model, specifying that a user has many contacts through servers.
When calling $user->contact()->create([]), we instead get:
Call to undefined method Illuminate\Database\Query\Builder::create()
Does anyone have a clue what might be causing this? Do query builders not allow for this type of chaining, or am I missing something blatantly obvious? As you can see, I've tried a few different methods but can't seem to produce a working result.
Cheers!
As you said:
A user can have many servers via its hasMany relationship.
so You cannot build another relation on relation that can return many results (becasue at the end we don't know exacly which server id we should set in contact new record).
So what you can do is to itterate over:
foreach ($user->server as $server) {
$server->contacts()->create($values);
}
You see: now you have specific server with id to put into new contact record.

Can't access custom pivot element (Laravel framework)

I created a relation between User and Event. I added a pivot element 'part_sure' to the pivot table and updated the models appropriately:
Now I have a problem with accessing this pivot element. If I try to do this...
... it doesn't display anything! No error but also no value.
Looking with this command...
... what is accessable in the pivot element:
As you can see, the part_sure element is not there.
My user model:
My event model:
I really don't know why this isn't working. Tried to google it for almost an hour. I would be really happy if somebody could give me a hint!
You're calling the events method from the User model, but you aren't showing us the User model.
What does your User model look like? Just like you did with the Event model, you need to specify the extra pivot column in the User model.
User model
public function events() {
return $this->belongsToMany('radclub\Event')->withPivot('part_sure');
}
You may need to edit radclub\Event with the proper namespace.

Retrieve selected keys from database from relations

I am using laravel 4 and I have to retrieve registrations and all users associated with that registrations but user table has lot more keys but I only need 3 keys so how can I get selected keys. I know laravel provide select method but its not working on relations.
Registration::where('section_id', '=', $key->id)
->with('user')
->select('users.id', 'users.name')
->get();
I tried users and user but nothing works. Could someone please post correct way to load this query.
Edit:
- Registration has one user
- Registrations has one section
I have registration table that contains section id and user id. I want to get all users, signed up for particular section. So this is very simple query and its working fine only problem is retrieving selected keys from database.
In your Registration model change your relation to this
public function user()
{
return $this->hasOne('User')->select('id','name');
}
And in your controller write this
Registration::where('section_id', '=', $key->id)->with('user')->get();
Hope this work for you.

laravel checking pivot returns error contains() on a non-object

Background:
What I am doing is I have made a page displaying a table with checkboxes for attendees and events. It was working until I tried to check my checkboxes based on a query through a pivot table through a belongs to many relation.
I have looked at some other threads and tried the same approach to check a pivot for existing entry data. I am using the contains() function to see if my attendee and scheduled_program_segment are matched, but for some reason my code gets this error.
Problem:
I get the error Call to member function contains() on a non-object.
Here is the bit of my code I think is relevent
#foreach( Auth::user()->attendee as $attendee )
<td class="col-lg-1">
{{
Form::checkbox(
($program->name . $attendee->first_name),
'1',
$attendee->scheduled_program_segments->contains($attendee->id)
)
}}
I tried changing to $attendee as well. Same error.
Also, when I run
{{$attendee->scheduled_program_segments()->get()}}
I get the following which I am assuming means I have the pivot table and model set up correctly, but it's not working so maybe I am wrong here.
[{"id":"1","created_at":"2014-11-14 15:19:44","updated_at":"2014-11-14 15:19:44","name":"Minecraft","description":"","date":"2014-11-06","cost":"20.00","start_time":"16:30:00","end_time":"17:30:00","location":"Cookstown","scheduled_program_id":"1","program_segment_id":"1","pivot":{"attendee_id":"1","scheduled_program_segment_id":"1"}},{"id":"1","created_at":"2014-11-14 15:19:44","updated_at":"2014-11-14 15:19:44","name":"Minecraft","description":"","date":"2014-11-06","cost":"20.00","start_time":"16:30:00","end_time":"17:30:00","location":"Cookstown","scheduled_program_id":"1","program_segment_id":"1","pivot":{"attendee_id":"1","scheduled_program_segment_id":"1"}}]
$attendee->scheduled_program_segments
is a m-m relation, so obviously it returns null, because Laravel 4+ relations need to be camelCased in order to work as dynamic properties (that is what you're trying to do).
So you can either rename your relation to scheduledProgramSegments() and then call it:
$attendee->scheduledProgramSegments
// or
$attendee->scheduled_program_segments // yes, this will work as well
or change that line as follows (which I'd rather not suggest):
$attendee->scheduled_program_segments()->get()->contains(...)

Resources