Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

LaravelFan's avatar

Issue with seeding my datatable

Hi,

I'm getting the message: Attempt to read property "banner" on null on the index page.

This is inside the Vendor.php model file:


<?php

namespace App\Models;

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

class Vendor extends Model
{
    use HasFactory;

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

This is the create_vendors_table.php migrations file:


<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('vendors', function (Blueprint $table) {
            $table->id();
            $table->text('banner');
            $table->string('phone');
            $table->string('email');
            $table->text('address');
            $table->text('description');
            $table->text('fb_link')->nullable();
            $table->text('tw_link')->nullable();
            $table->text('insta_link')->nullable();
            $table->integer('user_id');
            $table->boolean('status')->default(0);

            $table->timestamps();
        });
    }

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

This is the AdminProfileSeeder.php:


<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class AdminProfileSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $user = User::where('email', '[email protected]')->first();

        $vendor = new Vendor();
        $vendor->banner = 'uploads/1343.jpg';
        $vendor->shop_name = 'Admin Shop';
        $vendor->phone = '12321312';
        $vendor->email = '[email protected]';
        $vendor->address = 'Usa';
        $vendor->description = 'shop description';
        $vendor->user_id = $user->id;
        $vendor->save();
    }
}

This is the DatabaseSeeder.php:


<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // \App\Models\User::factory(10)->create();

        // \App\Models\User::factory()->create([
        //     'name' => 'Test User',
        //     'email' => '[email protected]',
        // ]);
        $this->call(UserSeeder::class);
        $this->call(AdminProfileSeeder::class);
    }
}

This is the index.blade.php file:


@extends('admin.layouts.master')

@section('content')
      <!-- Main Content -->
        <section class="section">
          <div class="section-header">
            <h1>Vendor Profile</h1>

          </div>

          <div class="section-body">

            <div class="row">
              <div class="col-12">
                <div class="card">
                  <div class="card-header">
                    <h4>Update Vendor Profile</h4>
                  </div>
                  <div class="card-body">
                    <form action="{{route('admin.vendor-profile.store')}}" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="form-group">
                            <label>Preview</label>
                            <br>
                            <img width="200px" src="{{asset($profile->banner)}}" alt="">
                        </div>
                        <div class="form-group">
                            <label>Banner</label>
                            <input type="file" class="form-control" name="banner">
                        </div>

                        <div class="form-group">
                            <label>Shop Name</label>
                            <input type="text" class="form-control" name="shop_name" value="{{$profile->shop_name}}">
                        </div>

                        <div class="form-group">
                            <label>Phone</label>
                            <input type="text" class="form-control" name="phone" value="{{$profile->phone}}">
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input type="text" class="form-control" name="email"  value="{{$profile->email}}">
                        </div>
                        <div class="form-group">
                            <label>Address</label>
                            <input type="text" class="form-control" name="address" value="{{$profile->address}}">
                        </div>
                        <div class="form-group">
                            <label>Description</label>
                            <textarea class="summernote" name="description">{{$profile->description}}</textarea>
                        </div>
                        <div class="form-group">
                            <label>Facebook</label>
                            <input type="text" class="form-control" name="fb_link" value="{{$profile->fb_link}}">
                        </div>
                        <div class="form-group">
                            <label>Twitter</label>
                            <input type="text" class="form-control" name="tw_link" value="{{$profile->tw_link}}">
                        </div>
                        <div class="form-group">
                            <label>Instagram</label>
                            <input type="text" class="form-control" name="insta_link" value="{{$profile->insta_link}}">
                        </div>

                        <button type="submmit" class="btn btn-primary">Update</button>
                    </form>
                  </div>

                </div>
              </div>
            </div>

          </div>
        </section>
@endsection

I ran the seeder only for the $this->call(AdminProfileSeeder::class); but the vendors table is empty.

Grateful for your guidance

0 likes
32 replies
LaravelFan's avatar

This is the VendorShopProfileController.php


<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Vendor;
use App\Traits\ImageUploadTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class VendorShopProfileController extends Controller
{
    use ImageUploadTrait;
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $profile = Vendor::where('user_id', Auth::user()->id)->first();
        return view('admin.vendor-profile.index', compact('profile'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'banner' => ['nullable','image', 'max:3000'],
            'shop_name' => ['required', 'max:200'],
            'phone' => ['required', 'max:50'],
            'email' => ['required', 'email', 'max:200'],
            'address' => ['required'],
            'description' => ['required'],
            'fb_link' => ['nullable', 'url'],
            'tw_link' => ['nullable', 'url'],
            'insta_link' => ['nullable', 'url'],
        ]);

        $vendor = Vendor::where('user_id', Auth::user()->id)->first();
        $bannerPath = $this->updateImage($request, 'banner', 'uploads', $vendor->banner);
        $vendor->banner = empty(!$bannerPath) ? $bannerPath : $vendor->banner;
        $vendor->shop_name = $request->shop_name;
        $vendor->phone = $request->phone;
        $vendor->email = $request->email;
        $vendor->address = $request->address;
        $vendor->description = $request->description;
        $vendor->fb_link = $request->fb_link;
        $vendor->tw_link = $request->tw_link;
        $vendor->insta_link = $request->insta_link;
        $vendor->save();

        toastr('Updated Successfully!', 'success');

        return redirect()->back();
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}

