Lord Jesus
Lord Jesus

Reputation: 170

laravel- how do I properly test eloquent relationship?

I have four tables: users(master), user_info,user_addresses and user_contacts

I created a eloquent relationship among them something like below:

User Model:

 public function user_info(){


        return $this->hasOne('App\Models\UserInfo');
    }

    /**
     * Get the user address associated with the user.
     */

    public function user_address(){
        return $this->hasMany('App\Models\UserAddress');

    }


    /**
     * Get the user contact associated with the user.
     */


    public function user_contact(){

        return $this->hasMany('App\Models\UserContact');
    }

UserInfo model:

 public function user(){

        return $this->belongsTo('App\Models\User');
    }

UserAddress model:

public function user(){

        return $this->belongsTo('App\Models\User');
    }

UserContact model:

public function user(){

        return $this->belongsTo('App\Models\User');
    }

Table structures:

users -> id , email, password,....other unimportant stuff.
user_info -> id, name, identity num, ......
user_address -> id, user_id, address1, address2,address3, shipping address,....
user_contact-> id, user_id, mobile_num,emergency_num,......

For now id column(auto increment) should be treated as key identifier for each user.

I inserted some dummy data to all the tables and I was wondering how do I test if the relationship and everything is correct (I suppose I have to use php artisan tinker)?

Upvotes: 0

Views: 2045

Answers (2)

Augusto Moura
Augusto Moura

Reputation: 1392

Recommended read: Database Testing, from the Laravel documentation

You may use php artisan tinker and $model->relationName()->attach($anotherModel) to test it out in a development environment, but for anything beyond that, building Factories and tests with PHPUnit are recommended.

Upvotes: 1

Sok Hai
Sok Hai

Reputation: 546

to answer your question:

Here is Tinker Definition

Tinker is a beautiful laravel package. Laravel Tinker is a powerful REPL for the Laravel framework. REPL stands for Read–Eval–Print Loop. This feature is powered by PsySH console.

Main Function of Tinker

The main function of tinker is to allow you to directly interact with laravel application from the command line such as Eloquent ORM, jobs, events, and more.

So the answer is yes. you can use tinker to test your eloquent relationships. for more info you can read Eloquent: Relationships.

and one more thing for your relationship I prefer using camelCase over _. but if you company or your team prefer _. that's find. but if you want to know about laravel best practice you also can read Here for more.

Thank and hope it can help you. have a nice day

Upvotes: 0

Related Questions