Undefined variable error exception in view

1.3k Views Asked by At

Controller method

 public function create(Request $request )
{
   $client_id = $request->input('client_name');
   //$userid = \Auth::user()->id;
   $invoice_id = Invoice::create([
    //'userid'=>$userid,
    'clientid'=>$client_id,
    ])->id;

    return redirect('invoice/create/'.$invoice_id);
}

View Where I'm getting an error

  @if($invoice_product->product_qty!=null)
       value="{{$invoice_product->product_qty}}"
  @endif

Model

  namespace App;

 use Illuminate\Database\Eloquent\Model;

class InvoiceProducts extends Model
{
protected $fillable = ['invoice_id'];
}

and the error Undefined variable: invoice_product (View: C:\xampp\htdocs\cs\resources\views\invoice\create.blade.php)

2

There are 2 best solutions below

0
Gabriel On

Try using 'with'

return redirect('invoice/create/'.$invoice_id)->with($invoice_id);

0
Amin.Qarabaqi On

It's not possible to inject variable into the view while redirecting!

there is two way for you to do that. first load view inside the create. and second get $client_id variable inside the invoice/create/ route controller. so you can inject your variables into your views when loading theme.

there is one important point. if the view is separated from a controller function then it should load it's own variables independently (inside the functions that load the view). otherwise it should be loaded inside of that controller.