2017-01-21 149 views
1

如何將laravel數據從控制器傳遞到視圖而不會獲得未定義的變量產品?將Laravel的控制器數據傳遞給視圖

控制器:

public function postSearch(Request $request){ 

    $text = $request->input('txtsearch'); 


$products = DB::table('products')->where('title', 'Like', $text)->get(); 


return redirect()->route('product.search', ['products' => $products]); 

} 

查看:

@extends('Layout.master') 

@section('content') 

@foreach($products as $product) 


{{$product->title}} 



@endforeach 

    @endsection 
+0

我沒有看到「名」有一個變量? – aimme

+0

更新了我的問題。 – steven

+0

代碼似乎是正確的..但你可能會在錯誤的觀點 – aimme

回答

0

當重定向,您應該使用with()數據閃進會話:從會話

return redirect()->route('product.search')->with(compact('products')); 

,然後得到的數據:

@foreach(session('products') as $product) 
+1

你已經解決了我的問題。 – steven

+1

這是安全的閃光數據進入會議,但? – steven

+0

是的,它很安全。 –

0

https://laravel.com/docs/5.3/redirects#redirecting-with-flashed-session-data

重定向到一個新的URL和閃爍的數據會話通常是在同一時間完成。通常,這是在您向會話刷新成功消息時成功執行操作後完成的。爲方便起見,可以在單個,流利方法鏈上產生RedirectResponse實例和閃存數據到會話:用戶被重定向

return redirect('dashboard')->with('status', 'Profile updated!'); 

後,可以顯示從會話閃蒸消息。例如,使用刀片語法:

@if (session('status')) 
    <div class="alert alert-success"> 
     {{ session('status') }} 
    </div> 
@endif 
0

@foreach中,您必須定義變量$products,因爲在控制器中將其定義爲['products' => $products]

您在代碼中有錯字,試試這個代碼,而不是:

@extends('Layout.master') 

@section('content') 

@foreach($products as $product) 

    {{$product->title}} 

@endforeach 

@endsection 

希望幫助

+0

否這不起作用仍然undefined - 產品 – steven

+0

你確定你把它改成'@foreach($ products as $ product)'?你的代碼是'@foreach($ product as $ products)',一定要改變它,並確保你調用了正確的變量'{{$ product-> title}}' –

+0

你的代碼看起來不錯,恐怕這只是'@ foreach'函數中的錯字 –

相關問題