How to use same Blade template for add and edit operation of one controller in Laravel?
Asked Answered
H

2

5

I have a question, I used the same blade template to create and insert. In my controller I created a variable ModificationMode on edit function and on the template I used isset() method.

Controller

public function edit($id)
{
    $ModificationMode = 0;
    $DataPraticien = \App\Praticien::find($id);

    return view('AjoutePraticien', compact('DataPraticien'))->with('ModificationMode', $ModificationMode);
}

View

@if(isset($ModificationMode))

<form method="post" action="{{route('prat.update', $DataPraticien ?? '')}}">
@csrf
@method('PATCH')
    @else
    <form action="{{route('prat.store')}}" method="post">
        @endif
//stuff
//stuff

I make every variable as optional. Is that a good idea? Can this method bring me some issues? How about security?

Hagler answered 14/1, 2020 at 23:44 Comment(0)
U
6

Here i am just explaining you with small example that how you use same form for add and edit. When I need to to the same I do this :

// routes.php
Route::get('test', 'TestController@create');
Route::get('test/{id}', 'TestController@edit');

Controller.php

// TestController.php
public function create()
{
    return view('form');
}

public function edit($id)
{
    $resource = Resource::find($id);

    return view('form', compact('resource'));
}

Blade file

// form.blade.php
<h2>{{ isset($resource) ? 'Edit a Record' : 'Create a new Record' }}</h2>

<form action="{{ isset($resource) ? '/test/' . $resource->id : '/test' }}" method="post">
    <label>Title</label>
    <input type="text" name="title" value="{{ old('title', isset($resource) ? $resource->title : '') }}" />

    <label>Description</label>
    <textarea name="description">{{ old('description', isset($resource) ? $resource->description : '') }}</textarea>

    <button type="submit">{{ isset($resource) ? 'Update' : 'Create' }}</button>
</form>
Urnfield answered 15/1, 2020 at 6:13 Comment(0)
A
0

I think you are correct. If my form is simple then I do similar. Just a $ModificationMode variable does not require for me. what I do...

@if(isset($DataPraticien))

    <form method="post" action="{{route('prat.update', $DataPraticien ?? '')}}">
    @method('PATCH')
@else
    <form action="{{route('prat.store')}}" method="post">
@endif
  @csrf
Absinthism answered 15/1, 2020 at 5:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.