how can export to excel from two tables have relationship (belongsTo) in laravel 8

I have order and user tables and the order table has a relationship (belongsTo) with user table via id_user column and when I export the data from order table user.name does not appear.

Here is the structure of the order table.

order table

I wanna appear when export to excel like this

expected result

OrderExport

<?php

namespace App\Exports;

use App\Models\Order;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class OrderExport implements FromCollection, WithHeadings
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        ## 1. Export all data
        // return Order::all();`

        ## 2. Export specific columns
        // $a = User::select('name')->get();
        return Order::select('id', 'user_id', 'phone', 'date', 'time', 'order_description')->get();
    }

    public function headings(): array
    {
        return [
            '#',
            'user_id',
            'phone',
            'date',
            'time',
            'order_description'
        ];
    }
} 

Order Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    use HasFactory;
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
} 

User Model

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'employee_number',
        'password',
        'is_admin'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
} 

export Route

//export to excel
Route::get('order/exportexcel', [HomeController::class, 'exportExcel'])->name('order.exportexcel');`

button export in Adminpage.blade.php

<a style="float:left;" href="{{ route('order.exportexcel') }}">
  <button class="bnt btn-info btn-default" style="margin-left:6px ;">export to excil</button>
</a>   

Excel Export in HomeController

public function exportExcel()
{
    $file_name = 'orders_'.date('Y_m_d_H_i_s').'.xlsx';

    return Excel::download(new OrderExport, $file_name);
}  

Upvotes: 0

Views: 939

Answers (1)

IGP
IGP

Reputation: 15879

You should just modify the query in your export class to make a join with the users table.

public function collection()
{
    return Order::query()
        ->select(
            'order.id',
            'user.name as user_id',
            'order.phone',
            'order.date',
            'order.time',
            'order.order_description'
        )
        ->join('users', 'users.user_id', 'orders.user_id')
        ->get();
}

Upvotes: 0

Related Questions