dimanche 11 février 2018

Laravel 5.5 eager loading throws error - Trying to get property of non-object

I see a lot of people are having trouble with eager loading and Laravel, and I'm one of them too. I'm getting the error: Trying to get property of non-object

I've looked at other stack overflow answers, but none of them have solved this issue: here's all my code

My 2 migration files

create_authors_table

<?php

# database/migrations/1970_01_01_000001_create_authors_table

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAuthorsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->string('author_id');
            $table->string('first_name');
            $table->string('last_name');
            $table->timestamps();

            $table->primary('author_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('authors');
    }
}

create_books_table

<?php

# database/migrations/1970_01_01_000002_create_books_table

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->string('book_id');
            $table->string('title');
            $table->string('author_id');
            $table->timestamps();

            $table->foreign('author_id')->references('author_id')->on('authors');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('books');
    }
}

Next, here's my routes

routes/web.php

<?php

# routes/web.php
Route::get('/books', 'BookController@index');

I have 2 models

Models/Author.php

<?php

# app/Models/Author.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    protected $primaryKey = 'author_id';

    public function book()
    {
        return $this->hasMany('App\Models\Book');
    }
}

Models/Book.php

<?php

# app/Models/Book.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $primaryKey = 'book_id';

    public function author()
    {
        return $this->belongsTo('App\Models\Author', 'author_id');
    }
}

Here's my BookController

<?php

# app/Http/Controllers/BookController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Book;

class BookController extends Controller
{
    public function index()
    {
        $books = Book::with('author')->get();


        $results = [];
        foreach ($books as $book) {
            $result = new \stdClass();
            $result->title = $book->title;
            $result->author_first_name = $book->author->first_name;
            $result->author_last_name = $book->author->last_name;
            $results[] = $result;
        }

        dd($results);
    }
}

Here's some test data to fill the database with:

insert into authors (author_id, first_name, last_name, created_at) 
values 
(
  'ceefb81f-48bb-ff07-1002-27fd8b7272b4', 'Charles', 'Coal', '2018-02-11 00:00:00'
);

INSERT INTO books (book_id, title, author_id, created_at)
VALUES 
(
  'a4e58f2a-36f5-f2fb-960c-c60e2689b337', 'Killing Coal', 'ceefb81f-48bb-ff07-1002-27fd8b7272b4',
  '2018-02-11 00:00:00'
),
(
  'a4e58f2a-36f5-f2fb-960c-c60e2689b338', 'Cleaning Coal', 'ceefb81f-48bb-ff07-1002-27fd8b7272b4',
  '2018-02-11 00:00:01'
),
(
  'a4e58f2a-36f5-f2fb-960c-c60e2689b339', 'Using Coal', 'ceefb81f-48bb-ff07-1002-27fd8b7272b4',
  '2018-02-11 00:00:02'
);

I've turned on logging in MySQL and can see that 2 queries are being run

# turn on logging by running the following in MySQL
SET GLOBAL log_output = "FILE";
SET GLOBAL general_log_file = "/tmp/mysql.logfile.log";
SET GLOBAL general_log = 'ON';

And here's the output of the MySQL log file

2018-02-11T18:52:21.426064Z   262 Prepare   select * from `books`
2018-02-11T18:52:21.426348Z   262 Execute   select * from `books`
2018-02-11T18:52:21.426539Z   262 Close stmt    
2018-02-11T18:52:21.430560Z   262 Prepare   select * from `authors` where `authors`.`author_id` in (?)
2018-02-11T18:52:21.430689Z   262 Execute   select * from `authors` where `authors`.`author_id` in ('ceefb81f-48bb-ff07-1002-27fd8b7272b4')

But, for some reason, the relationships aren't being associated



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire