Home > Software engineering >  How to pass a single value from controller to view Laravel
How to pass a single value from controller to view Laravel

Time:01-24

Hello i have made a function in my controller that generates random number and i want to pass that result number to the view.

This is the code of the controller:

 public function create()
    {
        $randomNumber = random_int(100000, 999999);
        $clients = Client::all();
        $products = Product::all();
        return view('orders/create',compact('clients','products'))
            ->with($randomNumber,(request()->input('page', 1) - 1) * 5);
    }

I have inserted ->with($randomNumber) because i saw that people used this method when they had an array and would call it in the view {{$randomNumber->first}} but as i mentioned above i have a single value only not an array.

This is the view code:

 <input id="orderNumber" type="orderNumber"  name="orderNumber" value="{{ $randomNumber }}" required autocomplete="orderNumber">

But shows me this error:

Undefined variable $randomNumber

CodePudding user response:

If you want send a random number to view you can do this :

public function create()
    {
        $randomNumber = random_int(100000, 999999);
        $clients = Client::all();
        $products = Product::all();
        return view('orders/create',compact('clients','products'))
            ->with('randomNumber',$randomNumber);
    }

Or you want send (request()->input('page', 1) - 1) * 5 named by randomNumber

->with('randomNumber',(request()->input('page', 1) - 1) * 5);
  • Related