PHP code example of mrzlanx532 / laravel-basic-components
1. Go to this page and download the library: Download mrzlanx532/laravel-basic-components library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mrzlanx532 / laravel-basic-components example snippets
...
use UploadImages;
...
/**
* Если есть константа UPLOAD_FILE_TRAIT_DELETING_FILES и она true,
* то при удалении модели также будут удаляться связанные с ней изображения (и нарезки)
*/
const UPLOAD_FILE_TRAIT_DELETING_FILES = true;
public static $filePropertiesWithSettings = [
'picture' => [
'200' => [200, 200, FileHelper::RESIZE_TYPE_SMART],
'400' => [400, 400, FileHelper::RESIZE_TYPE_FIT_INTO_AREA_WITH_PROPORTIONS],
'600' => [600, 600, FileHelper::RESIZE_TYPE_FIT_INTO_AREA_WITH_PROPORTIONS_AND_COLOR_CANVAS, '#ffffff', 'center'], // Возможные значение 4-го параметра: top-left, top, top-right, left, center, right, bottom-left, bottom, bottom-right
],
'background_picture' => null, // null означает сохранить как есть (без нарезок)
];
...
...
class UserResource extends JsonResource
{
/* @var $resource User */
public $resource;
/**
* @throws InvalidFilePropertiesWithSettingsPropertyConfiguration
*/
public function toArray($request): array
{
return [
'id' => $this->resource->id,
'photo' => $this->resource->getFileLinksBySettings('photo'),
'photo2' => $this->resource->getFileLinksBySettings('photo2', 'http://api.tip.ru'), // возможность кастомно задать домен, не смотря на UPLOAD_FILE_DOMAIN
];
}
}
...
use Mrzlanx532\LaravelBasicComponents\Helpers\FileHelper\FileHelper;
...
class UserResource extends JsonResource
{
/* @var $resource User */
public $resource;
/**
* @throws InvalidFilePropertiesWithSettingsPropertyConfiguration
*/
public function toArray($request): array
{
return [
'id' => $this->resource->id,
'photo1' => FileHelper::getFileLinksBySettings(User::class, 'photo1', $this->resource->photo1),
'photo2' => FileHelper::getFileLinksBySettings(User::class, 'photo2', $this->resource->photo2),
];
}
}
namespace App\Models;
use App\Config\UploadFileConfig;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Builder;
use App\Traits\UploadFile;
/**
* \App\Models\UserFile
*
* @property int id
* @property int user_id
* @property int file_id
* @property Carbon|null deleted_at
*
* @property UploadedFile|null uploadFile
* @property-read File $file;
*
* @method static Builder|ContactFile query()
* @method static ContactFile|null find($id)
* @method static ContactFile findOrFail($id)
*
* @mixin Model
*/
class UserFile extends Model
{
use UploadFile; // Добавляем трейт
use SoftDeletes; // Добавляем SoftDeletes, если требуется
protected $table = 'user_files';
public $timestamps = false;
/**
* Если настройки по-умолчанию не подходят, то создаем метод getUploadFileConfig
*/
public function getUploadFileConfig(): UploadFileConfig
{
return UploadFileConfig::create()
->setAsPublic()
->setForeignKey('file_id');
}
}
...
$user = new User;
$user->save();
if (isset($this->params['files'])) {
foreach ($this->params['files'] as $passedFile) {
$file = new UserFile;
// Свойство `uploadFile` является зарезервированным.
// $passedFile является \Illuminate\Http\UploadedFile
$file->uploadFile = $passedFile;
$files[] = $file;
};
$user->files()->saveMany($files);
}
...
namespace App\Services\Finance\BalanceInvoice;
use App\Models\Finance\BalanceInvoice as FinanceBalanceInvoice;
use Mrzlanx532\LaravelBasicComponents\Service\Service;
class FinanceBalanceInvoiceCreateService extends Service
{
public function getRules(): array
{
return [
'user_id' => 'w FinanceBalanceInvoice();
$balanceInvoice->user_id = $this->params['user_id'];
$balanceInvoice->offer_id = $this->params['offer_id'];
$balanceInvoice->base_type_id = $this->params['base_type_id'];
$balanceInvoice->state_id = $this->params['state_id'];
$balanceInvoice->total = $this->params['total'];
$balanceInvoice->save();
return $balanceInvoice;
}
}
...
public function create(Request $request, FinanceBalanceInvoiceCreateService $financeBalanceInvoiceCreateService): JsonResponse
{
return response()->json(
new FinanceBalanceInvoiceResource(
$financeBalanceInvoiceCreateService->setParams($request)->handle()
)
);
}
...
namespace App\Definitions\Finance\Balance;
use Mrzlanx532\LaravelBasicComponents\Definition\Definition;
class InvoiceBaseDefinition extends Definition
{
const OFFER = 'OFFER';
public static function items(): array
{
return [
self::OFFER => [
'id' => self::OFFER,
'title' => 'Оплата объявления',
],
];
}
}
namespace App\PanelForms\Backoffice\Users;
use App\Http\Resources\Backoffice\Users\User\UserResource;
use App\Models\Users\User;
use Mrzlanx532\LaravelBasicComponents\PanelForm\PanelForm;
class UserPanelForm extends PanelForm
{
protected string $model = User::class;
protected string|null $resource = UserResource::class;
protected function getInputs(): array
{
return [];
}
}
...
public function form(UserPanelForm $userPanelForm): JsonResponse
{
return response()->json($userPanelForm->get());
}
...
namespace App\Http\QueryBuilders;
use App\Models\Finance\BalanceTransaction;
use Mrzlanx532\LaravelBasicComponents\QueryBuilder\QueryBuilder;
use Illuminate\Database\Eloquent\Collection;
class FinanceBalanceTransactionQueryBuilder extends QueryBuilder
{
public function handle(): Collection|array
{
$balanceTransactionQuery = BalanceTransaction::query();
if ($this->request->has('user_id')) {
$balanceTransactionQuery->where('user_id', $this->request->get('user_id'))
}
return $balanceTransactionQuery->get();
}
}
...
public function list(Request $request): JsonResponse
{
return response()->json(
FinanceBalanceTransactionResource::collection(
(new FinanceBalanceTransactionQueryBuilder($request))->handle()
)
);
}
...
namespace App\PanelSet;
use App\Http\Resources\Web\MarketOffer\MarketOfferResource;
use App\Models\Market\Offer\Offer as MarketOffer;
use Mrzlanx532\LaravelBasicComponents\PanelSet\Filters\BooleanFilter;
use Mrzlanx532\LaravelBasicComponents\PanelSet\Filters\SelectFilter;
use Mrzlanx532\LaravelBasicComponents\PanelSet\PanelSet;
class MarketOfferPanelSet extends PanelSet
{
protected string $model = MarketOffer::class;
public string $resource = MarketOfferResource::class;
public string $browserId = 'market_offers';
/**
* Если необходимо передать кастомный способ поиска отличный от LIKE, делаем как в примере 1
*/
public array $fieldsForDefaultSearchFilter = ['costs_type_id', 'payment_type_id'];
protected array $defaultOrderBy = [
'created_at' => 'desc',
// Пример с мапингом: принимаем `created_at`, а в запрос кладем `tips_codes.created_at`
// 'created_at as tips_codes.created_at' => 'desc'
// Для кастомизации смотри "Пример 2"
];
public array $availableOrderBy = [
'created_at',
// Пример с мапингом: принимаем `created_at`, а в запрос кладем `tips_codes.created_at`
// 'created_at as tips_codes.created_at'
// Для кастомизации смотри "Пример 3"
];
public function __construct()
{
parent::__construct();
/**
* Пример 1
*/
$this->fieldsForDefaultSearchFilter = [
'costs_type_id',
'payment_type_id',
function (Builder $query, string|null $searchString) {
$query->OrWhere('id', '=', $searchString);
}
];
/**
* Пример 2
*/
$this->defaultOrderBy = [
'created_at' => function (\Illuminate\Database\Eloquent\Builder $queryBuilder) {
// Пример кастомизации: здесь пишем как обработать поле 'updated_at'
$queryBuilder->orderByRaw('<RAW SQL QUERY>');
}
];
/**
* Пример 3
*/
$this->availableOrderBy = [
'created_at' => function (\Illuminate\Database\Eloquent\Builder $queryBuilder, $field, $direction) {
// Пример кастомизации: здесь пишем как обработать поле 'updated_at'
$queryBuilder->orderByRaw('<RAW SQL QUERY>');
}
];
}
protected function setFilters()
{
$this->filtersManager->add(SelectFilter::class, 'product_id', 'Продукт', function (SelectFilter $selectFilter) {
$exampleOptions = [
0 => [
'id' => 1,
'title' => 'Продукт1'
],
1 => [
'id' => 2,
'title' => 'Продукт2'
],
];
$selectFilter->setOptions($exampleOptions);
});
$this->filtersManager->add(BooleanFilter::class, 'is_price_per_one_is_set', 'Тест', function (BooleanFilter $booleanFilter) {
// В запрос передаем вместо 'is_price_per_one_is_set' => 'is_price_per_one_is'
$booleanFilter->setFilterParamName('is_price_per_one_is');
// Скрываем из интерфейса, но обрабатываем всё равно
$booleanFilter->hidden();
// Делаем фильтр обязательным
$booleanFilter->
...
/**
* @throws InvalidJsonFormatForFiltersParameterException
* @throws InvalidPanelSetConfigurationException
*/
public function browse(MarketOfferPanelSet $marketOfferPanelSet): JsonResponse
{
return response()->json($marketOfferPanelSet->handle());
}
...
namespace App\PanelSets\Backoffice\Suppliers\Levels;
use App\Http\Resources\Backoffice\Suppliers\Levels\LevelListResource;
use App\Models\Suppliers\Levels\Level;
use Mrzlanx532\LaravelBasicComponents\PanelSetSortable\PanelSetSortable;
class LevelPanelSetSortable extends PanelSetSortable
{
protected string $model = Level::class;
public string $resource = LevelListResource::class;
/** [Опционально] Определяем нужна ли поддержка вложенности */
protected bool $isNested = false;
/** [Опционально] Колонка в таблице, которое будет отвечать за порядок */
protected string $orderField = 'order_index';
/** [Опционально] Колонка в таблице, которая определяет родителя при включенной вкложенности */
protected string $parentField = 'parent_id';
/** [Опционально] Колонка, содержащая в себе первичный ключ таблицы */
protected string $identifierField = 'id';
}
use App\PanelSets\Backoffice\Suppliers\Levels\LevelPanelSetSortable;
use Illuminate\Http\JsonResponse;
/**
* GET
* suppliers/levels/browse-sortable
* [backoffice-api]
* Браузер уровней поставщиков сортированный
*
* @param LevelPanelSetSortable $levelPanelSetSortable
* @return JsonResponse
*/
public function browseSortable(LevelPanelSetSortable $levelPanelSetSortable): JsonResponse
{
return response()->json($levelPanelSetSortable->handle());
}
use Mrzlanx532\LaravelBasicComponents\Service\PanelSetSortableUpdateService\PanelSetSortableUpdateService;
use App\PanelSets\Backoffice\Suppliers\Levels\LevelPanelSetSortable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* POST
* suppliers/levels/browse-sortable/update
* [backoffice-api]
* Обновить сортировку браузера
*
* @bodyParam items object[] $request)->handle();
return response()->json(['status' => true]);
}