Skip to content

Instantly share code, notes, and snippets.

@maldechavda
Created February 19, 2018 12:30
Show Gist options
  • Save maldechavda/595e9b2651c77b6ac37494368df6a11d to your computer and use it in GitHub Desktop.
Save maldechavda/595e9b2651c77b6ac37494368df6a11d to your computer and use it in GitHub Desktop.
Laravel File Upload test
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Foundation\Testing\RefreshDatabase;
class AddAvatarTest extends TestCase
{
use RefreshDatabase;
/** @test */
public function a_user_may_add_an_avatar_to_their_profile()
{
$this->signIn();
Storage::fake('public');
$this->json('POST', route('avatar', auth()->id()), [
'avatar' => $file = UploadedFile::fake()->image('avatar.jpg')
]);
$this->assertEquals(asset('avatars/'.$file->hashName()), auth()->user()->avatar_path);
Storage::disk('public')->assertExists('avatars/' . $file->hashName());
}
}
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => 'local',
]
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;
class UserAvatarController extends Controller
{
/**
* Store a new avatar.
*
* @return \Illuminate\Http\Response
*/
public function store()
{
request()->validate([
'avatar' => ['required', 'image']
]);
auth()->user()->update([
'avatar_path' => request()->file('avatar')->store('avatars', 'public')
]);
return response([], 204);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment