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

How to retrieve record from Eloquent Model?

This sounds stupid but I can’t find a way to retrieve a record from eloquent model Gallery.php:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Gallery extends Model
{
    use HasFactory;

    protected $fillable = ['text'];
}

Calling from a Route in web.php:

$data = Gallery::with('id', '=', 1)->get();

throws this error in laravel.log:

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

local.ERROR: Call to undefined relationship [id] on model [App\Models\Gallery]. {"exception":"[object] (Illuminate\\Database\\Eloquent\\RelationNotFoundException(code: 0): Call to undefined relationship [id] on model [App\\Models\\Gallery]. at /Users/artur/PhpstormProjects/strong-moebel.art/vendor/laravel/framework/src/Illuminate/Database/Eloquent/RelationNotFoundException.php:35)

The only thing that works is:

$data = Gallery::all();

>Solution :

The with() method at:

Gallery::with

Is used to refer to relationship with another model.
If you are looking to get data from just the Gallery model change with() to where() as below:

$data = Gallery::where('id', '=', 1)->get();

This will return a collection (think of it as an object containing an array of the results).

If you’re trying to access additional data from a related model you will need to setup the relationships as per the Laravel documentation.

If you want just the instance of Gallery related to that id, you can get it with

$gallery = Gallery::where('id', '=', 1)->first();
// or
$gallery = Gallery::find(1);
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