samedi 13 février 2021

problem after upgrading laravel and php version

I was working on laravel 5.2.45 and PHP 7.1 without any problem, then I decided to upgrade to laravel 7 and php 7.4 the project which I working on is working but I have problems with some pages especially with the belongs to relation in laravel , I get this error

Trying to access array offset on value of type null

this is the Model that I have

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Subscriber extends Model
{
    protected $table = 'reign_users';

    public $timestamps = false;

    /*public function profile()
    {
        return $this->belongsTo('App\Model\Profile', 'owner');
    }*/
    public function profiles()
    {
        return $this->hasOne('App\Model\Profile', 'id', 'srvid');
    }

    public function owners()
    {
        return $this->hasOne('App\Model\AclManager', 'id', 'owner');
    }
    
    public function radAcctData() {
        return $this->hasOne('App\Model\RadAcct', 'username', 'username');
    }
    
    public function usermac() {
        return $this->hasOne('App\Model\UserMAC', 'username', 'username');
    }
    
    public function onlineData() {
        return $this->hasOne('App\Model\OnlineUser', 'username', 'username');
    }

    public function userInvoice(){
        return $this->hasOne('App\Model\UserInvoice', 'username', 'username')->latest();
    }

    public function userNetwork(){
        return $this->hasOne('App\Model\Networks', 'id', 'networkid');
    }

    public function thanaName(){
        return $this->hasOne('App\Model\Thana', 'id', 'thana');
    }


}

and this is my code in controller code

  public function userFilterData(Request $request) {


        $user = Subscriber::with( 'userInvoice', 'usermac', 'userNetwork');

//        $user = Subscriber::leftJoin('radacct as r', function ($join) use($request) {
//                    $join->on('r.username', '=', 'reign_users.username');
//                    $join->on("r.acctstoptime", "IS", DB::raw("NULL"));
//                })
//                        ->with('userInvoice', 'usermac', 'userNetwork');

        /* only manager cannot see the deleted user */
        if (Session::get('type') == "Manager" && Session::get('admin_assistant') == 0) {
            $user->where('reign_users.owner', Session::get('id'));
        }

//date filter conditionn
        if (isset($request->dateFlag)) {
            $today = date("Y-m-d");
            if ($request->dateFlag == 1) {
                $user->where(DB::raw("date_format(reign_users.createdon, '%Y-%m-%d')"), $today);
            } elseif ($request->dateFlag == 2) {
                $weekStart = date('Y-m-d', strtotime('-6 days'));
                $user->whereRaw("date_format(reign_users.createdon, '%Y-%m-%d') BETWEEN '$weekStart' AND '$today'");
            } elseif ($request->dateFlag == 3) {
                $monthStart = date('Y-m-d', strtotime('first day of this month'));
                $user->whereRaw("date_format(reign_users.createdon, '%Y-%m-%d') BETWEEN '$monthStart' AND '$today'");
            } elseif ($request->dateFlag == 4) {
                $range = explode('-', $request->dateRange);
                $startDate = date('Y-m-d', strtotime($range[0]));
                $endDate = date('Y-m-d', strtotime($range[1]));
                $user->whereRaw("date_format(reign_users.createdon, '%Y-%m-%d') BETWEEN '$startDate' AND '$endDate'");
            } else {

            }
        }


//filter by user's status like active,online,expired
        if (isset($request->userStatus) && $request->userStatusVal != "") {
            $today = date("Y-m-d H:i:s");
            if ($request->userStatusVal == 1) {
                $user->whereRaw("reign_users.expiration <= '$today'");
            }
            if ($request->userStatusVal == 2) {
                $user->whereRaw("reign_users.expiration >= '$today'");
            }
            if ($request->userStatusVal == 3) {
                $threeDaysAfter = date("Y-m-d", strtotime("+3 days"));
                $dateToday = date("Y-m-d");
                $user->whereRaw("date_format(reign_users.expiration, '%Y-%m-%d') BETWEEN '$dateToday' AND '$threeDaysAfter'");
            }
            if ($request->userStatusVal == 4) {
                $user->whereRaw("reign_users.enableuser = 1");
            }
            if ($request->userStatusVal == 5) {
                $user->whereRaw("reign_users.enableuser = 0");
            }
        }

        if (isset($request->createdBy) && $request->createdByVal != "") {
            $user->whereRaw("reign_users.createdby = $request->createdByVal");
        }

        if (isset($request->profile) && $request->profileVal != "") {
            $user->whereRaw("reign_users.srvid = $request->profileVal");
        }

        if (isset($request->manager) && $request->managerVal != "") {
            $user->whereRaw("reign_users.owner = $request->managerVal");
        }

        if (isset($request->network) && $request->networkVal != "") {
            $user->whereRaw("reign_users.networkid = $request->networkVal");
        }

        if (($request->order[0]['column'] == 0) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.username", $order);
        }

        if (($request->order[0]['column'] == 4) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.expiration", $order);
        }

        if (($request->order[0]['column'] == 5) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.extended_expiration", $order);
        }
        if (($request->order[0]['column'] == 6) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.owner", $order);
        }

        /* string search */
        $searchStr = $request->search['value'];
        if ($searchStr != "") {
            $user->whereRaw("(reign_users.username like '%$searchStr%' OR reign_users.firstname like '%$searchStr%' OR reign_users.lastname like '%$searchStr%' OR reign_users.mobile like '%$searchStr%' OR reign_users.mac like '%$searchStr%')");
        }

        $user->where('reign_users.status', '!=', 3);


        $data['recordsTotal'] = $user->count();
        $data['recordsFiltered'] = $user->count();

        $user->limit($request->length)->offset($request->start);
        $userData = $user->get();

//        return $userData[1]->onlineData->status;
//        $expiredDate = $userData[1]->expiration;
//        $currentDate = date('Y-m-d');
//        $expiredInThreeDays = date('Y-m-d', strtotime('-3 days', strtotime($expiredDate)));
////        return $expiredInThreeDays;
//        if ($expiredInThreeDays >= $currentDate) {
//            return $expiredDate;
//        }else{
//            return $currentDate;
//        }

        $data['draw'] = $request->draw;


        $data['data'] = array();
        $sl = 0;
        foreach ($userData as $k => $val) {
            $isNewUser = 0;

            /* only new User don't have any invoice and monthly package user */
            if ($val->userInvoice == null && $val->profiles['timebaseexp'] == 1) {
                $isNewUser = 1;

                if ($val->user_type == 2) {
                    $profileMonthStartDay = $val->custom_month_start_day;
                    $userCurrentExpiration = date($val->expiration);

                    $countMonth = 1;
                    //$newDate = strtotime('+' . $countMonth . ' month', strtotime($userCurrentExpiration));
                    $newDate = strtotime('last day of next month', strtotime($userCurrentExpiration));
                    $nextMonthYear = date('Y-m', $newDate);

                    $settingData = SoftwareSetting::select('value')->where('attribute', 'gnrl_expiration_time')->first();
                    $time = $settingData->value;

                    $activationDate = date('Y-m-d H:i:s', strtotime($nextMonthYear . '-' . $profileMonthStartDay . ' ' . $time));
                } else {
                    /* if user have custom month start day, profile month start is ignored */
                    if ($val->custom_month_start_day != null) {
                        $profileMonthStartDay = $val->custom_month_start_day;
                    } else {
                        $profileMonthStartDay = $val->profiles['month_start_day'];
                    }

                    $profileUnitMonth = $val->profiles['timeunitexp'];
                    $userCurrentExpiration = date($val->expiration);


                    //$newDate = strtotime('+' . $countMonth . ' month', strtotime($userCurrentExpiration));
                    $newDate = strtotime('last day of next month', strtotime($userCurrentExpiration));
                    $nextMonthYear = date('Y-m', $newDate);


                    $settingData = SoftwareSetting::select('value')->where('attribute', 'gnrl_expiration_time')->first();
                    $time = $settingData->value;

                    $activationDate = date('Y-m-d H:i:s', strtotime($nextMonthYear . '-' . $profileMonthStartDay . ' ' . $time));
                }

                $createdDate = $val->createdon;
                $newExpirationDate = date('Y-m-d', strtotime($activationDate));

                $activatedDayCount = date_diff(date_create($createdDate), date_create($newExpirationDate));

                $dayCountNewUser = $activatedDayCount->format("%a");
            }

            $expiredDate = $val->expiration;
            $currentDate = date('Y-m-d');
            $expiredInThreeDays = date('Y-m-d', strtotime('-3 days', strtotime($expiredDate)));
            $userActive = $val->enableuser;
            if ($currentDate > $expiredDate && $userActive == 0) {
                $color = 'gray';
            } elseif ($currentDate > $expiredDate && $userActive == 1) {
                $color = 'red';
            } elseif ($expiredInThreeDays <= $currentDate) {
                $color = 'orange';
            } elseif ($userActive == 0) {
                $color = 'gray';
            } elseif ($userActive == 1) {
                $color = 'blue';
            } else {
                $color = 'black';
            }

            $data['data'][$sl]['user_name'] = "<a class='userShow'  data-toggle='modal'
                                               data-target='#userDetails' href='$val->id'><strong style='color:" . $color . "'>" . $val->username .
                    "</strong></a><br><small class='text-info'>Added: " . date('d,M Y', strtotime($val->createdon)) . "</small>";



            $data['data'][$sl]['full_name'] = $val->firstname . ' ' . $val->lastname .
                    "<br> <small class='text-info'>Phone: " . $val->mobile . "</small>";


            $data['data'][$sl]['profile'] = ($val->user_type == 2) ? $val->ip : $val->profiles['srvname'] . "<br><small class='text-danger'>" .$val->usermac['mac'].
  "</small>";

            if ($val->isNOC == 1) {
                $networkBox = 'NOC';
            } else {
                $networkBox = 0;//$val->userNetwork['name'];
            }
            $data['data'][$sl]['networkBox'] = $networkBox;

            $data['data'][$sl]['billing_date'] = date('d,M Y H:i:s', strtotime($val->expiration));
//            $data['data'][$sl]['billing_date'] = date('d,M Y H:i:s', strtotime($val->expiration)) .
//                    "<br><small class='text-danger'>Last Online: " .
//                    date("d,M Y, H:i", strtotime($val->lastonline)) . "</small>";

            $data['data'][$sl]['expiration'] = "<small>" . date('d,M Y H:i:s', strtotime($val->extended_expiration)) . "</small>";

            $data['data'][$sl]['owner'] = $val->owners['full_name'] == "" ? "Admin" : $val->owners['full_name'];


            $costAmount = 0;
            if ($val->owners['id'] > 0) {
                $profile = AclManagerProfiles::select('cost_amount')->where(array(
                            'manager_id' => $val->owners['id'],
                            'profile_id' => $val->profiles['id'],
                        ))->first();
                $costAmount = isset($profile->cost_amount) ? $profile->cost_amount : 0;
            }

            if ($isNewUser == 1) {
                $unitPrice = round(($dayCountNewUser / 30) * $val->profiles['unitprice']);
                //$data['data'][$sl]['commission'] = $costAmount > 0 ? ($unitPrice - round(($dayCountNewUser / 30) * $costAmount)) : 0;
            } else {
                $unitPrice = $val->profiles['unitprice'];
                //$data['data'][$sl]['commission'] = $costAmount > 0 ? ($unitPrice - $costAmount) : 0;
            }

            $data['data'][$sl]['monthly_bill'] = $unitPrice + $val->additional_cost - $val->discount;


            $data['data'][$sl]['activation'] = "<a class='userActive badge badge-info' data-toggle='modal'
                                               data-target='#expirationExpand' price='$unitPrice' username='$val->username' href='$val->id'>
                                                Pay Bill
                                            </a>";
            if (Session::get('admin_assistant') == 1 && $val->owner > 0) {
                $data['data'][$sl]['activation'] = "";
            }

            $editUrl = URL::to('subscriber' . '/' . $val->id);

            if ($val->status == 0) {
                $data['data'][$sl]['action'] = "<a href='$editUrl' action='GET'>
                                                <i class='icon-pencil text-info'></i>
                                                </a>
                                                 |
                                                <a href='$editUrl' data-method='delete'
                                                data-confirm='Are you sure?  User will be delete.'>
                                                <i class='icon-trash text-danger'></i>
                                                </a>";
            } else {
                $data['data'][$sl]['action'] = "<a href='$editUrl' data-method='delete'
                                                    data-confirm='Are you sure? Do you want to restore this User?'>
                                                <i class='icon-reload text-danger'></i>
                                                </a>";
            }

            $sl++;
        }

        echo json_encode($data);
        die();
    }

I have 2 tables ,one is for super admin and the other one is for manager , I am trying to get the supscribed users and the manager that they are belongs to , some of users are belongs to super admin who is not found in manager table , so the owner of them in the table will be 0 , so when I am trying to get the owner details I get

Trying to access array offset on value of type null

in this line

 $data['data'][$sl]['owner'] = $val->owners['full_name'] == "" ? "Admin" : $val->owners['full_name']; 

the problem is same code working fine on an old version of laravel , but not in this new version. I think the problem is with the relationship in the model, but I don't know how to solve it.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire