0

I'm working on a simple calculator app in Laravel Blade. We have not moved to models yet, just working in views and routes, so I keep running into options I haven't learned how to use yet.

My application is running without issue but is not retaining the selected value in the dropdown on POST. I am able to print the value to the screen, and it is working in a later selector. I think I just need to write an if statement in the options to set the selected value, but I can't find syntax that I understand/am allowed to use in this project.

    <div class="form-group">
      <select class="form-control form-control-lg" id="operatorInput" name="operatorInput" value="{{Session::get('operator')}}">
        <option value="+" @if(Session::get('operatorInput') == "+" ? "selected" : "" )@endif>Addition (+)</option>
        <option value="-" @if(Session::get('operatorInput') == "-" ? "selected" : "" )@endif>Subtraction (-)</option>   
      </select>
    </div>

I get a throwable error on this example, so I know it isn't correct.

katies1987
  • 51
  • 7
  • Does this answer your question? [How can I set the default value for an HTML – edgarzamora Nov 08 '19 at 00:15
  • No, it doesn't. I want to set the selection and then pass it to POST so my dropdown displays the value selected until I clear it. Setting the default just makes that value the one that is held in session and is then posted. Thank you though! – katies1987 Nov 08 '19 at 02:31

1 Answers1

0

The throwable error is due to calling the Session Facade without the \ root indicator, use the session helper instead

For example routes/web.php

Route::get('/', function () {
    session(['operatorInput' => '-']);
    return view('welcome');
});

And welcome.blade.php

<div class="form-group">
    <select class="form-control form-control-lg" id="operatorInput" name="operatorInput"
        value="{{ session('operator') }}">
        <option value="+" {{  (session('operatorInput') == "+") ? "selected" : "" }}>Addition (+)</option>
        <option value="-" {{  (session('operatorInput') == "-") ? "selected" : "" }}>Subtraction (-)</option>
    </select>
</div>

Result

enter image description here

You can keep your current code but you need to add a backslash \ before the \Session facade alias, but I find the helper function to be more elegant for a view file (and shorter)

Hope this helps

Salim
  • 9,886
  • 5
  • 23
  • 55