I created class which load DB data.
<?php
namespace App\Repositories;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class FantasticRepository
{
private function getFantastic($id)
{
$user = Auth::user();
$companyId = $user->id;
$tableName = "elites";
return \DB::table($tableName )->where('id', $id)->first();
}
}
But a controller can not call a function of the class I created.
use App\Repositories\FantasticRepository;
class FooController extends Controller
{
private FantasticRepository $fantasticRepository;
public function getFantastic(Request $request)
{
$ke = $fantasticRepository->getInformation($request->id);
return view('ke.index',compact($ke));
}
}
My Error log says
local.ERROR: Undefined variable: fantasticRepository {"userId":4,"exception":"[object] (ErrorException(code: 0): Undefined variable: fantasticRepository at /Users/Developments/abc/app/Http/Controllers/FooController.php:36) [stacktrace] #0 /Users/Developments/app/Http/Controllers/FooController.php(36): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Undefined varia...', '/Users/...', 36, Array)
Is a laravel app able to use an external class?
CodePudding user response:
in Laravel we can import call with use.
use App\Repositories\FantasticRepository;
class FooController extends Controller
{
use FantasticRepository;
public function getFantastic(Request $request)
{
$ke = $this->getFantastic($request->id);
return view('ke.index',compact($ke));
}
}
CodePudding user response:
You need dependency injection. You can do that on constructor or in function argumants.
public function __construct(private FantasticRepository $fantasticRepository) {}
//or
public function getFantastic(Request $request, FantasticRepository $fantasticRepository) {}
CodePudding user response:
You cannot use the private
function outside of its class
so you have to define getFantastic
function as public
function to use it in controller
private function getFantastic($id)
{
$user = Auth::user();
$companyId = $user->id;
$tableName = "elites";
return \DB::table($tableName )->where('id', $id)->first();
}
to
public function getFantastic($id)
{
$user = Auth::user();
$companyId = $user->id;
$tableName = "elites";
return \DB::table($tableName )->where('id', $id)->first();
}