Snapey's avatar

firstly, change the size of user_id in the vendors table to match the id in the users table

So the error message is becaus $profile is null

Profile is null because as you say, vendors table is empty. You dont check if record was found in controller so pass null to the view

Your vendors table might be empty because the seeder never ran?

You need to check if the seeder is running and why you dont get your row created

LaravelFan's avatar

@Snapey Hi, This is what I got in the terminal after running the seeder:


mamunsson@dynamic-pd01:~/multivendorshop> php artisan db:seed

   INFO  Seeding database.  

  Database\Seeders\AdminProfileSeeder ...................................................................................................... RUNNING  

   Error 

  Class "Database\Seeders\User" not found

  at database/seeders/AdminProfileSeeder.php:15
     11▕      * Run the database seeds.
     12▕      */
     13▕     public function run(): void
     14▕     {
  ➜  15▕         $user = User::where('email', '[email protected]')->first();
     16▕ 
     17▕         $vendor = new Vendor();
     18▕         $vendor->banner = 'uploads/1343.jpg';
     19▕         $vendor->shop_name = 'Admin Shop';

      +8 vendor frames 

  9   database/seeders/DatabaseSeeder.php:22
      Illuminate\Database\Seeder::call()
      +22 vendor frames 

  32  artisan:35
      Illuminate\Foundation\Console\Kernel::handle()

mamunsson@dynamic-pd01:~/multivendorshop> 

Before running the seeder, I commented this part: //$this->call(UserSeeder::class);


<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // \App\Models\User::factory(10)->create();

        // \App\Models\User::factory()->create([
        //     'name' => 'Test User',
        //     'email' => '[email protected]',
        // ]);
        //$this->call(UserSeeder::class);
        $this->call(AdminProfileSeeder::class);
    }
}

martinbean's avatar

@Mamunsson Why don’t you actually read your error messages? Since they’re pointing you to problems.

You have an error:

Database\Seeders\User

Fix that first. You’re trying to use your User model class without importing it first.

You then go on to talk about a completely unrelated error here (Incorrect integer value) which is completely unrelated to the original error (Attempt to read property "banner" on null) because you’re just skipping ahead and ignoring any and all the errors beforehand.

You need to address errors as and when you encounter them, instead of ignoring them. Error messages aren‘t written to be ignored; they’re there to tell you something’s gone wrong or something didn’t work as expected, and to give you a hint as to what you need to change to fix it.

LaravelFan's avatar

@martinbean

Hi,

I modified the AdminProfileSeeder


<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User; // Added this line
use App\Models\Vendor; // Added this line if Vendor is also a model

class AdminProfileSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $user = User::where('email', '[email protected]')->first();

        $vendor = new Vendor();
        $vendor->banner = 'public/images/1343.jpg';
        $vendor->shop_name = 'Admin Shop';
        $vendor->phone = '12321312';
        $vendor->email = '[email protected]';
        $vendor->address = 'Usa';
        $vendor->description = 'shop description';
        $vendor->user_id = $user->id;
        $vendor->save();
    }
}

I ran the seeder, and got this:


mamunsson@dynamic-pd01:~/multivendorshop> php artisan db:seed

   INFO  Seeding database.  

  Database\Seeders\AdminProfileSeeder ...................................................................................................... RUNNING  

   ErrorException 

  Attempt to read property "id" on null

  at database/seeders/AdminProfileSeeder.php:26
     22▕         $vendor->phone = '12321312';
     23▕         $vendor->email = '[email protected]';
     24▕         $vendor->address = 'Usa';
     25▕         $vendor->description = 'shop description';
  ➜  26▕         $vendor->user_id = $user->id;
     27▕         $vendor->save();
     28▕     }
     29▕ }
     30▕

  1   database/seeders/AdminProfileSeeder.php:26

I see there is an issue at line 26 and need guidance on this issue.

JussiMannisto's avatar

@Mamunsson Did you read the error message?

Attempt to read property "id" on null

That means you're trying to access the "id" property on a null object. It even shows the exact line where this occurs. $user is null and you're trying to read its id property, hence the error.

martinbean's avatar

I see there is an issue at line 26 and need guidance on this issue.

@Mamunsson So you go to line 26 and see where you’re trying to read a property called “id” (i.e. ->id). Whatever variable you’re doing ->id on is null, and not an object like you think it is.

The error message even has a helpful little arrow pointing to the problem line, showing you’re doing $user->id. Well, the $user variable is null and not an object. So look at why that is.

Snapey's avatar

@Mamunsson This line

$user = User::where('email', '[email protected]')->first();

fails to find a user, possibly because you have not seeded the users table at this point, or you have seeded it with users that does not include one with an email of '[email protected]'

1 like
LaravelFan's avatar

