skip to Main Content

I wan to get data for two variables in same method but its not happening

function display(){
    $datas=Req::all();
    $products = Product::all();
    return view ('products.dispaly')->with('products', $products,'datas',$datas);
}

here i want to get data from table and assign them to two separate variables $datas, and $ products? what is the correct way to do it?

4

Answers


  1. You have to use view this way:

    return view(
        'products.dispaly',
        [
            'products' => $products,
            'datas' => $datas,
        ]
    );
    

    Another way that is exactly the same, just less verbose, is to use compact:

    return view('products.dispaly', compact('products', 'datas'));
    
    Login or Signup to reply.
  2. You have view name "dispaly"… I guess it should be: "display".

    Try this:

        return view('products.display', ['products' => $products, 'datas' => $datas]);
    

    or

        return view ('products.display')
                    ->with('products', $products)
                    ->with('datas',$datas);
    
    Login or Signup to reply.
  3. If you have data in variables and want that data on the next page with the same name as the variables I prefer to use "compact" it is a php function that creates an array from variables and their values.

        function display() {
            $datas=Req::all();
            $products = Product::all();
            return view ('products.display', compact('products', 'datas'));
        }
    

    This is the same like:

        function display() {
            $datas=Req::all();
            $products = Product::all();
            return view ('products.display', [
                'products' => $products,
                'datas' => $datas
            ]);
        }
    

    But compact do it for you 🙂

    Login or Signup to reply.
  4. To have an easy code to understand use compact is the best way

    return view('products.dispaly',compact('products','datas'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search