Home > Software design >  How do I fix Trying to access array offset on value of type null on a live server?
How do I fix Trying to access array offset on value of type null on a live server?

Time:01-10

Everything works on localhost but am getting error when I deploy on a live server. Can anyone help?

CONTROLLER

$status = Auth::guest()
    ? null
    : Request::where('person_id', auth()->user()->persn['id'])
        ->orderBy('id','DESC')
        ->limit(1)
        ->get();

BLADE TEMPLATE

@if(!empty(Auth::user()->persn->id) == !empty(Auth::user()->persn->req[0]->person_id) )
  @foreach ($status as $statu)
    @if($statu->is_accepted == 1 && $statu->is_payed == 1)
      <a href="#"  data-toggle="modal" data-target="#LoanReq">
        <i ></i> Ask
      </a>
      <a href="#"  data-toggle="modal" data-target="#Status-modal" onclick="return update(event)">
        <i ></i> Statut
      </a>
    @else
      <a href="#"  data-toggle="modal" data-target="#MyProfile-form">
        <i ></i> Account
      </a>
      @if ($status[0]->is_accepted == 1 && strtotime($status[0]->count_deadline) > time())
        <a href="#"  data-toggle="modal" data-target="#Status-modal" onclick="return update(event)">
          <i ></i> Statut
        </a>
      @else
        <a href="#"  data-toggle="modal" data-target="#Status-modal" onclick="return update(event)">
          <i ></i> Statut
        </a>
      @endif
    @endif
  @endforeach
@else
  <h1>NOTHING</h1>
@endif

CodePudding user response:

The line

@if(!empty(Auth::user()->persn->id) == !empty(Auth::user()->persn->req[0]->person_id) )

is the most likely culprit. More specifically

!empty(Auth::user()->persn->req[0]->person_id)
                               ^^^

if Auth::user()->persn->req evaluates to null, then trying to get an offset of it will throw an error.

This condition is weird, but one way to ugly patch this error would be

@if ( !empty(Auth::user()->persn->id) == ( !empty(Auth::user()->persn->req) && !empty(Auth::user()->persn->req[0]->person_id) ) )

Also, since emptyreturns a bool, you should use logical operators.

@if (!empty(Auth::user()->persn->id
    && !empty(Auth::user()->persn->req)
    && !empty(Auth::user()->persn->req[0]->person_id))

CodePudding user response:

Use the optional() method to guard your relationship queries like

optional(auth()->user()->persn)->id

or

optional(auth()->user()->persn)['id']

CodePudding user response:

By checking my blade codes, I realized that I was just repeating the same condition. So I had to remove the below line from my controller to fix the error.

where('person_id', auth()->user()->persn['id'])
  •  Tags:  
  • Related