Home > database >  Laravel 8 all() Function does not map db values to model properties
Laravel 8 all() Function does not map db values to model properties

Time:12-12

I am fairly new to laravel so I assume this is a newbie question. Basically I try to retrieve my db data through the static all()-function. But somehow my resulting model instance only populates data in the attributes array but all model properties are null.

I have a simple route

Route::get('/posts', function () {
    $posts = App\Models\Post::all();
    ddd($posts[0]);
    return view('posts', [
        'posts' => $posts,
    ]);
});

and a simple model

<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    public $id;
    public $title;
    public $excerpt;
    public $body;
    public $published_at;
    public $category_id;

    protected $fillable = [
        'title',
        'excerpt',
        'body',
        'published_at',
        'category_id',
    ];

    protected $guarded = ['id'];

    public function category() {
        return $this->belongsTo(Category::class);
    }
}

this is what ddd() returns

App\Models\Post {#1225 ▼
   id: null
   title: null
   excerpt: null
   body: null
   published_at: null
   category_id: null
  #fillable: array:5 [▶]
  #guarded: array:1 [▶]
  #connection: "mysql"
  #table: "posts"
  #primaryKey: "id"
  #keyType: "int"
   incrementing: true
  #with: []
  #withCount: []
   preventsLazyLoading: false
  #perPage: 15
   exists: true
   wasRecentlyCreated: false
  #escapeWhenCastingToString: false
  #attributes: array:8 [▼
    "id" => 1
    "title" => "Dedrick Ebert DDS"
    "excerpt" => "Possimus sit animi enim error. Omnis maxime ducimus nesciunt omnis quibusdam."
    "body" => "Neque est aliquid est placeat. Eaque nihil nobis nobis nostrum consequuntur. Omnis quis aut ipsum quo. Facilis velit ducimus quisquam consequatur vitae quidem.  ▶"
    "published_at" => "2003-10-06"
    "category_id" => 7
    "created_at" => "2021-12-07 20:30:15"
    "updated_at" => "2021-12-07 20:30:15"
  ]
  #original: array:8 [▶]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
   timestamps: true
  #hidden: []
  #visible: []
}

Can somebody explain me what I am missing here?

Thanks for your pointers

CodePudding user response:

What do you want to get as a result?

The first element of $posts is the Object of the first post and you don`t need to define those properties again. you can just use

$post->id

delete all your defined properties.

  • Related