Error call to a member function connection on null

I tried creating a unit test for the relationships between my User and Shop models, however when I run vendor\bin\phpunit this error(s) are thrown, I have no idea about this since I'm a newbie in...

I tried creating a unit test for the relationships between my User and Shop models, however when I run vendor\bin\phpunit this error(s) are thrown, I have no idea about this since I’m a newbie in unit testing. I tried to run my code on my controller to see if the relationship actually works, and fortunately it is working as expected, but not when run in phpunit. What have I done wrong for this phpunit not to work with Models?

Fatal error: Uncaught Error: Call to a member function connection() on null in E:projectstryvendorlaravelframeworksrcIlluminateDatabaseEloquentModel.php:1013

Stack trace:
E:projectstryvendorlaravelframeworksrcIlluminateDatabaseEloquentModel.php(979): IlluminateDatabaseEloquentModel::resolveConnection(NULL)

This is my UserTest.php

<?php

namespace TestsUnit;

use TestsTestCase;
use IlluminateFoundationTestingDatabaseMigrations;
use IlluminateFoundationTestingDatabaseTransactions;

use AppUser;
use AppShop;

class UserTest extends TestCase
{

    protected $user, $shop;

    function __construct()
    {
        $this->setUp();
    }
    
    function setUp()
    {
        $user = new User([
            'id' => 1,
            'first_name' => 'John',
            'last_name' => 'Doe',
            'email' => 'JohnDoe@example.com',
            'password' => 'secret',
            'facebook_id' => null,
            'type' => 'customer',
            'confirmation_code' => null,
            'newsletter_subscription' => 0,
            'last_online' => null,
            'telephone' => null,
            'mobile' => null,
            'social_security_id' => null,
            'address_1' => null,
            'address_2' => null,
            'city' => null,
            'zip_code' => null,
            'signed_agreement' => 0,
            'is_email_confirmed' => 0
        ]);

        $user = User::find(1);
        $shop = new Shop([
            'id' => 1,
            'user_id' => $user->id,
            'name' => 'PureFoods Hotdog2',
            'description' => 'Something that describes this shop',
            'url' => null,
            'currency' => 'USD'
        ]);
        $user->shops()->save($shop);

        $shop = new Shop([
            'id' => 2,
            'user_id' => $user->id,
            'name' => 'PureFoods Hotdog',
            'description' => 'Something that describes this shop',
            'url' => null,
            'currency' => 'USD'
        ]);

        $user->shops()->save($shop);

        $this->user = $user;

    }

    /** @test */
    public function a_user_has_an_id(){
        $user =  User::find(1);
        $this->assertEquals(1, $user->id);
    }

    /** @test */
    public function a_user_has_a_first_name()
    {
        $this->assertEquals("John", $this->user->first_name);
    }

    /** @test */
    public function a_user_can_own_multiple_shops()
    {
        $shops = User::find(1)->shops()->get();
        var_dump($this->shops);
        $this->assertCount(2, $shops);
    }
}

It seems, this error is caused by this line of code:
$user->shops()->save($shop); — this code actually works when run in my sample routes or Controller but is throwing errors when run in phpunit

User.php

<?php

namespace App;

use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $guarded = [ 'id' ];
    protected $table = "users";   

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    /**
     * returns the Shops that this user owned
     */
    public function shops()
    {
        return $this->hasMany('AppShop');
    }
}

Shop.php

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Shop extends Model
{
    protected $guarded = [ 'id' ];
    protected $table = "shops";

    /**
     * returns the Owner of this Shop
     */
    public function owner()
    {
        return $this->belongsTo('AppUser');
    }
}

Any help will be very much appreciated. Thanks!

So I built a small 5.4 app in my spare time for work. Works great in dev. Works great when I deploy it out to some cheap hosting I control. Now trying to deploy it on company servers and I keep getting the following error every time I hit the app. This even happens when I try to load the homepage, which shouldn’t be trying to establish a database connection at all if I understand things correctly.

I’ve tried to do some digging and have found some people suggesting it might be an issue with the order of service providers in app.php, but I haven’t changed the order at all, and it works fine in other environments.

I’m trying to follow the code to understand what’s going on here, but I’m a bit out of my depth. Looking for any suggestions on next steps to take to understand what’s happening.

PHP message: PHP Fatal error:  Uncaught Error: Call to a member function connection() on null in /var/www/interviewmanager/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:1058

Stack trace:
#0 /var/www/interviewmanager/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1024): IlluminateDatabaseEloquentModel::resolveConnection(NULL)
#1 /var/www/interviewmanager/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(859): IlluminateDatabaseEloquentModel->getConnection()
#2 /var/www/interviewmanager/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(818): IlluminateDatabaseEloquentModel->newBaseQueryBuilder()
#3 /var/www/interviewmanager/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(802): IlluminateDatabaseEloquentModel->newQueryWithoutScopes()
#4 /var/www/interviewmanager/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1374): IlluminateDatabaseEloquentModel->newQuery()
#5 /var/www/inter...
Database/Eloquent/Model.php:1058
Stack trace:
#0 /var/www/interviewmanager/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1024): IlluminateDatabaseEloquentModel::resolveConnection(NULL)
#1 /var/www/interviewmanager/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(859): IlluminateDatabaseEloquentModel->getConnection()
#2 /var/www/interviewmanager/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(818): IlluminateDatabaseEloquentModel->newBaseQueryBuilder()
#3 /var/www/interviewmanager/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(802): IlluminateDatabaseEloquentModel->newQueryWithoutScopes()
#4 /var/www/interviewmanager/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1374): I

Я попытался создать единичный тест для отношений между моделями User и Shop, однако, когда я запускаю vendor\bin\phpunit эта ошибка (-ы) выбрасывается, я понятия не имею об этом, так как я новичок в модульном тестировании, Я попытался запустить свой код на своем контроллере, чтобы увидеть, действительно ли отношение действительно работает, и, к счастью, оно работает так, как ожидалось, но не при запуске в phpunit. Что я сделал неправильно для этого phpunit, чтобы не работать с Моделями?

Fatal error: Uncaught Error: Call to a member function connection() on null in E:projectstryvendorlaravelframeworksrcIlluminateDatabaseEloquentModel.php:1013

Stack trace: E:projectstryvendorlaravelframeworksrcIlluminateDatabaseEloquentModel.php(979): IlluminateDatabaseEloquentModel::resolveConnection(NULL)

Это мой UserTest.php

<?php

namespace TestsUnit;

use TestsTestCase;
use IlluminateFoundationTestingDatabaseMigrations;
use IlluminateFoundationTestingDatabaseTransactions;

use AppUser;
use AppShop;

class UserTest extends TestCase
{

    protected $user, $shop;

    function __construct()
    {
        $this->setUp();
    }

    function setUp()
    {
        $user = new User([
            'id' => 1,
            'first_name' => 'John',
            'last_name' => 'Doe',
            'email' => '[email protected]',
            'password' => 'secret',
            'facebook_id' => null,
            'type' => 'customer',
            'confirmation_code' => null,
            'newsletter_subscription' => 0,
            'last_online' => null,
            'telephone' => null,
            'mobile' => null,
            'social_security_id' => null,
            'address_1' => null,
            'address_2' => null,
            'city' => null,
            'zip_code' => null,
            'signed_agreement' => 0,
            'is_email_confirmed' => 0
        ]);

        $user = User::find(1);
        $shop = new Shop([
            'id' => 1,
            'user_id' => $user->id,
            'name' => 'PureFoods Hotdog2',
            'description' => 'Something that describes this shop',
            'url' => null,
            'currency' => 'USD'
        ]);
        $user->shops()->save($shop);

        $shop = new Shop([
            'id' => 2,
            'user_id' => $user->id,
            'name' => 'PureFoods Hotdog',
            'description' => 'Something that describes this shop',
            'url' => null,
            'currency' => 'USD'
        ]);

        $user->shops()->save($shop);

        $this->user = $user;

    }

    /** @test */
    public function a_user_has_an_id(){
        $user =  User::find(1);
        $this->assertEquals(1, $user->id);
    }

    /** @test */
    public function a_user_has_a_first_name(){
        $this->assertEquals("John", $this->user->first_name);
    }

    /** @test */
    public function a_user_can_own_multiple_shops(){
        $shops = User::find(1)->shops()->get();
        var_dump($this->shops);
        $this->assertCount(2, $shops);
    }
}

Похоже, эта ошибка вызвана этой строкой кода: $user->shops()->save($shop); — этот код действительно работает при запуске в моих phpunit маршрутов или контроллере, но бросает errors при запуске в phpunit

User.php

<?php

namespace App;

use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $guarded = [ 'id' ];
    protected $table = "users";   

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    /**
     * returns the Shops that this user owned
     */
    public function shops(){
        return $this->hasMany('AppShop');
    }
}

Shop.php

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Shop extends Model
{
    protected $guarded = [ 'id' ];
    protected $table = "shops";

    /**
     * returns the Owner of this Shop
     */
    public function owner(){
        return $this->belongsTo('AppUser');
    }
}

Любая помощь будет очень оценена. Благодарю!

623 votes

0 answers

Get the solution ↓↓↓

I am creating new composer PHP package. and I ran into error «Error: Call to a member function connection() on null»
I was trying to connect to database using «use IlluminateDatabaseCapsuleManager as Capsule;». here is my capsule code

<?php

namespace APN;

use IlluminateDatabaseCapsuleManager as Capsule;

trait DB
{
    public function __construct()
    {
        $capsule = new Capsule;
        $capsule->addConnection([
            'driver' => DBDRIVER,
            'host' => DBHOST,
            'database' => DBNAME,
            'username' => DBUSER,
            'password' => DBPASS,
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
        ]);
        $capsule->setAsGlobal();
        $capsule->bootEloquent();
    }
}

?>

<?php

namespace APNOrderPortal;
use APNModelsToolsNBNRestLocation;
use APNModelsToolsNBNCSA;

/**
 * OrderAPI
 */
class OrderAPI
{
    use DB;
    public function productOrderQualification() {
        print_r(ToolsNBNCSA::all())
    }
}

when I run the unit test it throws «Error: Call to a member function connection() on null» at line print_r(ToolsNBNCSA::all()).
any help would be appreciated

2021-12-20

Write your answer


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-12-20

Link To Source

Link To Answer
People are also looking for solutions of the problem: constant expression contains invalid operations

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

Понравилась статья? Поделить с друзьями:
  • Error call hotline перевод
  • Error calculating max stack value
  • Error caching lexicon topic lexicon ru core resource
  • Error cached plan must not change result type
  • Error cache miss php