Skip to content

Commit 2f51176

Browse files
committed
feat: ユーザープロフィール画像のアップロード・削除機能を実装
1 parent 049e858 commit 2f51176

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

app/Http/Controllers/Api/UserController.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ public function update(Request $request)
3232
Rule::unique('users')->ignore($user->id),
3333
],
3434
'password' => 'nullable|min:8|confirmed',
35+
'avatar' => 'nullable|string',
3536
]);
3637

3738
// 名前とメールアドレスを更新
@@ -43,6 +44,24 @@ public function update(Request $request)
4344
$user->password = Hash::make($validated['password']);
4445
}
4546

47+
// アバターの処理
48+
if (array_key_exists('avatar', $validated)) {
49+
if ($validated['avatar'] === null || $validated['avatar'] === '') {
50+
// 削除の場合
51+
$user->avatar = null;
52+
} elseif (!empty($validated['avatar'])) {
53+
// 更新の場合
54+
$avatar = $validated['avatar'];
55+
56+
// data:image/png;base64, などのプレフィックスを削除
57+
if (preg_match('/^data:image\/(\w+);base64,/', $avatar)) {
58+
$avatar = substr($avatar, strpos($avatar, ',') + 1);
59+
}
60+
61+
$user->avatar = $avatar;
62+
}
63+
}
64+
4665
$user->save();
4766

4867
return response()->json([

app/Models/User.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@ class User extends Authenticatable
3030
'name',
3131
'email',
3232
'password',
33-
'google_id', // Google OAuthのID
33+
'google_id',
34+
'avatar',
3435
];
3536

3637
/**
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
use Illuminate\Database\Migrations\Migration;
4+
use Illuminate\Database\Schema\Blueprint;
5+
use Illuminate\Support\Facades\Schema;
6+
7+
return new class extends Migration
8+
{
9+
/**
10+
* Run the migrations.
11+
*/
12+
public function up(): void
13+
{
14+
Schema::table('users', function (Blueprint $table) {
15+
$table->longText('avatar')->nullable()->after('email');
16+
});
17+
}
18+
19+
/**
20+
* Reverse the migrations.
21+
*/
22+
public function down(): void
23+
{
24+
Schema::table('users', function (Blueprint $table) {
25+
$table->dropColumn('avatar');
26+
});
27+
}
28+
};

0 commit comments

Comments
 (0)