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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With