Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Laravel 5.0 Relationship In Laravel And How To Use It

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 102
    Comment on it

    In laravel we can create relation between the tables and can use them where ever we need it we need not to create custom queries or use query builder to retrieve data. I have written one of example of my worked project.



    //hasOne relationship models
    public function companyCountry() {
    return $this->hasOne('App\Country', 'id', 'country_id');
    }
    public function companyState() {
    return $this->hasOne('App\State', 'id', 'state_id');
    }
    
    public function compnayUserInfo() {
    return $this->belongsTo('App\User', 'userid', 'userid');
    }
    
    //    hasMany relationship models
    public function companyDepartments() {
    return $this->hasMany('App\CompanyDepartment', 'id', 'company_id');
    }   
    
    public function getDetails_v2(){
        $companyList = $this->where('userid', '=', Auth::user()->userid)->limit(1)->get();
        $company = array();
        $exist = $companyList->toArray(); if(empty($exist)){ return $company; }//Testing if the id exist or not
    
        $company['Company'] = $companyList[0]->toArray();
        $company['UserInfo'] = $companyList[0]->compnayUserInfo->toArray();
        $company['Country'] = $companyList[0]->companyCountry->toArray();
        $company['State'] = $companyList[0]->companyState->toArray();
        return $company;
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: