Laravel eloquent: Save data with relationship - mysql

I created an invoice form which has a section where users can dynamically add (via jquery row add) items to be invoiced.
I need to save these data into two tables: Invoice and Invoiceitems. The two tables have one to many via MySQL relationship and Laravel models have hasMany and belongsTo relation assigned.
My question is how to save the data into Invoiceitems table.

In your App\Invoice, define your relationship with App\InvoiceItem as follows:
public function items()
{
return $this->hasMany(InvoiceItem::class);
}
In your App\InvoiceItem model, define your relationship with App\Invoice as follows:
public function invoice()
{
return $this->belongsTo(InvoiceItem::class);
}
To create an Invoice with many InvoiceItem, you would then do something like this:
$invoice->items()->saveMany([
new App\InvoiceItem(['title' => 'iPhone X']),
]);
Read more about Eloquent Relationships.

Related

How to concat two tables into one row with validations (Lumen, Laravel)

I'm using Laravel and I'm trying to return this on API:
{
id: 1
name: BOM DIA
},
id: 2
name: BOM DIA (SUPERM VANEZA, BATISTA & IZEPE, BOM DIA)
}
But I'm confused. I have a table named 'Teams', and at this table, some columns have a number 'biid'. This 'biid' is the same information from another table name 'Clients'.
More than one 'Clients' can have same 'biid', but 'Teams' only have unique 'biid' or don't have any 'biid'.
I wanna to concat 'Teams' who has 'biid' with column named 'slug' in table 'Clients'.
Tables:
This should be like this:
How can I even think in make this?
Hello you need relations to do it if i know your problem
so let's talk about relation in your case Teams as many clients
the relation in your model teams will be this:
public function client(){
return $this->belongsToMany(Client::class);
}
What laravel does with belongsToMany method ?
for each client who as the same id's who you references teams and laravel will add it to you Eloquent Object.
Your client has one teams
soin your client model if you named it client :
public function team(){
return $this->belongsTo(Model::class);
}
to get the detail of relation who you need :
you will need to make the relations request, this will contribute to remove n +1 problem:
$clients = Client::with(['team']);
$teams = Team::with(['client']);
// here i don't know if you need ->get() try without and with
To access the relations:
foreach($clients as $client){
echo $client->team->name;
}
foreach($teams->client as $team){
echo $team->name;
}
// or
foreach($teams as $team){
echo $team->client->name;
}
But i think for that you need to rename you column because that are not explicit for laravel
to access relations you column need to have client_id and team_id to work.

How to get object of object within an object through laravel model

I am making Web App in laravel 5.2....I have patient data stored in patient table(Patient Table does not contain doctor and area of treatment data) in database and then i have billing table which contains the data of patient's billing.In Billing table i want to retrieve the data from two columns(doctor_id and area_of_treatment_id) like i retrieved billing by defining relation in Patient Model...
I have already retrieve the patients along with their billing but i also need the doctor and area of treatment tables data by using their id stored in billing table....I have defined the relation of billing in Patient Model..Please help me to resolve my problem
Billing relation in Patient Model:
public function billing()
{
return $this->belongsTo(Billing::class,'mr','mr');
}
Patient Controller:
$patients = \App\Patient::with(['billing'])->get();
Patient Data along with billing:
You should also define the relations in Billing model:
public function doctor()
{
return $this->belongsTo(Doctor::class);
}
public function areaOfTreatment()
{
return $this->belongsTo(AreaOfTreatment::class);
}
Then you can eager load the objects with nested eager loading:
$patients = \App\Patient::with(['billing', 'billing.doctor', 'billing.areaOfTreatment'])->get();
Ref: https://laravel.com/docs/5.5/eloquent-relationships#eager-loading

Relationships between tables in laravel using backpack package

I am using backpack CRUD package to create my website project in laravel 5.2
I want to establish a relationship between two tables. First table is called customer and second table is called transaction. Each customer has many transaction(1:N relationship).
Customer table record:
ID Name
123456 xyz
Transaction table record:
ID CustomerID
101010 123456
I know that I have to specify the relation in the customer model. But, how can I display the result of the relationship in CRUD ?
You should have relationships on both the Transaction and the Customer models, so you can do $customer->transactions and $transaction->customer:
class Customer extends Model
{
/**
* Get the comments for the blog post.
*/
public function transactions()
{
return $this->hasMany('App\Transactions', 'CustomerID', 'ID');
}
}
and
class Transaction extends Model
{
/**
* Get the comments for the blog post.
*/
public function customer()
{
return $this->belongsTo('App\Customer', 'CustomerID', 'ID');
}
}
Spend some time in the Eloquent Relationships Documentation. It's really important to understand them if you want to be a Laravel developer.
In order to display the relationship in the CRUD, you can then use Backpack's select column type to display it in the table view and select or select2 field types to display it in the add/edit views. Read the CRUD Example Entity to better understand how that works.
First of all when you are creating migrations for both tables, table which contain Foreign Key (FK) must have field like this:
public function up(){
$table->increments('id');
$table->integer('customerID')->unsigned();
}
After that you are need to call next command into console
php artisan migrate
Next is going next commands:
php arisan backpack:crud customers
php arisan backpack:crud transactions
After that you need to define functions in models which returns values from other tables. Customer models need to have next function
public function transactions(){
return $this->hasMany('Transaction');
}
Transaction model must have next function
public function customer() {
return $this->belongsTo('Customer');
}
Next you must add CRUD field in Customer controller to display
transactions in select box.
$this->crud->addField([
'label' => 'Transactions', // Label for HTML form field
'type' => 'select2', // HTML element which displaying transactions
'name' => 'customerID', // Table column which is FK for Customer table
'entity'=> 'customer', // Function (method) in Customer model which return transactions
'attribute' => 'ID', // Column which user see in select box
'model' => 'Transaction' // Model which contain FK
]);
Hope this helps :)
After you built onetomany relationship with transaction, you can get the results.
$customer=Customer::where(['id'=>'123456'])->with('transaction')
->first();
print_r($customer->Name); // gives the customer name
foreach($customer->transaction as $cid)
{
print_r($cid->CustomerID); // gives the customer id
}
Laravel Relationships Documentation is always helpful. Go through it.

