1

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();
    }
}
Pippo
  • 2,173
  • 2
  • 3
  • 16
Novice
  • 41
  • 7

2 Answers2

1

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')
steven7mwesigwa
  • 5,701
  • 3
  • 20
  • 34
1

Thanks @steven7mwesigwa. You solve my issue. I found other solution but the sequence of segment number will change.

<?php $uri = current_url(true); ?>
<?php echo $uri->getSegment(4); ?>
Novice
  • 41
  • 7