lundi 1 février 2016

how to make one to many relationship in laravel

i'm trying to make a one to many relationship using eloquent model and want to show the products in the specified category that is my product model :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\softDeletes;

class Product extends Model
{
    //
    use softDeletes;
    protected $table='products';

    public function category(){
        return $this->belongsTo('App\Category');
    }
}

and that is my category model :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\softDeletes;

class Category extends Model
{
    //
    use softDeletes;
    protected $table='category';

   public function product(){
    return $this->hasMany('App\Product','category_id','id');
   }
}

and that's the product controller :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Product;
use App\Category;

class productsController extends Controller
{
    //
    public function getShow($id,Request $request){
            $in=$request->get('id');
            $category=Category::all();
            $product=Product::find($id);
            $products=$product->category()->where('category_id','=',$in);

            return view ('contents.products')->with('products',$products)
                                            ->with('category',$category);
    }
}

and this is the product table :

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('category_id');
            $table->string('describtion');
            $table->string('image_name');
            $table->timestamps();
            $table->softDeletes();
        });
    }

and that is the category table :

public function up()
    {
        Schema::create('category', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
            $table->softDeletes();
        });
    }

and it gives me this error : Call to a member function category() on a non-object

so how can i solve it ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire