Ad

Call To A Member Function GetPaginate() On A Non-object

- 1 answer

I'm new to laravel framwork , and I'm coding my first web app

and getting the following error

 FatalErrorException in PersonController.php line 26:
Call to a member function getPaginate() on a non-object

this is my Controller

   <?php

namespace App\Http\Controllers; 
use App\Repositories\PersonRepository;

class PersonController extends Controller
{
    protected  $personRepo ;
    protected  $nbrPerPage = 4 ;


    public  function  _construct(PersonRepository $personRepository)
    {
        $this->personRepo = $personRepository ;
    }
    public function index()
    {
        $persons = $this->personRepo->getPaginate(nbrPerPage);
        $links = $persons->setPath('')->render();

        return view('index', compact('persons', 'links'));
    }

    public function create()
    {

    }


    public function store()
    {

    }


    public function show($id)
    {
        //
    }


    public function edit($id)
    {
        //
    }


    public function update($id)
    {
        //
    }


    public function destroy($id)
    {
        //
    }


}

and this my repository class

<?php
namespace  App\Repositories ;
use App\Person ;
use App\User;


class PersonRepository {

  protected  $person ;
    public function  _construct (Person $person)
    {
        $this->$person = $person  ;
    }


    public  function  getPaginate($n)
    {

        return $this->person-> paginate($n) ;
    }


 }
Ad

Answer

Unless these are just typos in the question, you have a lot of typos in your code.

The typo that is causing this specific error is that the name of the constructor method should be __construct (with two underscores), not _construct (with one underscore).

Since the constructor method is misspelled on your PersonController, this method is never called and the personRepo attribute is never set. Since it is never set, the line $persons = $this->personRepo->getPaginate(nbrPerPage); is trying to call getPaginate() on a non-object.

Additional typos/issues I see at a glance:

  • $persons = $this->personRepo->getPaginate(nbrPerPage);
    nbrPerPage is being used as a constant. This is incorrect. Should be:
    $persons = $this->personRepo->getPaginate($this->nbrPerPage);
  • Constructor on PersonRepository also misspelled. Should be __construct(), not _construct.
  • $this->$person = $person ;
    This is inside the attempted construct of the PersonRepository. The $ needs to be removed from $this->$person. Should be:
    $this->person = $person;
Ad
source: stackoverflow.com
Ad