TimeRunner2359
TimeRunner2359

Reputation: 47

Undefined index : anything?

When I go to page I get the error : "Undefined index : img". When I use var_dump or print_r function , I can see the whole array and its all OK.

My web.php

Route::get('/Products/{id}','productcontroller@show');

My controller

public function show($id)
{
         $products = DB::select("SELECT * FROM products where id=$id");

    return view("productpage" ,["products"=> $products]);
}

My blade view

@extends("master")
@section("mainpage")
<div class="container">
<img src="{{$products["img"]}}">
<p>{{$products["description"]}}</p>
<p>{{$products["price"]}}</p> 
</div>
@endsection

Upvotes: 2

Views: 78

Answers (1)

Daniel
Daniel

Reputation: 11182

The error occurs because DB::select returns an iterable (an array in Laravel versions prior to 5.3 and a Collection in later versions)

It doesn't matter that it's only a single result - it will still be an array or collection with a single value in it.

You will have to either display it in a loop, or show the first product element by index $products[0]['img']

Also, your code is vulnerable to SQL injection. Please consider using prepared statements to avoid this.

Applying this for your query looks like this

$products = DB::select("SELECT * FROM products where id = :id", ['id' => $id]);

Upvotes: 4

Related Questions