shahzad1122
shahzad1122

Reputation: 285

How to show records from two different tables in same view in laravel

I am here stuck in this issue: The issue is i want to load the 2 column values from two different tables in same view and view in which i want to show the values is already having controller method: I will explain you with my code:

My controller method:

                   public function pageListHere()
   {
                   $list = PageList::all();
                   return view('page-list',compact('list'));
}

this is my method using PageList model table name is (page_master).

And my view is:

            @foreach($list as $key => $value)
            <tr>
            <input type="hidden" id="rwid" value="{{$value->id}}"/><td></td>
            <td><p data-placement="top" data-toggle="tooltip" title="" data-original-title="Tolltip">{{$value->page_name}}</p></td>
            <td>  <a href="" class="pglst-lnk">  {{$value->page_url}</a</td>
           <td>  

Now here i want to add two more values in blade template like {{$value->coupon_count}} and {{$value->total sum}} But these two values are in different tables How i can get these two values from different tables while i am having same views and i have already define controller method:

Any help would be highly appreciated!!

    class PageList extends Model
     {
     protected $table = 'page_master';

    protected $appends = ['page_particulars','page_coupon'];

    protected $fillable = ['business_id', 'page_url', 'page_name'];

   public function getpageParticularsAttribute(){


  }
public function getpageCouponAttribute(){

      }
  }

              class PageCoupon extends Model
               {
             protected $table = 'page_coupon';

         protected $fillable = ['page_id','code','is_ordered','user_limit'];

       }

and 2nd model is:

               class Sale extends Model
               {
                protected $table = 'page_particulars';

protected $fillable = ['user_id','product_asin','page_expiry_date','market_place','promo_title','regular_price','promo_price','company_logo','coupon_file','email_from','email_subject','facebook_link','twitter_link','website_link','email_body'];

}

Upvotes: 1

Views: 1657

Answers (1)

athulpraj
athulpraj

Reputation: 1577

You can either add a relation to the other table In your Model add

public function particulars()
{
    return $this->hasOne('App\Sale','page_id');
}

and use 

$value->particulars->regular_price;

or you can use Eloquent append to add new values to the same model

In your Model add

  protected $appends = ['coupon_count','total_sum']

and a function to get the attribute

  public function getCouponCountAttribute(){
     //fetch from other table and return here for example
     return Coupon::where('page_id',$this->id)->count();
  }
  public function getTotalSumAttribute(){
     //fetch from other table and return here
  }

Upvotes: 1

Related Questions