Home > Software design >  Laravel Undefined variable in where clause
Laravel Undefined variable in where clause

Time:03-30

I'm trying to get the id query parameter from the url. After that, I want to compare the ID in url with artwork ID in database is it the same, then proceed to other action.

However, the $artworks()->id in the where clause is count as undefined variable. The problem is Undefined Variable: artworks. May I know which part I have do wrong?

public function show($id)
{
    if(filled($id)){
        $artworks   = Artwork::all()->where($id,'=',$artworks()->id);
        $categories = Category::all();
        $artist = User::all();
        return view('pages.artwork-detail', compact('categories', 'artworks','artist'));
    }else{
        echo("The id does not exist.");
    }

}

CodePudding user response:

You can just do it this way:

public function show($id)
{
    if(filled($id)){
        $artworks   = Artwork::find($id);
        $categories = Category::all();
        $artist = User::all();
        return view('pages.artwork-detail', compact('categories', 
               'artworks','artist'));
     }else{
       echo("The id does not exist.");
    }

}

CodePudding user response:

I don't know if my answer will work, but I can definetely fix some issues in your code.

public function show($id)
{
    if(!filled($id)) return echo("The id does not exist.");
    
    // I don't know $id belongs to what. If it's artworks' id:
    $artworks   = Artwork::findOrFail($id);
    // Otherwise, let's say it's user_id on the artworks table:
    $artworks   = Artwork::where('user_id', $id)->get();
    // But if it's, use the following line instead of the other one.
    
    
    $categories = Category::all();
    
    $artist = User::all();
    
    return view(
        'pages.artwork-detail',
         compact('categories', 'artworks', 'artist')
    );
}

CodePudding user response:

Try these where condition

$artworks   = Artwork::where('id','=', $id)->get();

$artworks   = Artwork::where('id', $id)->get();

$artworks   = Artwork::find($id);

if you need just one record try these where condition

$artworks   = Artwork::where('id','=', $id)->first();

$artworks   = Artwork::where('id', $id)->first();

$artworks   = Artwork::find($id);
  • Related