Item Management
Item management is the most advanced example included in the Pro theme, because every item has a picture, belongs to a category and has multiple tags. To access this example click the "Examples/Item Management" link in the left sidebar or add /item to the URL. Here you can manage the items. A list of items will appear once you start adding them (to access the add page click "Add item"). On the add page, besides the Name and Description fields (which are present in most of the CRUD examples) you can see a category dropdown, which contains the categories you added, a file input and a tag multi select. If you did not add any categories or tags, please go to the corresponding sections (category management, tag management) and add some.
The code for saving a new item is a bit different than before (see snippet bellow):
public function store(ItemRequest $request, Item $model)
{
$item = $model->create($request->merge([
'picture' => $request->photo->store('pictures', 'public'),
'show_on_homepage' => $request->show_on_homepage ? 1 : 0,
'options' => $request->options ? $request->options : null,
'date' => $request->date ? Carbon::parse($request->date)->format('Y-m-d') : null
])->all());
$item->tags()->sync($request->get('tags'));
return redirect()->route('item.index')->withStatus(__('Item successfully created.'));
}
Notice how the picture and tags are easily saved in the database and on the disk.
Similar to all the examples included in the theme, this one also has validation rules in place. Note that the picture is mandatory only on the item creation. On the edit page, if no new picture is added, the old picture will not be modified.
public function rules()
{
return [
'name' => [
'required', 'min:3', Rule::unique((new Item)->getTable())->ignore($this->route()->item->id ?? null)
],
'category_id' => [
'required', 'exists:'.(new Category)->getTable().',id'
],
'excerpt' => [
'required'
],
'description' => [
'required'
],
'photo' => [
$this->route()->item ? 'nullable' : 'required', 'image'
],
'tags' => [
'required'
],
'tags.*' => [
'exists:'.(new Tag)->getTable().',id'
],
'status' => [
'required',
'in:published,draft,archive'
],
'date' => [
'required',
'date_format:d-m-Y'
]
];
}
In the item management we have an observer (app\Observers\ItemObserver
) example. This observer handles the deletion of the picture from the disk when the item is deleted or when the picture is changed
via the edit form. The observer also removes the association between the item and the tags.
public function deleting(Item $item)
{
File::delete(storage_path("/app/public/{$item->picture}"));
$item->tags()->detach();
}
The policy which authorizes the user on item management pages is implemented in App\Policies\ItemPolicy.php
.