Getting extra fields from laravel api having belongstomany relationship - laravel

I have two data tables related to each other by the belongstomany relationship. And when I am fetching data from its api controllers with selecting only two column keys ['id','title'] yet it returns some extra data in the response object.
modelcode:
public function place(){
return $this->belongsToMany(Place::class,'city_place')->select(array('id', 'title'));
}
controller code:
public function ofcity($id)
{
$city=City::findOrFail($id);
return new CityResource( $city->place()->get());
}
enter image description here

You must indicate the name of the table in front of the fields.
model Place code:
protected $columns = ['places.id', 'places.title']; //all column for select
public function scopeExclude($query, $value = [])
{
return $query->select(\array_diff($this->columns, (array) $value));
}
model City code:
public function place()
{
return $this->belongsToMany(Place::class,'city_place', 'city_id', 'place_id');
}
controller code:
public function ofcity($id)
{
$cities = City::findOrFail($id)->place()->exclude(['featured_image'])->get()->toArray();
return response()->json(['cities' => $cities], 200);
}
In exclude skip all the fields that need not to be shown.

Thanks everyone here helping me out but none of the above solution worked..I figured it out after trying different functions and spending hours on this.
model Place code:
public function place(){
return $this->belongsToMany(Place::class,'city_place','city_id','place_id')->select(array('places.id', 'places.title'));
}
controller code:
public function ofcity($id)
{
$city=City::findOrFail($id);
return new CityResource( $city->place()->get()->map(function ($item,$key) {
return ['id' => $item['id'],'title'=>$item['title']];
})
);

Related

nested query with laravel model

I am writing a nested query with Laravel.
Namely First, the Truck information is drawn, then I list the data of the vehicle with "truck_history", there is no problem until here, but I want to show the information of the invoice belonging to the "invoice_id" in truck_history. but I couldn't understand how to query, I want to do it in the model, is this possible? If possible, how will it be done?
"ID" COLUMN IN INVOICE TABLE AND "invoice_id" in "InvoiceDetail" match.
TruckController
public function getTruck($id)
{
$truck = Truck::with(['truckHistory'])->find($id);
return $truck;
}
Truck Model
protected $appends = ['company_name'];
public function companys()
{
return $this->belongsTo(Contact::class, 'company_id', 'id');
}
public function getCompanyNameAttribute()
{
return $this->companys()->first()->name;
}
public function truckHistory(){
return $this->hasMany(InvoiceDetail::class,'plate_no','plate');
}
So you can add another relationship in the InvoiceDetail::class and add in the truck history.
try something like this:
public function truckHistory(){
return $this->hasMany(InvoiceDetail::class,'plate_no','plate')->with('Invoice');
}
Simply add the following relations (if you don't already have them):
Invoice model :
public function truckHistory()
{
return $this->hasOne(InvoiceDetail::class);
}
InvoiceDetail model :
public function invoice()
{
return $this->belongsTo(Invoice::class);
}
And you can get the relation invoice of the relation truckHistory adding a point as separator :
public function getTruck($id)
{
$truck = Truck::with(['truckHistory.invoice'])->find($id);
return $truck;
}

Populating a pivot table with Laravel/Eloquent

I have 8 tables: products, pests, actives, crops, active_product, pest_product, crop_product, and active_pest
I've built a form that loads information about a selected (agrichemical) product - in that form, the user selects the pests, actives, and crops associated with that product. When submitted, my existing code is saving the expected information in the products table and, through a set of "belongsToMany" relationships, the active_product, pest_product, and crop_product pivot tables are also correctly updated.
My problem is that I do not know how to use the actives and pests information (i.e. their respective id values) to add to/update the active_pest table.
I'd appreciate some direction.
The methods in my models are as follow:
product
public function Actives()
{
return $this->hasMany('App\Models\Active','active_product', 'product_id', 'active_id');
}
public function pest()
{
return $this->belongsToMany('App\Models\Pest','pest_product', 'product_id', 'pest_id');
}
public function active()
{
return $this->belongsToMany('App\Models\Active','active_product', 'product_id', 'active_id');
}
active
public function product()
{
return $this->belongsToMany('App\Models\Product', 'active_product', 'active_id', 'product_id');
}
public function pest()
{
return $this->belongsToMany('App\Models\Pest', 'active_pest', 'active_id', 'pest_id');
}
pest
public function active()
{
return $this->belongsToMany('App\Models\Active', 'active_pest', 'pest_id', 'active_id');
}
public function product()
{
return $this->belongsToMany('App\Models\Product','pest_product', 'pest_id', 'product_id');
}
public function crop()
{
return $this->belongsToMany('App\Models\Crop','crop_pest', 'pest_id', 'crop_id');
}
I am using BackPack for Laravel - my Product controller contains this function for updating:
public function update(UpdateRequest $request)
{
$redirect_location = parent::updateCrud($request);
return $redirect_location;
}
updateCrud is
public function updateCrud(UpdateRequest $request = null)
{
$this->crud->hasAccessOrFail('update');
$this->crud->setOperation('update');
// fallback to global request instance
if (is_null($request)) {
$request = \Request::instance();
}
// update the row in the db
$item = $this->crud->update($request->get($this->crud->model->getKeyName()),
$request->except('save_action', '_token', '_method', 'current_tab', 'http_referrer'));
$this->data['entry'] = $this->crud->entry = $item;
// show a success message
\Alert::success(trans('backpack::crud.update_success'))->flash();
// save the redirect choice for next time
$this->setSaveAction();
return $this->performSaveAction($item->getKey());
}
Thanks, Tom
you can use laravel's attach method like this:
$actives = App\Active::create([
'someColumn' => 'test',
'anotherColumn' => 'test',
]);
$pests = App\Pest::create([
'someColumn' => 'test',
'anotherColumn' => 'test',
]);
$actives->pest()->attach($pests);
^^^-relation name in model

Laravel: Retrieve data inputted by user

I'm quite new to Laravel and I'm confused with how I have to retrieve data inputted by certain users.
In my project, there is a user profile that should display all form submissions by the user.
Here is my controller function:
public function clientAccount(BookingRequest $bookings)
{
$client = Client::whereUserId(Auth::id())->with('user')->first();
$bookings = BookingRequest::with(Auth::id())->with('client')->first(); //unsure about here//
return view('client.account', compact('client','bookings'));
}
Here is my model:
public function client()
{
return $this->belongsTo('App\Client', 'client_id', 'user_id');
}
How do I fix this?
EDIT:
I tried using this but somehow I don't get any display
$bookings = BookingRequest::where('client_id',Auth::id());
If the relationship needs to be one to many meaning one Client has many Bookings, than in your Client model you should have the following function:
public function bookings()
{
return $this->hasMany(BookingRequest::class);
}
then you just need to find the client, and for him you just use
$client->bookings()
it will list all the bookings for that client.
Following on from nakov:
public function clientAccount()
{
$client = Client::whereUserId(Auth::id())->with('user')->first();
$bookings = $client->bookings();
return view ('client.account')->with('bookings', $bookings)
}
And in your user profile view:
foreach($bookings as $booking){
// do something with each booking
// e.g. var_dump($booking) to see the data you're working with
}
Thanks for all your responses!
I'm now able to retrieve data by using this:
public function clientAccount()
{
$client = Client::whereUserId(Auth::id())->with('user')->first();
$bookings = $client->booking()->with('client')->get();
return view('client.account', compact('client','bookings'));
}
and in my model, I used this instead
public function booking()
{
return $this->hasMany('App\BookingRequest', 'client_id', 'user_id');
}

Defining relationship on pivot table elements in laravel

I'm building a small application on laravel 5.4 where I'm having following models and relationship:
Interaction Model:
public function contactsAssociation()
{
return $this->belongsToMany('App\Contact', 'contact_interaction', 'interaction_id', 'contact_id')->withPivot('company_id')->withTimestamps();
}
Contact Model:
public function company()
{
return $this
->belongsToMany('App\Company', 'company_contact','contact_id', 'company_id')->withTimestamps();
}
and Company Model:
public function contacts()
{
return $this->belongsToMany('App\Contact', 'company_contact', 'company_id','contact_id');
}
Now I'm fetching some data something like this:
$tempData['contacts'] = $interaction->contactsAssociation()->with('company')->get();
I want to extract company data from the pivot table which is mentioned in the relationship. Currently I can't find solution so I have to do:
$tempData['contacts'] = $interaction->contactsAssociation()->get();
$companies = [];
foreach($tempData['contacts'] as $contact)
{
$companies[] = Company::find($contact->pivot->company_id);
}
$tempData['company'] = $companies;
Guide me on this, thanks,
You can pass an array to the withPivot() function with every field you want to retrieve:
public function contactsAssociation()
{
return $this->belongsToMany('App\Contact', 'contact_interaction', 'interaction_id', 'contact_id')
->withPivot(['company_id', 'other_field'])
->withTimestamps();
}
Hope this helps you.

Laravel 4 Eloquent relations query

I have a project with main table 'Qsos' and bunch of relations. Now when I try to create advanced search I don't really know how to query all relations at the same time. Qso model has following:
public function band()
{
return $this->belongsTo('Band');
}
public function mode()
{
return $this->belongsTo('Mode');
}
public function prefixes()
{
return $this->belongsToMany('Prefix');
}
public function user()
{
return $this->belongsTo('User');
}
public function customization() {
return $this->hasOne('Customization');
}
Then I have SearchController with following code that has to return collection of all Qsos following required conditions:
$qsos = Qso::withUser($currentUser->id)
->join('prefix_qso','qsos.id','=','prefix_qso.qso_id')
->join('prefixes','prefixes.id','=','prefix_qso.prefix_id')
->where('prefixes.territory','like',$qTerritory)
->withBand($qBand)
->withMode($qMode)
->where('call','like','%'.$input['qCall'].'%')
->orderBy('qsos.id','DESC')
->paginate('20');
And then in view I need to call $qso->prefixes->first() and $qso->prefixes->last() (Qso and Prefix has manyToMany relation) but both return null. What is wrong?
Here is the eloquent code that I found working but taking VERY long time to process:
$qsos = Qso::withUser($currentUser->id)
->with('prefixes')
->withBand($qBand)
->withMode($qMode)
->where('call','like','%'.$input['qCall'].'%')
->whereHas('prefixes', function($q) use ($qTerritory) {
$q->where('territory','like',$qTerritory);
})
->orderBy('qsos.id','DESC')
->paginate('20');

Resources