skip to Main Content

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" class="form-control @error('name') is-invalid @enderror" name="orderNumber" value="{{ $randomNumber }}" required autocomplete="orderNumber">

But shows me this error:

Undefined variable $randomNumber

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. To set variables not necessary in your case.

    Everything can be done in a more compact manner, like:

    return view('orders/create',[
                'clients' => Client::all(),
                'products' => Product::all(),
                'randomNumber' => random_int(100000, 999999),
            ])->with((request()->input('page', 1) - 1) * 5);
    

    In blade/ view get variable like:

    {{ $randomNumber }}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search