Laravel 5 get relation data - php

I've made application with Laravel 5.5 and I use MySQL database. I have 2 tables
people: id, name, homeplanet_id
planets: id, name
And foreign key people.homeplanet_id references planets id
I also have 2 models: Person and Planet, and PersonController.
I can get Person's data in controller by using
Person::find($id)->getAttributes()
but it is like
[
id => 1
name => Name
homeplanet_id => 1
]
How can I get data look like next
[
id => 1
name => Name
homeplanet_id => Planet_name
]

You may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users.
https://laravel.com/docs/5.5/eloquent-resources
So, if you want to get JSON, use resources. If you want this data format for Blade views, it's a bad idea to transform it. Just work with the data in Blade template:
{{ $person->name }} lives on the planet {{ $person->planet->name }}
Where planet is name of relationship defined in Person model:
public function planet()
{
return $this->belongsTo(Planet::class, 'homeplanet_id')
}

Use with() method,
Something like
$person = Person::where(array())->with('planet')->get(); //You can fetch all related data by passing multiple values for method with()
To print
{{$person->planet->name}} //where planet indicated the relation on person model as follows
Where planet indicated the relation on Person model.
In our case
Getting data
$person = Person::where(array('id'=>$id))->with('planet')->get();
And in Person model do something like following to fetch planet using with() method:
Person extends model{
public function panet(){
//your relation one to one, one to many etc.....whatever
}
}
Try exploring eager loading in Laravel (eloquent) and scoped query too.
Visit the link for Eager loading and everything will be done by the ORM itself.Link

Related

Get number of count of a value in database table in Laravel

Good day. I am building an API, in which I want to return some data. I have three tables
counsels
counsel_cases
analysis_sc
A section of the counsels table is shown below
A section of the counsel_cases is also shown below
Finally, a section of the analysic_sc is shown below.
I want that when a counsel is selected, through the counsel_id, I can fetch the cases belonging to the counsel from the counsel_cases, and then with that information, I want to be able to fetch the number of cases of such a counsel belonging to a legal head (area of practice) on the third table as shown in the design below.
How will that be possible. I have a relationship between counsel and counsel_cases though. Also, I have tried using a foreach loop as shown below, but I am unable to get the unique values of the legal_head.
public function getCounselPracticeAreas(Request $request)
{
$counsel_id = $request->route('counsel_id');
$cases = CounselCase::select('suit_number')->where('counsel_id', $counsel_id)->get();
$data = [];
foreach ($cases as $case) {
$values = AnalysisSc::select('legal_head')->where('suitno', $case->suit_number)->first();
array_push($data, $values);
}
return response()->json([
"message" => "successful",
"data" => $data
]);
}
However, this is the value I get
[![enter image description here][5]][5]
I want to get something like this:
$data : [
"legal_head" : [
"name" : "Criminal Law",
"count" : 2
]
]
Please, is this possible
I know this is quite long. And I hope I explained myself well. Thanks
you need to use SQL Joins to create a relationship between the tables and fetch the data
It looks like you're skipping using relationships in your models. Once you have your models set up, retrieving the data you need will be a lot easier with Laravel. You may want to separate your models/tables a little more and add relationships, like the following:
Models/tables:
Counsel (counsels)
id
name
LegalHead (legal_heads)
id
name
Case (cases)
id
suit_number
year
subject_matter
legal_head_id
case_counsels (This is not a model, just a relationship table)
id
case_id
counsel_id
appearing_for
role
Note: I wasn't sure how your data is structured. You can use this as start and adjust as necessary.
Relationships
The Many-Many relationship is suitable for the case counsels and you'll be able to add the role as a pivot(extra field) for the relationship.
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many
Case
legal_head: belongsTo
counsels: belongsToMany with pivot for role
Counsel
cases: belongsToMany with pivot for role
Retrieving the Objects
When that is set up, you won't have to do as much query work. You can do this to get case data with counsels, legal_head and their role for each case:
$cases = Case::with('counsels','legal_head')->get();
And this to get the Legal Head names with the number of cases:
$legal_heads = LegalHead::withCount('cases')->get();

Laravel 6.x right way to handle Pivot tables

