Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jyotishmoy's avatar

Can't access hasOne relationship data in FromView excel export for maatwebsite/excel library

I have created an excel export with maatwebsite/excel library for all applications in my project using FormView. I can easily access the table data but can't access the hasOne relationship data in my export view file. It gives "Trying to get property 'add_line_1' of non-object" error. If I try to dump the data as JSON, the hasOne relationship data is however present. Here's my export code:


<?php

namespace App\Exports;

use App\Models\Application;
//use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\Exportable;

class ApplicationsExport implements FromView
{

    use Exportable;

    public function __construct($search)
    {
        $this->search  = $search;
    }

    public function view(): View
    {

    	$query = Application::query();
	
	if ($this->search != 'all') {
            $search = $this->search;
            $query->where(function ($q) use ($search) {
                $q->where('mobile', $search)->orWhere('email', $search);
            });
        }

	$applications = $query->with('address')->get();

	return view('exports.applications', [
            'applications' => $applications
        ]);

    }

}

Here's my blade view file code:


<!DOCTYPE html>
<html>
<head>
<title>Export All Applications</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
  <table>
    <thead>
      <tr>
        <th>Application ID</th>
        <th>Full Name</th>
        <th>Email</th>
        <th>Mobile</th>
        <th>Address Line 1</th>
        <th>Address Line 2</th>
        <th>City</th>
        <th>State</th>
        <th>Country</th>
        <th>PIN</th>
      </tr>
    </thead>
    <tbody>
	
	@foreach ($applications as $application)
		
		<tr>
          		<td>{{ $application->application_id }}</td>
          		<td>{{ $application->full_name }}</td>
          		<td>{{ $application->email }}</td>
          		<td>{{ $application->mobile }}</td>
			<td>{{ $application->address->adr_line_1 }}</td>
                	<td>{{ $application->address->adr_line_2 }}</td>
                	<td>{{ $application->address->city_details->name }}</td>
                	<td>{{ $application->address->state_details->name }} </td>
                	<td>{{ $application->address->country_details->name }} </td>
                	<td>{{ $application->address->pin }} </td>
		</tr>

	@endforeach

    </tbody>
  </table>
</body>
</html>

Now I don't know what am I doing wrong here. I'd be glad to have suggestions regarding the approach i should follow to solve the problem. Thank You

0 likes
1 reply

Please or to participate in this conversation.