Search code examples
laravelconstructorcontrollerhelper

Laravel :: call method in helper class with constructor


as I mentioned in last question I am beginner in Laravel therefore I need some help ,I have to make helper class to create random Id for some tables ,I create this class with table constructor to recieve deffirent tables :

<?php
namespace App\Helpers;

use Illuminate\Support\Facades\DB;

class RandomId
{
    public function __construct($my_table)
    {
        $this->my_table=$my_table;
    }

    public function get_id()
    {
        $id = mt_rand(1000000000, 9999999999); 
        if($this->check_id($id)){
            get_id();
        }
        return $id;
    }

    public function check_id($id)
    {
        $table=DB::table($this->my_table)->where('id',$id)->get();
        if (count($course)==0){
            return false;
        }
        return true;
    }
}

then I add it as alias in config/app.php

'RandomId' => App\Helpers\RandomId::class,

now I want to call it in controller ,I did somethinf like this but don't work :

<?php

namespace App\Http\Controllers\course;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Helpers\RandomId;

class Course_controller extends Controller
{
    public function add(Request $request)
    {
       $id=RandomId::get_id('courses');
       dd($id);
    }
}

I get this error :Non-static method App\Helpers\RandomId::get_id() should not be called statically


Solution

  • It's because get_id function is not static. You should add static keyword when defining static methods:

    public static function get_id()
    {
           ....