Patrick Obafemi Patrick Obafemi - 1 month ago 16
PHP Question

Non-static method App\User::getallreferrals() should not be called statically

am trying to call functions inside my model in my controller but i get this error.


(1/1) ErrorException Non-static method App\User::getallreferrals() should not be called statically. in HomeController.php (line 37)


this is my model.



namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;

class User extends Authenticatable
{
use Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array
*/



public function getallreferrals()
{
return $this->model->where('referred_by', Auth::user()->referral_id)->pluck('referral_id');
}


}

then my controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\DateTime;
use App\User;
use Auth;
use Session;


class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}

/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/

public function index()
{
$captain = User::getcaptain();
$referrals = User::getallreferrals();


return view('home', ['captain' => $captain, 'referrals' => $referrals]);
}


Please what am i not doing right? I have been on this project for a while now.

Answer Source

As it is saying the getallreferrals method is not static, but you are trying to call it with :, which means static.

It should be something like

use a Scope for this in User model

public function scopeGetallreferrals($query, $user)
{
    return $query->where('referred_by', $user->referral_id);
}

and in controller

public function __construct(User $user)
{
    $this->user = $user;
}

public function index()
{
    $captain = $this->user->getcaptain();
    $referrals = $this->user->getallreferrals(Auth:user())->pluck('referral_id');

    return view('home', ['captain' => $captain, 'referrals' => $referrals]);
}