Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to use same blade to add and edit content

Tags:

php

laravel

blade

I'm creating a simple blog and I'm trying to use the same blade to edit and add article.

I've managed to make it work but I think the way I'm doing it is pretty strange. I have to use in the blade if(!empty($article)) or {{$article->title or ''}}.

Is there a better way of doing it ? Is it bad practice to try to mix them up ?

Here is my add/edit/blade for better understanding

<form method="post" action="/blog/{{$article->id or ''}}">
    {{ csrf_field() }}
    @if(!empty($article))
    <input type="hidden" name="_method" value="PUT">
    @endif
    <input type="text" name="title" class="form-control" value="{{$article->title or ''}}" />
    <textarea name="content" class="form-control">{{$article->content or ''}}</textarea>
    <button type="submit">Envoyer</button>
</form>
like image 508
Baldráni Avatar asked Mar 16 '17 07:03

Baldráni


1 Answers

If create/edit forms are almost the same it's a good idea to use one view and one model method for both forms. You can do something like this:

<form method="post" action="{{ route('article.'.(isset($article) ? 'update' : 'store' )) }}">
    {{ csrf_field() }}
    <input type="hidden" name="_method" value="{{ isset($article) ? 'PUT' : 'POST' }}">
    <input type="text" name="title" class="form-control" value="{{ $article->title or '' }}" />
    <textarea name="content" class="form-control">{{ $article->content or ''}}</textarea>
    <button type="submit">Envoyer</button>
</form>

Another cool way to handle this is to use Laravel Collective package. It has the form model binding feature which is perfect for this kind of situation.

And in a model I usually use updateOrCreate() which can handle both creating a new object and updating existing one.

like image 181
Alexey Mezenin Avatar answered Sep 28 '22 21:09

Alexey Mezenin