Charles Smith
Charles Smith

Reputation: 3289

Laravel 8 seeding property [id] does not exist on the Eloquent builder instance

I am rebuilding an old project for a client and moving it to Laravel 8. I've created all the models and converted all the data from the current project into json so I can migrate the data as seeder data.

I have a Usercar model that has a belongsTo relationship with the Car and the User models. I need to re-create the relationships during the seeding process by comparing and matching the old id values in order to create the new records and relationships. All my seeders run successfully until I get to the **UsercarSeeder**, then I get a property [id] does not exist on the Eloquent builder instance error. I know I am missing something really simple. Thanks.

database/data/cars.json

[
    {
        "old_car_id": 31,
        "start_year": 1955,
        "end_year": 1958,
        "model": "356  Carrera 1500 GS Coupe",
        "horse_power": 110,
...

database/data/users.json

[
    {
        "old_user_id": "4be7c3a7-d626-456a-83be-5d303bf90d02",
        "first_name": "Charles",
        "last_name": "Smith",
...

database/data/user-cars.json

[
    {
        "old_user_id": "4be7c3a7-d626-456a-83be-5d303bf90d02",
        "old_car_id": 227,
        "car_color": "Gray",
        "year": 2015,
        "tire_points": 140,
...

database/seeders/UsercarSeeder.php

<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Car;
use App\Models\Usercar;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class UsercarSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {

        $json = file_get_contents('database/data/user-cars.json');
        $data = json_decode($json);

        $user = User::where('old_user_id', 'old_user_id')->get();
        $car = Car::where('old_car_id', 'old_car_id')->get();

        foreach ($data as $obj) {
            Usercar::create(array(
                'user_id' => $user->id,
                'car_id' => $car->id,
...

Upvotes: 0

Views: 850

Answers (1)

P. K. Tharindu
P. K. Tharindu

Reputation: 2730

The get() method returns a collection of models. If you need a single object, you should be using the first() method.

Also the where() should look something like:

->where($column, $value)

Looks like you are passing the column name twice which would probably return an empty collection.

Upvotes: 1

Related Questions