如何检查变量是否在 laravel Blade 中有数据

新手上路,请多包涵

我想检查刀片中是否存在变量..因为我使用了以下几行:

 @if(is_null($products))
    <div class="alert alert-warning">
        <strong>Sorry!</strong> No Product Found.
    </div>
@else

    @foreach($products as $product)
        //
    @endforeach
@endif

问题是当刀片上有 $products 时,我可以在 foreach 循环内部显示,但是当我得到空变量时。我无法显示消息 No Data Found 它只显示空白空间?检查刀片内部的变量是否有任何问题?

控制器代码:

 public function productSearch(Request $request)
    {
        $name = $request->name;
        $products = Product::where('name' , 'like', '%'.$name.'%')->get();
        return view('cart.product',compact('products'));
    }

原文由 User57 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 500
1 个回答

我发现完成您在这里尝试的最有效(也是迄今为止最简单的方法)如下。

 Assumption #1: You Know The Variable Exists Within The View.

REMEMBER: an empty array will always return false.
Therefore, there is no real need to run it through a function like empty or is null.
Comparing it to null will tell you if it exists or not.

(您可以通过检查变量是否不等于 NULL 来绕过这个假设(如果您将该变量传递给视图,这有点臃肿,所以在我看来,我会 KEEP IT SIMPLE STUPID [KISS] - 如果你愿意,你可以在以后进一步重构时尽情发挥)。

反正..

我会坚持使用与您现在非常相似的代码,也许这里的代码将是您视图的代码:

 @if(!$products)

    <div class="alert alert-warning">
        <strong>Sorry!</strong> No Product Found.
    </div>

@else

    @foreach($products as $product)

        // {{ $product . “code goes here.” }}

    @endforeach

@endif

并且您的控制器的代码看起来像这样(您几乎拥有它,请记住: "perfect practice makes perfect!" - 但是,是的,控制器代码:

 public function productSearch(Request $request)
{
    // Easily obtain the name submitted by the form (I assume via the request object
    // dependency injection magic
    $name = $request->name;

    // I would consider using the DB builder tool, as follows, as there is more docs on it
    // see: https://laravel.com/docs/5.6/queries - this will return a collection (iterable)
    $products = DB::table(‘products’)
                ->where('name' , 'like', '%'.$name.’%’)
                ->get();

    // simply passing to the view
    return view('cart.product', compact('products'));
}

您还需要包含 Product 模型、DB (Laravel) 和(通常)请求对象,如下所示:

 // Laravel Dependencies
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
// User Created Model
use App\Product;

希望这对您有所帮助!

原文由 Dilworth 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题