Laravel Accessing Foreign Key Using Eloquent Where Clause

Viewed 2857

I have two models called Item and Sale where

class Item extends Model
{   
    public function sale()
    {
        return $this->hasMany('App\Sale', 'sale_id');
    }
}

and

class Sale extends Model
{
    public function item()
    {
        return $this->belongsTo('App\Sale', 'item_id');
    }
}

This is my migration files for Items

public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('code');
            $table->string('name');
            $table->string('location');
            $table->double('buy_price');
            $table->double('sell_price');
            $table->integer('quantity');
            $table->timestamps();
        });
    }

And Sales

public function up()
    {
        Schema::create('sales', function (Blueprint $table) {
            $table->increments('id');
            $table->date('date');
            $table->integer('quantity');
            $table->double('sell_price');
            $table->double('subtotal');
            $table->integer('item_id')->unsigned();
            $table->timestamps();
        });

        Schema::table('sales', function (Blueprint $table) {
            $table->foreign('item_id')->references('id')->on('items')
                  ->onDelete('cascade')->onUpdate('cascade');
        });
    }

I recorded the daily sales data to see what are the items sold that day. Therefore I wanted to view the sales daily. And this is what I have done in my controller.

class SaleController extends Controller
{
    public function show($date)
    {
        $sales = Sale::where('date', $date)->get();
        return view('sale.detail', compact('sales'));
    }
}

And finally in my blade, I did this to call the information of the items

@foreach($sales as $sale)
    <tr>
        <td>{{ $sale->item->code }}</td>
        <td>{{ $sale->item->name }}</td>
        <td>{{ $sale->sell_price }}</td>
        <td>{{ $sale->quantity }}</td>
    </tr>
@endforeach

In the end I got Trying to get property of non-object Can someone enlighten me what is wrong with my code? I am relatively new in Laravel but I'm keen on trying different things to see what this framework can do.

Thanks a lot

2 Answers
Related