升级 laravel 和 php 版本后出现问题

problem after upgrading laravel and php version

我在 laravel 5.2.45 和 PHP 7.1 上工作没有任何问题,然后我决定升级到 laravel 7 和 php 7.4 我从事的项目正在运行,但我在某些页面上遇到问题,尤其是 laravel 中的属于关系,我收到此错误

 [2021-02-13 15:32:00] local.ERROR: Trying to access array offset on value of type null {"exception":"[object] (ErrorException(code: 0): Trying to access array offset on value of type null at /var/www/html/easy/app/Http/Controllers/SubscriberController.php:431)
[stacktrace]
#0 /var/www/html/easy/app/Http/Controllers/SubscriberController.php(431): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError()
#1 [internal function]: App\Http\Controllers\SubscriberController->userFilterData()
#2 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array()
#3 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\Routing\Controller->callAction()
#4 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Route.php(240): Illuminate\Routing\ControllerDispatcher->dispatch()
#5 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Route.php(197): Illuminate\Routing\Route->runController()
#6 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(681): Illuminate\Routing\Route->run()
#7 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Routing\Router->Illuminate\Routing\{closure}()
#8 /var/www/html/easy/app/Http/Middleware/Permissions.php(49): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#9 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): App\Http\Middleware\Permissions->handle()
#10 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(76): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#11 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle()
#12 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#13 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\View\Middleware\ShareErrorsFromSession->handle()
#14 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(56): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#15 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Session\Middleware\StartSession->handle()
#16 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#17 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle()
#18 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(66): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#19 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Cookie\Middleware\EncryptCookies->handle()
#20 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#21 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(683): Illuminate\Pipeline\Pipeline->then()
#22 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(658): Illuminate\Routing\Router->runRouteWithinStack()
#23 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(624): Illuminate\Routing\Router->runRoute()
#24 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(613): Illuminate\Routing\Router->dispatchToRoute()
#25 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(165): Illuminate\Routing\Router->dispatch()
#26 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}()
#27 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(63): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#28 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle()
#29 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}()
#30 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(140): Illuminate\Pipeline\Pipeline->then()
#31 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(109): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter()
#32 /var/www/html/easy/public/index.php(55): Illuminate\Foundation\Http\Kernel->handle()
#33 {main}
"} 

这是我的模型

<?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');
    }


}

这是我在控制器代码中的代码

  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();
    }

这是经理模型

class AclManager extends Model
{

    protected $table = 'reign_acl_managers';
    public $timestamps = false;

    public function parent()
    {
        return $this->hasOne('App\Model\AclManager', 'id', 'parent_id');
    }

    public function manager()
    {
        return $this->hasOne('App\Model\AclGroup', 'id', 'group_id');
    }

}

我有2个tables,一个是给超级管理员的,另一个是给经理的,我想得到订阅的用户和他们所属的经理,一些用户属于在经理 table 中找不到超级管理员,因此 table 中他们的所有者将为 0, 所以当我试图获取所有者详细信息时,我得到

Trying to access array offset on the value of type null

在这一行

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

问题是相同的代码在 laravel 的旧版本上运行良好,但在这个新版本中却不行。我认为问题出在模型中的关系上,但我不知道如何解决。

问题是 $val->ownersnull

在 PHP 的旧版本中,每当您尝试在 [=12= 上使用 [] 运算符时,此 error/notice 都会通过返回 null ]变量。

您可以通过 运行 下面的代码先使用 PHP 7.3 然后 PHP 7.4 来测试它:

<?php
$a = null;
var_dump($a['a']);

PHP 7.3 将打印 NULL,而 PHP 7.4 将抛出您提到的错误。

在升级您的 PHP 版本时,出现这些错误是正常的,因为过去该语言过于宽松。

LE:条件 $val->owners['full_name'] == "" 之前有效,因为 null == "" 的计算结果为 true,您可以将其替换为 !isset($val->owners['full_name'])