> For the complete documentation index, see [llms.txt](https://taffo.gitbook.io/hotcoffee/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://taffo.gitbook.io/hotcoffee/customization-and-logic/helper-methods.md).

# Helper Methods

### Introduction

HotCoffee comes with some helper functions that can help speed up your development. You can also use the HotCoffee facade.

### settings($key, $default)

Get a global setting value. \
`string $key` - Key of the setting.\
`string $default` - Default value, if key is not found.

```markup
<title> {{ settings('website_name') }} </title>
```

```php
use TaffoVelikoff\HotCoffee\Facades\HotCoffee;

public function index() {
    $title = HotCoffee::settings('website_name');
    return view('home', compact('title'));
}
```

### menu($keyword, $type)

Get a menu and it's elements by keyword.\
`string $keyword` - Keyword of the menu.\
`string $type` - Type of the menu or blade template to use when rendering.

```markup
<!-- Get menu with key of 'main' and render as unstyled unordered list -->
{{ menu('main') }}

<!-- Get menu with key of 'main' and render using bootstrap -->
{{ menu('main', 'bootstrap') }}

<!-- Render using a custom view resources/views/main_menu.blade.php -->
{{ menu('main', 'main_menu') }}
```

```php
use TaffoVelikoff\HotCoffee\Facades\HotCoffee;
...

// Get menu items as collection
$menuItems = HotCoffee::menu('main', 'collection');

// Get as a json string
$menuItems = HotCoffee::menu('main', 'json');
```

### is\_json($string)

Check if a given string is in JSON format.\
`string $string` - String to check.

```php
is_json('{ "name":"John" }'); // returns true
is_json('is this json?'); // returns false
```

### language\_fields($fields, $edit)

Automatically generates HTML fields for the translatable attributes of a model.\
`array $fields` - HTML fields to be generated.\
`mixed $edit` - Model to be updated.

```php
{!! language_fields([
    'name' => [
        'type' => 'text', 
        'title' => 'Name of product'
    ],
    'description' => [
        'type' => 'textarea', 
        'title' => 'Description of product', 
        'class' => 'tinymce',
        'hr'    => true
    ],
    'notes' => [
        'type' => 'textarea', 
        'title' => 'Additional Notes', 
        'info' => [
            'type'    => 'success',
            'content' => 'You can leave some additional notes here.'
        ], 
        'rows' => '4'
    ]
], $product ?? null) !!}
```

{% hint style="info" %}
Wrap the `language_fields()` method around `{!! !!}` in your blade templates, instead of `{{ }}` to display the unescaped HTML output.
{% endhint %}

The above example will produce these HTML fields:

* Input of type `"text"` with name `"name"` and label text `"Name of product"`.
* Textarea with name `"description"`, label text `"Description of product"` and additional class `"tinymce"`. Because of the `hr => true` a horizontal line will be added after the field to serve as a separator.
* Textarea of 4 rows height, name `"notes"`, label text `"Additional Notes"` and additional information text bellow the field `"You can leave some additional notes here"`, colored in green (bootstrap `success` class is added to the text `div`).

If you want to change the template used to render the translatable fields you can copy `vendor/taffovelikoff/hotcoffee/resources/views/admin/components/language_fields.blad.php` to `resources/views/vendor/hotcoffee/admin/components/language_fields.blad.php` and edit as you desire.

### sef\_field($edit)

Generates field for the SEF keyword (for search engine friendly URLs).\
`mixed $edit` - Model to be updated.

<div align="left"><img src="/files/-M2DqzhDyrnuRoQJ9GkC" alt=""></div>

```markup
{!! sef_field($product ?? null) !!}
```

Your model should use the `TaffoVelikoff\LaravelSef\Traits\HasSef` trait. You can create the custom URL by using `$product->createSef('custom_url_name');` or update it with `$product->updateSef('new_url');`.

### image\_attachments\_field($edit)

Generates an upload field for the image attachments.\
`mixed $edit` - Model to be updated.

<div align="left"><img src="/files/-M2Drof-XDypoLSQTIKK" alt=""></div>

```markup
{!! image_attachments_field($product ?? null) !!}
```

Your model should use the `Bnb\Laravel\Attachments\HasAttachment` trait.&#x20;

```php
// Attach the images
foreach($request->file('images') as $file) {
    $product->attach($file, ['group' => 'images']); 
}

// Get image attachments
$attachments = $product->attachment('images');
```

### thumbnail($filepath, $dimensions, $fit, $source)

{% hint style="warning" %}
&#x20;Be careful when/how you use this. It can slow down page loading time.
{% endhint %}

Dynamically generates a thumbnail for an image, stores it in the cache and renders it.\
`string $filepath` - Path to an image file.\
`mixed $dimensions` - String or array of dimensions. For example `[300, 400]` will create a thumbnail with width of **300px** and height of **400px** and `'300'` will create a square image of **300px**.\
`string $fit` - Sets how the image is fitted to its target dimensions. Can be  "contain", "max", "fill", "stretch" or "crop".\
`mixed $source` - Source directory to search for the image. By default it's the `public` folder.

```markup
<!-- Thumbnail for public/images/logo.png with dimensions of 400x400 -->
<img src="{{ thumbnail('images/logo.png', '400') }}" />

<!-- Thumbnail for public/images/logo.png with dimensions of 500x400 and crop -->
<img src="{{ thumbnail('images/logo.png', '400', 'crop') }}" />
```

{% hint style="info" %}
Attachments have their own `thumbnail()` method.\
`<img src="{{ $attachment->thumbnail([800, 600]) }}" />`
{% endhint %}

### language\_validation\_rules($ruleLine)

If you have used the `{!! language_fields($fields) !!}` helper method to generate the HTML fields for the translatable properties in your view you can also use `language_validation_riles()` to generate validation rules for all languages in your form requests or controllers. \
`array $ruleLines` Array of validation rules.

```php
$rules = language_validation_rules(
    'title'     => 'required|min:3',
    'content'   => 'required',
);

// Given that we have 4 locales in hotcoffee.php (en, bg, fr and de) will return
[
    'title.en.title'   => 'required|min:3',
    'title.bg.title'   => 'required|min:3',
    'title.de.title'   => 'required|min:3',
    'title.fr.title'   => 'required|min:3',
    'content.en.title' => 'required',
    'content.bg.title' => 'required',
    'content.de.title' => 'required',
    'content.fr.title' => 'required',
];
```

Now whenever add more locales you do not need to go back to the form request (or controller) and write validation more validation rules.

### language\_validation\_messages($messageLines)

Generates validation messages for translatable fields for every languages defined in hotcoffee.php config file. It is very similar to `language_validation_riles()` but it applies to the custom validation messages.\
`array $messageLines` Array of custom validation messages.

```php
/**
 * Example form request using language_validation_rules()
 * and language_validation_messages() helper methods.
 */

namespace App\Http\Requests\Admin;

use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;

class StoreProduct extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
    
        // For non-translatable (or normal) fields
        $normal = [
            'price'   => 'numeric',
        ]; 
        
        // For translatable fields
        $translatable = language_validation_rules([
            'title'     => 'required|max:64|min:3',
            'content'   => 'required',
        ]);

        // Merge all
        return array_merge($normal, $translatable);

    }
    
    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        
        // For non-translatable (or normal) fields
        $normal = [
            'price.numeric'     => __('admin.err_price_not_numeric'),
        ];

        // For translatable fields
        $translatable = language_validation_messages([
            'title.required'     => 'admin.err_title_required',
            'title.max'          => 'admin.err_title_max',
            'title.min'          => 'admin.err_title_min',
            'content.required'   => 'admin.err_content_required',
        ]);

        // Merge all
        return array_merge($normal, $translatable);
    }
}
```

Or even a cleaner way:

```php
public function rules()
{
    return array_merge(
        [
            'price'   => 'numeric'
        ],
        language_validation_rules([
            'title'     => 'required|max:64|min:3',
            'content'   => 'required',
        ])
    );
}
```
