1
I use https://laravel-admin.org/docs/en/README on my site.
I have two models Post
and PostImage
.
In the Post
model in the controller, I added fields that add images to the PostImage
model, everything works and the images are saved, here is the code:
/**
* Make a form builder.
*
* @param int|null $id
*
* @return Form
*/
protected function form($id = null)
{
$form = new Form(new Post());
$form->column(
1 / 2,
function (Form $form) use ($id) {
$form->switch('status', __('Status'));
$form->number('order', __('Order'))->default(10)->required();
$form->text('title', __('Title'))->required();
$form->ckeditor('description', __('Description'))->required();
}
);
$form->column(
1 / 2,
function (Form $form) {
$form->hasMany(
'postImages',
'Images',
function ($form) {
if ($form->model()) {
$href = admin_url('post-images/' . $form->model()->id . '/edit');
$form->html(
'<div class="pull-right"><a class="btn btn-primary btn-sm" href="' . $href . '"><span class="fa fa-edit"></span> Edit</a></div>'
);
}
$form->image('img_preview', __('Preview image'))->move(PostImage::PATH_PREFIX_PREVIEW)->required();
}
);
return $form;
}
Now I need to resize the image and resave it, for this I add $form->saved()
here with the corresponding code, now this is what it looks like:
/**
* Make a form builder.
*
* @param int|null $id
*
* @return Form
*/
protected function form($id = null)
{
$form = new Form(new Post());
$form->column(
1 / 2,
function (Form $form) use ($id) {
$form->switch('status', __('Status'));
$form->number('order', __('Order'))->default(10)->required();
$form->text('title', __('Title'))->required();
$form->ckeditor('description', __('Description'))->required();
}
);
$form->column(
1 / 2,
function (Form $form) {
$form->hasMany(
'postImages',
'Images',
function ($form) {
if ($form->model()) {
$href = admin_url('post-images/' . $form->model()->id . '/edit');
$form->html(
'<div class="pull-right"><a class="btn btn-primary btn-sm" href="' . $href . '"><span class="fa fa-edit"></span> Edit</a></div>'
);
}
$form->image('img_preview', __('Preview image'))->move(PostImage::PATH_PREFIX_PREVIEW)->required();
}
);
$form->saved(
static function ($form) {
/**
* @var PostImage $postImage
* @var Request $request
*/
$postImage= $form->model();
$request = request();
if ($request->file('img_preview')) {
$postImage->copyImg(
'img_preview',
180,
120,
$postImage->img_preview,
PostImage::PATH_PREFIX_PREVIEW
);
}
}
);
}
);
return $form;
}
But it doesn't work, there are no errors. The function itself just doesn't work. Although the code is working, when I use this $form->saved()
in the PostImage
model controller, everything works and the image is resized.
There is an assumption that I am trying to store the PostImage
model inside the Post
model, but this does not work like that.
How can this be fixed? I would be grateful for any hint..
0 comments:
Post a Comment
Thanks