# [Usage](../../../usage.md) > Resource

Use a Resource when a Model needs standard list/create/edit/delete pages without hand-writing routes, controllers and Blade views. It wires the [Form component](../../components/forms/form.md) (with [form autofill](form_autofill.md)) to a [Table](../../components/visuals/table.md), and built-in [Users resource](users_resource.md) / [Roles resource](roles_resource.md) are the same template pre-configured.

A 'Resource' is a simple class template that simplify and accelerate the record storing and viewing process.

- Generates automatically all the routes to view, create and update records of a Model.
- Generates automatically all the blade views to view, create and update records of a Model.

---
## Creation

All resource classes must be created inside the folder:
```html
/app/Resources/*
```

The class name is not relevant and will not be considered in the resource creation, is only useful to the user.

Example of a resource:

```php
class PeopleResource extends KFramework\Templates\Resource
{
    public $resourceName = "people";
    public $resourceLabel = "People";
    public $resourceModel = Person::class;

    protected function formSchema($record)
    {
        return [
            Input::make('name'),
            Input::make('surname')
        ];
    }

    public function table()
    {
        return parent::table()->setSchema([
            TableColumn::make('name')
                ->setGroupable()
                ->setLabel('Name'),
            TableColumn::make('surname')
                ->setGroupable()
                ->setLabel('Surname'),
        ])
            ->setPageable();
    }

}
```

At the application boot, the class will automatically registered and all its routes.

In this case, the resource is available at the URL:
```html
/resources/people
```
The url always starts with `/resources/` and then the resource name. Is strongly advised to not use special chars in the name.

At `/resources/people` location the user can find a table, configured as above, with buttons to add, edit or delete the records for the model `Person`, with its form.

## Personalization

`$resourceName` and `$resourceModel` are fundamental for the Resource, and cannot be avoided. The resource name provide a name for the view and for the routes, and the resource model is the class where to fetch the record.

Instead `$resourceLabel` is optional, but is advised to choose one.

```php
public $resourceName = "people";
public $resourceLabel = "People";
public $resourceModel = Person::class;
```

Other parameters:

```php
public $resourceAllowDuplication = false;
// It will spawn a button to duplicate your record data into the form, the action function used is 'store',
// so it will create a new record. You can manipulate the save using the fact that the 'id' is passed to the request.

public $resourceAllowSoftDelete = false;
// Will enable soft-delete for the resource record. If column is found, will set 'deleted_at' at now(). If no deleted_at
// is found, then it will try for column 'deleted' and try to set it to 1 (integer). If enabled the query will
// automatically filter deleted records.
```

if duplication is enabled, you will get a `$isDuplicating` variable in your resource class, which can be used to make manipulations:

```php
return parent::form($record)
    ->setSchema([
        Input::make('name')
            ->setRequired()
            ->setValidate([!isset($record) || $this->isDuplicating ? 'unique:customers,name' : null])
            ->setLabel('Name')
```

in this example, the validator is checking the unique name for customer, but only if is in create or duplicate view and not in edit view. Because `$record` is passed to the form if is duplicating values.

### Form

The form can be set in two ways.

1. Using the `formSchema` function:

```php
protected function formSchema($record)
{
    return [
        Input::make('name'),
        Input::make('surname')
    ];
}
```
The formSchema function provides a very easy approach, but is limited: only the schema of the form can be defined and lacks personalization, like form columns or enabling/disabling buttons.

2. Using the `form` function:

```php
public function form($record): Form
{
    return parent::form($record)
        ->setColumns(2)
        ->setSchema([
            Input::make('name'),
            Input::make('surname')
        ]);
}
```
This approach offers complete control over the form configuration. Is strongly advised to use `parent::form($record)`, because the Resource template has already some specific configuration over the Form component.

**NOTE**: in both approaches, the `$record` is passed to the function to do manipulations on the form. If `$record` is present, then the user is in the edit page.
**NOTE 2**: if custom `store` or `update` function are not defined, the Form fields should have the same name of the field of the Model.

