Reputation: 431
I am creating commenting system, now, I want to show user profile images in comment area.
I want to catch and show multiple images from laravel 5.8 public folder. Here is what I tried.
If user has a profile image, I want to show it. If not, I want to show an avatar using vue avatar component. My images are stored in public/uploads/profile.
Now I don't have any errors in my console. Also I can show user name and user comments.
Image name is stored in mysql.
comment.vue(first comment)
<div class="user" v-if="comment.user.image && comment.user.image.length > 0">
<span :v-for="(item, index) in comment.user.image">
<img :src="'uploads/' + 'profile' + '/' + item.image">
</span>
</div>
<div else class="user" >
<avatar :username="comment.user.name" :size="45"></avatar>
</div>
commentController.php
public function index(Post $post)
{
return $post->comments()->paginate(10);
}
public function show(Comment $comment)
{
return $comment->replies()->paginate(10);
}
public function store(Request $request, Post $post)
{
return auth()->user()->comments()->create([
'body' => $request->body,
'post_id' => $post->id,
'comment_id' => $request->comment_id
])->fresh();
}
profiles table
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('user_id');
$table->string('image');
$table->string('gender');
$table->string('country');
$table->string('bod');
$table->string('instagram');
$table->string('description');
$table->timestamps();
});
In my VS code, uploads folder started turning red.
Upvotes: 0
Views: 2257
Reputation: 2806
My solution is create a api route to show image. For example.
api.php
Route::get('profile/{fileName}', 'ProfileController@showImage');
ProfileController.php
class ProfileController {
...
public function showImage($fileName)
{
$path = public_path("/images/{$fileName}");
if (!\File::exists($path)) {
return response()->json(['message' => 'Image not found.'], 404);
}
$file = \File::get($path);
$type = \File::mimeType($path);
$response = \Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
}
}
And you image src will be /api/profile/{imageName}
. This is my solution.
Upvotes: 1