Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel, Eloquent: how to access model instances? (I dont want static calls)

given some code:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class Reception extends Model
{
    use HasFactory;

    protected $table = 'receptions';

    /**
     * get all with repetitive info
     */
    public function getAllWithRepetitiveInfo() : Collection
    {
        return DB::table('receptions')->leftJoin('receptions_repetitives', 'receptions_repetitives.reception_id', '=', 'receptions.id')->get();
    }
}

this getAllWithRepetitiveInfo would be used somewhere in my controller, but… how? Seeing the documentations: https://laravel.com/docs/10.x/eloquent all I see were static calls. I dont want that…
here https://github.com/alexeymezenin/laravel-best-practices I saw something similar:

public function index()
{
return view(‘index’, [‘clients’ => $this->client->getWithNewOrders()]);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but of course following this logic: $this->reception won’t work (property doesn’t exist) and I dont know how it would even be injected.

So all in all, I want to avoid Reception::getAllWithRepetitiveInfo(), I want to do $this->reception->getAllWithRepetitiveInfo()

>Solution :

You inject your model as dependency (in constructor or method or other) then you can call it like that you want:

class SomeController extends Controller {

    public function __construct(private Reception $reception) {}

    public function index() {
      dd($this->reception->getAllWithRepetitiveInfo());
    }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading