UserProductsController
class UserProductsController extends Controller
{
public function index()
{
$products = Product::get();
return view ('products')->with(compact('products'));
}
public function product_categories()
{
$categories = Category::all();
return view ('categories')->with(compact('categories'));
}
}
products_table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('prod_name');
$table->string('prod_brand')->nullable();
$table->unsignedBigInteger('cat_id');
$table->string('prod_image_path')->nullable();
$table->timestamps();
$table->foreign('cat_id')
->references('id')
->on('categories')
->onDelete('cascade');
});
}
categories_table
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('cat_name');
$table->string('cat_image_path')->nullable();
$table->string('cat_description')->nullable();
$table->timestamps();
});
}
Product Model
class Product extends Model
{
public function category()
{
return $this->belongsTo('App\Category','category_id');
}
}
Category Model
class Category extends Model
{
public function category()
{
return $this->hasMany('App\Product');
}
}
My route is
Route::get('/All_Products', 'UserProductsController@index')->name('All_Products');
Route::get('/product_categories', 'UserProductsController@product_categories')->name('categories');
How can I get all products with the same category? As this is my first project I am spending much more time on this. But nothing worked for me. Can anyone guide me, please?