skip to Main Content

i am biginner , in body of html i have a input that filled by table row clicking:

<input id="office_id" disabled>

i want to place diffrent tag in body by value of office_id,if has value ,call PUT method and if is null value in office_id call POST method:

@if (?????)
     <form method="POST" action="{{ route('office.store') }}">
          <button type="submit" id="saveBtn" class="btn btn-warning" style="width: 95px;"> save</button>
      </form>
@else
     <form method="PUT" action="{{ route('office.update',$office->office_id) }}">
           <button type="submit" id="saveBtn" class="btn btn-warning" style="width: 95px;"> update</button>
     </form>
 @endif

What code should I write inside the if condition?

2

Answers


  1. In this code the empty() function is used to check if the office_id is empty or not. If it’s empty, it means you’re creating a new office, so the form uses the POST method and directs to the office.store route. If it’s not empty, it means you’re updating an existing office, so the form uses the POST method with the @method(‘PUT’) directive to override the method and directs to the office.update route with the specific office_id.

    @if (empty($office->office_id))
        <form method="POST" action="{{ route('office.store') }}">
            <button type="submit" id="saveBtn" class="btn btn-warning" style="width: 95px;">Save</button>
        </form>
    @else
        <form method="POST" action="{{ route('office.update', $office->office_id) }}">
            @method('PUT') {{-- Add this line to specify the method as PUT --}}
            <button type="submit" id="saveBtn" class="btn btn-warning" style="width: 95px;">Update</button>
        </form>
    @endif
    
    Login or Signup to reply.
  2. Your code has a few problems besides your question: I will try addressing both in my answer:

    Security

    Whenever working with forms, always make sure @csrf is present in your form to prevent potential XSS attacks.

    Solution

    Since you use blade templates you can conditionally use just one form to fulfil both the condifitons:

    <form id="officeForm" method="{{ !empty($office->office_id) ? 'PUT' : 'POST' }}"
          action="{{ !empty($office->office_id) ? route('office.update', $office->office_id) : route('office.store') }}">
        @csrf
        @if(!empty($office->office_id))
            @method('PUT')
        @endif
        <button type="submit" id="saveBtn" class="btn btn-warning" style="width: 95px;">
            {{ !empty($office->office_id) ? 'Update' : 'Save' }}
        </button>
    </form>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search