I want to connect my Customer model with my CustomerGroup model in Laravel using Pivot tables.
I tried it with the following: (as reference I used https://ben.lobaugh.net/blog/204838/how-to-use-custom-pivot-tables-in-laravel-6-x but I could have made something wrong)
I created the migration customer_group_customer and in the scheme I added following:
$table->unsignedBigInteger("customer_group_id");
$table->unsignedBigInteger("customer_id");
In the models Customer and Customer_groups I added a function. The function is like the following (this is the Customer model for example):
public function groups(){
return $this->belongsToMany("App\CustomerGroup","customer_group_customer","customer_id","customer_group_id");
}
Then I created a customer and a Group and then connected them manually with:
DB::table("customer_group_customer")->insert(["customer_group_id" => $group->id, "customer_id" => $customer->id]);
After that I fetched all Customers and saw that there aren't connected (via dd() I couldn't see any entry on groups or similar):
$customer = \App\Customer::create([]);
$group = \App\CustomerGroup::create(["name" => "hey"]);
DB::table("customer_group_customer")->insert(["customer_group_id" => $group->id, "customer_id" => $customer->id]);
dd(\App\Customer::first());
How do pivot tables get setup correctly?
And is there a better way to create a customer and assign it a group, without making it manually with the DB facade?
The reason your not seeing the groups relationship when you dd() the Customer is because it hasn't been loaded.
You can load the relationship by using with() when querying the model, or load() after you have an instance of the model, or simply by accessing the relationship as a property e.g. $customer->groups;
Eloquent Eager loading documentation
You can also use the relationship to attach different relations rather than using the DB facade to do it manually:
$customer = \App\Customer::create([]);
$group = \App\CustomerGroup::create(['name' => 'hey']);
$customer->groups()->attach($group);
dd($customer->groups);
Attaching / Detaching Documentation

laravel eloquent - match data stored within array

I have a multiselect form to store multiple client_id in contact table:
{!! Form::select('client_id[]', $clients, null, ['multiple'=>true]) !!}
When I show an individual client, I wish to show the related contacts.
My client Model has as a 1:many relationship defined as:
public function contact()
{
return $this->hasMany('App\Models\contact');
}
usually, for non array items, I would use:
$contacts = $client->contact()->get();
to fetch related contacts, but as the client_id is stored as an array in my contact table, how to I fetch this data?
I really think you just want this:
$contacts = $client->contact()->lists('id', 'name')->toArray();
Note that you didn't specify your version of Laravel, but in 5.1+ lists returns a Illuminate\Support\Collection instance, but in previous versions it returns an Array.
Sidenote
Your hasMany relationship should be defined as plural and not singular:
public function contacts()
This is by no means a requisite, but it better defines your relationship type.

Getting data from a linked CakePHP3 entity

I have a User entity with a hasMany relationship to Profile via a user_id foreign key.
Within my User class I'm trying to create a virtual field so I can access the name property of the linked Profile entity
protected $_virtual = ['profile_name'];
protected function _getProfileName()
{
return $this->profile->name;
}
Whatever I try I get Trying to get property of non-object
I've also tried:
$this->_properties['profile']->name;
$this->profile->_properties['name'];
I know I can get this data by building a query up using Cake\ORM\Table but I has hoping to aovid that.
What am I doing wrong?
p.s. there is definitely linked data between the two tables.
The answer seems to be
That's not how it works
Instead, use 'eager loading' to get the linked entity data. That is to say use the contain method when using find():
e.g.
$users = TableRegistry::get('users');
$query = $users->find('all', ['contain' => ["Profiles"]])
->where(['id' => $userId])
->first();
or on the query object itself:
$query->contain(['Profiles']);
In this example $query will contain Profile entity objects along with the User entity
i.e. $query->profiles is an array of Profile entities

Laravel eager loading, loaded table fields

how can I choose which fields I want to get from the with ORM eloquent. For example
$tourTeams = Tournament::with('teams')->where('id', $tourId)->first();
From the teams relation I want only to get the name (without the id and timestamps).
I didn't it in the documentation. For the Tournament eloquent I can do it via the get function while passing it an array of fields names, like this: get(array('name', 'id')). But how do I do this on the Team eloquent?
Note: here is how Team related to Tournament, this code taken from the Tournament eloquent file:
public function teams()
{
return $this->belongsToMany('Team', 'Tournament_Team');
}
You can get specific columns from the relation like this:
$tourTeams = Tournament::with(['teams'=>function($q){
$q->select('id','name');
}])->where('id', $tourId)->first();

Categories