Add image to api response

This commit is contained in:
Philipp Lang 2024-01-14 15:52:54 +01:00 committed by philipp lang
parent 539e41cffe
commit b69c895921
4 changed files with 32 additions and 0 deletions

View File

@ -31,6 +31,7 @@ class FormApiResource extends JsonResource
'config' => $this->config,
'slug' => $this->slug,
'dates' => $this->from->equalTo($this->to) ? $this->from->format('d.m.Y') : $this->from->format('d.m.Y') . ' - ' . $this->to->format('d.m.Y'),
'image' => $this->getMedia('headerImage')->first()->getFullUrl(),
];
}

View File

@ -3,6 +3,7 @@
namespace Database\Factories\Form\Models;
use App\Form\Models\Form;
use Database\Factories\Traits\FakesMedia;
use Illuminate\Database\Eloquent\Factories\Factory;
use Tests\Feature\Form\FormtemplateSectionRequest;
@ -20,6 +21,8 @@ use Tests\Feature\Form\FormtemplateSectionRequest;
*/
class FormFactory extends Factory
{
use FakesMedia;
/**
* The name of the factory's corresponding model.
*

View File

@ -0,0 +1,24 @@
<?php
namespace Database\Factories\Traits;
use Illuminate\Http\UploadedFile;
use Spatie\MediaLibrary\HasMedia;
trait FakesMedia
{
public function withImage(string $collection, $filename): self
{
return $this->afterCreating(function (HasMedia $model) use ($filename, $collection) {
$pathinfo = pathinfo($filename);
UploadedFile::fake()->image($filename, 1000, 1000)->storeAs('media-library', $filename, 'temp');
$model->addMediaFromDisk('media-library/' . $filename, 'temp')
->usingName($pathinfo['filename'])
->usingFileName($pathinfo['basename'])
->toMediaCollection($collection);
});
}
}

View File

@ -5,6 +5,7 @@ namespace Tests\Feature\Form;
use App\Form\Models\Form;
use App\Form\Models\Formtemplate;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class FormApiListActionTest extends TestCase
@ -14,11 +15,13 @@ class FormApiListActionTest extends TestCase
public function testItDisplaysForms(): void
{
Storage::fake('temp');
$this->loginNami()->withoutExceptionHandling();
Formtemplate::factory()->name('tname')->sections([FormtemplateSectionRequest::new()->name('sname')])->create();
$form = Form::factory()
->name('lala 2')
->excerpt('fff')
->withImage('headerImage', 'lala-2.jpg')
->description('desc')
->from('2023-05-05')
->to('2023-06-07')
@ -33,6 +36,7 @@ class FormApiListActionTest extends TestCase
->assertJsonPath('data.0.excerpt', 'fff')
->assertJsonPath('data.0.description', 'desc')
->assertJsonPath('data.0.slug', 'lala-2')
->assertJsonPath('data.0.image', $form->getMedia('headerImage')->first()->getFullUrl())
->assertJsonPath('data.0.dates', '05.05.2023 - 07.06.2023')
->assertJsonPath('data.0.from_human', '05.05.2023')
->assertJsonPath('data.0.to_human', '07.06.2023');