Having the `$record` in the form function, you can also set a custom additional label, using record if you need it:

```php
public function form($record): Form
{
    $this->resourceRecordLabel = isset($record) ? $record->name : '';

    return parent::form($record)
        ->setColumns(2)
        ->setSchema([
            Input::make('name'),
            Input::make('surname')
        ]);
}
```

in this case, the `$record->name` will be added to the edit page for the record.

> NOTE: both in edit or duplication form, the primary key of the $record will be automatically fetched and injected as hidden fields, so you can simply get it from the request if you want to do some manipulations, and is not necessary to place it as hidden fields every time.

### Table

The `table` function inherit a pre-configured table with standard buttons: `new`, `edit`, `delete`.

```php
public function table()
{
    return parent::table()->setSchema([
        TableColumn::make('name')
            ->setGroupable()
            ->setLabel('Name'),
        TableColumn::make('surname')
            ->setGroupable()
            ->setLabel('Surname'),
    ])
        ->setPageable();
}
```

In the parent function the table is:
```php
public function table()
{
    return Table::make()
        ->setHeaderSchema([
            $this->resourceNewButton
        ])
        ->setButtons([
            $this->resourceEditButton,
            $this->resourceDeleteButton,
        ])
        ->setQuery($this->query());
}
```
You can use parent table and redefine the table by simply repeating methods you want to change.

### Query

Not always the query expected for the model is:
```php
public function query()
{
    return $this->resourceModel::query();
}
```

you can redefine the query of the resource by override the `query` function.

### Personalized store, update, delete

The standard function in the resource class to store, update or delete a record are:

```php
public function store(Request $request)
{
    $data = $request->all();
    $record = $this->resourceModel::create($data);

    return $record;
}

public function update(Request $request, $id)
{
    $record = $this->resourceModel::findOrFail($id);
    $data = $request->all();
    $record->update($data);

    return $record;
}

public function delete($id): bool
{
    try {
        $record = $this->resourceModel::find($id);
        if($record) {

            $record->delete();

            $record = $this->resourceModel::find($id);

            if($record) {
                return false;
            } else {
                return true;
            }
        }

        return true;

    } catch(\Exception $e) {
        Log::error($e->getMessage());
        return false;
    }
}
```

Is possible to override them by simply redefine them in your Resource class, if you need a custom data saving.

**NOTE**: at the end of `store` or `update` is important for the Resource handle to return the `$record`.
**NOTE 2**: at the end of `delete` you must return `true` if deleted with success or `false` if something went wrong.

### returnTo

By default, the store function (saving after record creation) will redirect to the edit record page. The update function (saving after record edit) will instead redirect to the resource list page.

If you need to change this behaviour, just add into the route the parameter `returnTo`:

```php
route('resources.items.edit', ['id' => $item->id, 'returnTo' => '/link_to_return'])
```

After saving, it will redirect to that URL.

---
For more practical example of configuration, see the [User resource](users_resource.md) or the [Roles resource](roles_resource.md).

## Example

Minimal end-to-end wiring:

```php
// app/Resources/CustomerResource.php
class CustomerResource extends KFramework\Templates\Resource
{
    public $resourceName = "customers";
    public $resourceLabel = "Customers";
    public $resourceModel = Customer::class;

    protected function formSchema($record)
    {
        return [
            Input::make('name'),
            Input::make('surname'),
        ];
    }
}
```

```html
<!-- any Blade nav -->
<a href="/resources/customers">Customers</a>
```

Visiting `/resources/customers` shows the table, `/resources/customers/create` and `/resources/customers/{id}/edit` reuse the same schema with [form autofill](form_autofill.md).

## See also

- [Usage](../../../usage.md)
- [Form component](../../components/forms/form.md) — `setFormRecord()` used internally by `parent::form($record)`
- [Form autofill](form_autofill.md) — how edit/duplicate forms are pre-filled
- [Users resource](users_resource.md) / [Roles resource](roles_resource.md)