Search code examples
codeigniter-4

CI4 Attempt to read property "uri" on null


I am facing this error in my CI 4 Model (ErrorException. Attempt to read property "uri" on null)

Here's my code below.

namespace App\Models;

use CodeIgniter\Model;

class scoresheet_model extends Model
{
    protected $table = 'players';
    protected $primaryKey = 'player_id';
    protected $allowedFields = [
        'player_id',
        'player_firstname',
        'player_surname',
        'player_team_id',
        'player_position',
        'player_jersey_number',
        'player_is_playing',
    ];
    
    function getHomeTeam()
    {
        return $this->db->table('players')
        ->where('player_team_id=', $this->request->uri->getSegment('3'))
        ->orderby('player_jersey_number')
        ->get()
        ->getResult();
    }
}

Solution

  • Accessing the Request

    An instance of the request class already populated for you if the current class is a descendant of CodeIgniter\Controller and can be accessed as a class property:

    <?php
    
    namespace App\Controllers;
    
    use CodeIgniter\Controller;
    
    class UserController extends Controller
    {
       public function index()
       {
           if ($this->request->isAJAX()) {
               // ...
           }
       }
    }
    

    If you are not within a controller, but still need access to the application’s Request object, you can get a copy of it through the Services class:

    <?php
    
    $request = \Config\Services::request();
    

    Solution:

    Instead of:❌

    $this->request->uri->getSegment('3')
    

    Use:✅

    \Config\Services::request()->uri->getSegment('3')