简体   繁体   中英

Laravel error compact(): Undefined variable

i got error compact(): Undefined variable: 1 in { return view('front.catepro',compact('category_products',$id_)); } { return view('front.catepro',compact('category_products',$id_)); }

but i all data correct in db and other route

<?php

namespace App\Http\Controllers;

use App\Products_model;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $products=Products_model::all();
        return view('front.home',compact('products'));
    }

    public function shop()
    {
        $products=Products_model::all();
        return view('front.shop',compact('products'));
    }

    public function showCates($id)
    {
        $category_products=Products_model::where('category_id',$id)->get();
        $id_=$id;
        return view('front.catepro',compact('category_products',$id_));
    }
}

Why using extra variable when you can directly send parameter like

public function showCates($id)
{
    $category_products=Products_model::where('category_id',$id)->get();
    return view('front.catepro',compact('category_products','id'));
}

It should be like this

$category_products=Products_model::where('category_id',$id)->get();
$id=$id; //Remove underscore
return view('front.catepro',compact('category_products','id'));

This will work

public function showCates($id)
{
    $category_products=Products_model::where('category_id',$id)->get();
    $id_=$id;
    return view('front.catepro',compact('category_products','id'));

}

But No need to assign id again in controller.Because you get it so just pass it my suggetion to you

public function showCates($id)
{
    $category_products=Products_model::where('category_id',$id)->get();
    return view('front.catepro',compact('category_products','id'));

}

its perfect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM