php - How to fetch data from multiple tables while exporting in laravel

I have two tables

  1. Accessory Request
  2. Accessory Details table

One accessory request can have multiple entries in accessory details table. I am trying to export the data but the data i am getting is from just accessory request table.

This is my controller code --

 public function export() 
    {
        return Excel::download(new AccessoryRequestExport, 'accessory.xlsx');
    }

and this is my AccessoryRequestExport Code --

<?php

namespace App\Exports;

use App\AccessoryRequest;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromArray;

class AccessoryRequestExport implements FromCollection, WithHeadings
{
   public function collection()
   {
       return AccessoryRequest::with('details')->get();
   }
   public function headings() : array
   {
       //Put Here Header Name That you want in your excel sheet 
       return [
           'id',
           'user_id',
           'store_id',
           'request_date',
           'status',
           'created_at',
           'updated_at', 
           'accessory_request_id',
           'vendor_id',
           'barcode',
           'description',
           'qty',
           'status'
       ]; 
   } 
}

I have listed the relation as "details" which is defined in my AccessoryRequest Model as written below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class AccessoryRequest extends Model
{
   protected $fillable = ['user_id', 'store_id', 'request_date', 'status'];

   public function user() {
       return $this->belongsTo('App\User', 'user_id');
   }

   public function store() {
       return $this->belongsTo('App\Store', 'store_id');
   }

   public function details() {
       return $this->hasMany('App\AccessoryRequestDetail');
   }
   public function vendor() {
       return $this->belongsTo('App\AccessoryVendor', 'vendor_id');
   }

}

Please help me with this---

  1. Accessory detail columns entries should be fetched while exporting the data
  2. There is column name as user_id in my accessory_request table, right now user_id is being fetched while exporting, if i want to display user_name which is there in user table, How can i do it?

Answer

Solution:

I don't now this Excel library, but maybe you need to use 'details.' syntax in headings for get values from relations. I mean 'details.vendor_id', 'details.barcode' and like that. For user you need to use AccessoryRequest::with('details', 'user')->get() and then, if 'details.' syntax works, you can use 'user.user_name' heading.

Source