Tojo
Tojo

Reputation: 249

Condition in controller laravel

I have this code in my Laravel controller

public function index($id=false) {
    //get resto by name
    $resto_nom = DB::table('restos as r')
        ->JOIN('produit as p', 'p.r_id', '=', 'r.r_id')
        ->JOIN('categorie as c', 'c.ca_id', '=', 'p.ca_id')
        ->WHERE('r.r_nom', $id)
        ->WHERE('p.po_etat', 1)
        ->get();

    foreach ($resto_nom as $r):
        $r_nom = $r->r_nom;
        $r_description = $r->r_description;
        $r_specialite = $r->r_specialite;
        $meta = $r_nom.', '.$r_specialite.", restaurant NosRepas, repas";
        $description = $r_nom.' - '.$r_specialite.'. '.$r_description;
    endforeach;

    if($id != $r_nom){
        return view('frontend.pages.resto', compact('meta', 'description', 'resto_nom'));
    }else{
        return view('frontend.pages.resto', compact('meta', 'description', 'resto_nom'));
    }
}

I have error after Undefined variable: r_nom My goal is displaying if the value found is correct so view display and so incorrect it returns 404 not found.

Upvotes: 1

Views: 796

Answers (1)

Laerte
Laerte

Reputation: 7083

You have to set the variable before foreach, otherwise it will be available only inside the loop. Try this:

$r_nom = null;
foreach ($resto_nom as $r):
    $r_nom = $r->r_nom;
    $r_description = $r->r_description;
    $r_specialite = $r->r_specialite;

    $meta = $r_nom.', '.$r_specialite.", restaurant NosRepas, repas";
    $description = $r_nom.' - '.$r_specialite.'. '.$r_description;
endforeach;

Upvotes: 1

Related Questions