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
:
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();
CodePudding user response:
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);