Laravel 5.2 How to get values from two or more table from a relationship

I have a default authentication table user and another table user_profiles
user(id,email,password)
user_profiles(id,first_name,last_name,mobile)
i am connecting these two table using a many-to-many relationship
for this, i added relationship in the both model class- User and UserProfile
// User Model
public function userProfiles()
{
return $this->belongsToMany('App\Models\UserProfile', 'user_user_profile',
'user_profile_id', 'user_id');
}
//UserProfile Model
public function users()
{
return $this->belongsToMany('App\User', 'user_user_profile',
'user_profile_id', 'user_id');
}
and i tried to access the UserProfle details via user table using
$user=\App\User::find(1)->userProfiles()->get();
but not working and also tried
/$user = \App\User::findOrFail(1)->with('userProfiles')->get();
that is also not working , please help to
Get the user_profile table details along with user table
How to access the Pivot table(user_id,user_profile_id) value
How to display these data from multiple tables into a view form?
You have defined the relationship wrong in your User Model: swap user_id and user_profile_id
// User Model
public function userProfiles()
{
return $this->belongsToMany('App\Models\UserProfile', 'user_user_profile',
'user_id' , 'user_profile_id');
}

Laravel inserting into a three-way pivot table

Summary
I am building a music discovery service. My question is: How do I insert data into the three-way pivot table Tag_Track_User ?
Schema
I have this schema seen here at LaravelSD
It comprises of six main tables (and a few others):
Artists, Albums, Tracks, Tags, Users and Tag_Track_User
The Artists->Albums->Tracks relationship is straightforward and as you'd expect.
Tags, Tracks and Users all relate to one-another as no two can exist without the third.
Relationships
Artists hasMany() Albums
Albums hasMany() Tracks and belongsTo() an Artist
Tracks belongsTo() Albums
Tracks belongsToMany() Tags and belongsToMany() an Users
Tags belongsToMany() Tracks and belongsToMany() an Users
Users belongsToMany() Tags and belongsToMany() an Tracks
Models
User model
public function tags()
{
return $this->belongsToMany('Tag', 'tag_track_user', 'user_mdbid', 'tag_mdbid')->withPivot('track_mdbid');
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tracks()
{
return $this->belongsToMany('Track', 'tag_track_user', 'user_mdbid', 'track_mdbid')->withPivot('tag_mdbid');
}
The Tag and Track model contain the same respective relationships.
Question
So my question is:
How do I insert data into the Tag_Track_User table? The tag_track_user table is a 3-way pivot table cointaining information about tracks that users have tagged.
You have to be logged in to tag a track (which means I have access to the user’s ID). The tracks ID is accessed as I am displaying it on the page where the form is contained. The tag on the other hand; if it already exists in the tags table, I want to get it’s ID and re-use that (as they are unique), if not, I want to create it, assign it an ID and insert that into the tag_track_user_table.
I need to check whether the Tag exists
If it does, get it's ID
Insert data into the Tag_Track_User table
Thank you
Any help I receive on this, is greatly appreciated.
Well:
$tag = Tag::firstOrCreate(array('text' => $tag_text));
TagTrackUser::create(array(
"tag_mdbid" => $tag->mdbid,
"track_mdbid" => $track->mdbid,
"user_mdbid" => Auth::user()->mdbid
));
Something like that? firstOrCreate does what the name says it does, the rest is pretty straightforward Eloquent.
Since seems that there is not an appropriate pattern in Laravel, the cleaner and easier way is to implement any three-pivot-relationships via a model dedicated to the pivot table:
class Track
public function trackTags()
{
return $this->hasMany('TagTrack');
}
...
class Tag
public function tagTracks()
{
return $this->hasMany('TagTrack');
}
...
class TagTrack
public function track()
{
return $this->belongsTo('Track');
}
public function tag()
{
return $this->belongsTo('Tag');
}
public function anotherRelationship(){
...
}
You can do:
$track->trackTags->myCustomPivotDataAndRelationship()
and in TagTrack you have freedom to add as many relationship and field I want
Note than you can still keep the many to many to use when you don't need to access pivot relationships