@Snapey I tried to run the seeder again, and I got this:


 Database\Seeders\AdminProfileSeeder . RUNNING  

   Illuminate\Database\QueryException 

  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'shop_name' in 'field list' (Connection: mysql, SQL: insert into `vendors` (`banner`, `shop_name`, `phone`, `email`, `address`, `description`, `user_id`, `updated_at`, `created_at`) values (public/images/1343.jpg, Admin Shop, 12321312, [email protected], Usa, shop description, 1, 2024-05-22 19:59:45, 2024-05-22 19:59:45))

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:813
    809▕                     $this->getName(), $query, $this->prepareBindings($bindings), $e
    810▕                 );
    811▕             }
    812▕ 
  ➜ 813▕             throw new QueryException(
    814▕                 $this->getName(), $query, $this->prepareBindings($bindings), $e
    815▕             );
    816▕         }
    817▕     }

  i   A column was not found: You might have forgotten to run your database migrations. 
      https://laravel.com/docs/master/migrations#running-migrations

      +12 vendor frames 

  13  database/seeders/AdminProfileSeeder.php:26
      Illuminate\Database\Eloquent\Model::save()
      +8 vendor frames 

  22  database/seeders/DatabaseSeeder.php:22
      Illuminate\Database\Seeder::call()

I made the necessary corrections by adding this to the table:


php artisan make:migration add_shop_name_to_vendors_table --table=vendors

But I got the same result.

LaravelFan's avatar

@Snapey I know that I need to run php artisan migrate, I already did but didn't work. I was able to fix the issue. I created the shop_name column manually, ran the seeder and everything went well.

martinbean's avatar

I created the shop_name column manually, ran the seeder and everything went well.

😬

LaravelFan's avatar

If I try to fill the data directly in the MySQL database I get the error message:

#1366 - Incorrect integer value: '' for column multivendor.vendors.user_id at row 1

LaravelFan's avatar

I was able to fix the issue. I created the shop_name column manually, ran the seeder and everything went well.

Snapey's avatar

@Mamunsson you cant do things like this

I ran the migration but it errored so I said F-you Laravel we are doing this my way. You just better not get bitchy if I want to migrate again.

Do you not learn? Investigate and fix issues, not just work around them.

2 likes
martinbean's avatar

@Snapey Yeah. @mamunsson is in for a world of hurt the next time they need to run migrations or set up their project on a new computer.

LaravelFan's avatar

@martinbean I appreciate the grilling (I mean the criticism), that said, I've done many successful migrations and seedings in the past and it went well. This time, however, it didn't work as expected and this can happen. I tried to roll back the migration, re-ran the migration, and attempted to seed again with no success. Yes, I read the error messages, understood them but couldn't find a solution because my level of knowledge is that of a learner.

LaravelFan's avatar

@Snapey This is the migrations file:


<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('vendors', function (Blueprint $table) {
            $table->id();
            $table->string('shop_name')->nullable();
            $table->text('banner');
            $table->string('phone');
            $table->string('email');
            $table->text('address');
            $table->text('description');
            $table->text('fb_link')->nullable();
            $table->text('tw_link')->nullable();
            $table->text('insta_link')->nullable();
            $table->integer('user_id');
            $table->boolean('status')->default(0);

            $table->timestamps();
        });
    }

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

shop_name is included as we can see, but I was unable to migrate it even with rollback and re-migrate. What could be the reason?

Snapey's avatar

I see you are still using integer for user_id !

$table->integer('user_id');
Snapey's avatar

@Mamunsson because your ID in user model will be a bigger field so it can hold larger numbers.

But, tell you what, when you get an error migrating, why not share the error instead of saying "I understood the error but didn't know how to fix it"

LaravelFan's avatar

@Snapey Because the only message I got when I ran php artisan migrate command was: NOTHING TO MIGRATE.

Snapey's avatar

@Mamunsson thats because Laravel thinks you have run this migration already so if you edit a migration you need to artisan migrate:rollback and then artisan migrate.

gych's avatar

Like @snapey already said, you propably updated an existing migration that has already been migrated to your database. This will give you the message nothing to migrate because it has already been migrated once before.

Either run php artisan migrate:fresh this will reset all the tables in the database an migrate it again (all data will be deleted)

You can also use php artisan migrate:refresh --path="database\migrations\migration_file_name.php" this will only reset the table for the specific migration, all data for that table will be deleted. Replace migration_file_name.php with the correct file name of the migration you want to refresh.

Another option is to create a new migration for the change you want to apply but I personally never do this while the application is not live and still in development. I only do this when the application is in production because then you don't want the existing data to get deleted.

1 like
martinbean's avatar

when I ran php artisan migrate command was: NOTHING TO MIGRATE

@Mamunsson Well that’s what happens when you manually change your database schema, instead of defining those changes in migrations.

Only took three hours for you to prove me right and for you to find yourself in a pickle when trying to migrate your database.

So, again:

  1. Read error messages when they happen instead of disregarding them, carrying on. All you’re doing then is compounding problems.
  2. integer != unsignedBigInteger, hence you getting incompatible type errors. But you wouldn’t be using integer columns in the first place if you had read the Laravel migration docs, specifically the foreign keys section.
2 likes
LaravelFan's avatar

@gych Many thanks. I'll work on this issue and let you know how it goes.

1 like

Please or to participate in this conversation.