Within personal and work based projects, creating front end routes files has always brought up the question of whether there should be both a create and an edit page view template.

Although this is the normal convention, managing these views can prove difficult to maintain as editing even a small change on one file leads to consideration and potential change of the other view template.

Whats the alternative?

My new method has been to create a view.blade.php, which serves as a replacement for both create.blade.php and edit.blade.php view templates. The view.blade.php file will have conditions which render the correct text, partials and content depending on the route that the request has been used.

To help with this, I often use a the active package which provides an elegant method to check the current route of the request. The package allows you to do the following:

@if (is_active('users.edit'))
    // Show edit code here
@endif

How will it work within the template?

As a small example, let’s update both the text and the route of a button based on the current route.

<form ...>
   <button type="submit">Create</button>
</form>

We have a form a button to submit the form. Within the create view we would use “Create” to indicate this form will create a new entry. We also may use “Update” to indicate this form will update the current entry.

Using a view.blade.php (combining both the create and edit blade templates into one) and using the active package, we will be able to use the following:

<form ...>
   <button type="submit">{{ is_active('users.edit') ? 'Update' : 'Create' }}</button>
</form>

Here, we check whether or not the current route being accessed has the name users.edit (is it also possible to use urls too). This check is performed using a ternary expression. If true, the template will echo “Update” else it will default to “Create”.

What about the form’s action?

It is possible to use the same logic to conditionally set the route of the view. So this:

<form action="{{ route('users.store') }}" method="POST">
    ...
</form>

Turns into this:

<form action="{{
    is_active('users.edit')
    ? route('users.update', ['id' => $user->id ])
    : route('users.store')
}}" method="POST">
    ...
</form>

Here, we again check if the current route is users.edit however we now render the correct route for the form action.

What about input values?

With input values, we can add a null coalescing operator to check the value:

<input type="text" name="name" value="{{ $user->name ?? '' }}">

This same methodology can be used throughout the template to render condition content. This will also hopefully save time when making changes to such templates, and serve as a reminder than both conditions need to be catered for.

Until next time.