I want to upload a user image with Laravel - php

I want to upload a user image with Laravel. I upload the photo to the storage folder, but it doesn't appear on my visual view page.How can I change the path of a photo?
My Codes:
File Name:Controller
public function postSaveAccount(Request $request)
{
$this->validate($request, [
'first_name' => 'required| max:50'
]);
$user = Auth::user();
$user->first_name = $request['first_name'];
$user->update();
$file = $request->file('image');
$filename = $request['first_name']. '-' . $user->id . '.jpg';
if($file) {
Storage::disk('local')->put($filename, File::get($file));
}
return redirect()->route('account');
}
public function getUserImage($filename)
{
$file = Storage::disk('local')->get($filename);
return new Response($file, 200);
}
My Codes:
File Name: account.blade.php
<section class="row new-post">
<div class="col-md-6 col-md-offset-3">
<header><h3>Your Account</h3></header>
<form action="{{route('account.save')}}" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="first_name">First Name</label>
<input type="text" name="first_name" class="form-control" value="{{$user->first_name}}" id="first_name">
</div>
<div class="form-group">
<label for="image">Image (Only.jpg)</label>
<input type="file" name="image" class="form-control" id="image">
</div>
<button type="submit" class="btn btn-primary">Save Account</button>
<input type="hidden" value="{{Session::token()}}" name="_token">
</form>
</div>
</section>
#if(Storage::disk('local')->has($user->first_name. '-' . $user->id . '.jpg'))
<section class="row new-post">
<div class="col-md-6">
<img src="{{route('account.image',['filename' => $user->first_name. '-' .$user->id. '.jpg']) }}" alt="" class="img-responsive">
</div>
</section>

You can upload an image like this:
public function store(Request $request)
{
$imgLocation = Storage::disk('public')->put(time() . '.' . $request->file('image')->getClientOriginalName(), $request->gif), $request->file('image'));
// you may need this to save it in an image model / table if dont skip this creation
$image = Image::create([
'name' => $request->name,
'path' => $imgLocation
]);
if ($video) {
return response()->json("Success!");
}
return response()->json("Error!");
// You can also return redirect()->route('image.index')...
}

Related

Upload image laravel 9 stored as .tmp file in database

this is my first time using Laravel 9 and I want to ask some Question.
So I try to upload image and save it to database, then I want to show the image in my view. But the problem is in phpmyadmin it only shows the location where the uploaded file is stored as .tmp. The image that I uploaded is with the file name that matches what I want in the folder public/image, but why in database the name changes become D:\xampp\tmp\php5819.tmp, can anyone help me please?
Here's my controller:
public function create()
{
$student = Student::all();
return view('create', ['addstudent' => $student]);
}
public function save(Request $request)
{
$newName = '';
if ($request->file('image')) {
$extension = $request->file('image')->getClientOriginalExtension();
$newName = $request->name . '-' . now()->timestamp . '.' . $extension;
$request->file('image')->storeAs('image', $newName, 'public');
}
$request['image'] = $newName;
$student = Student::create($request->all());
if ($student) {
session()->flash('success', 'Data berhasil ditambahkan');
session()->flash('pesan', 'Data berhasil ditambahkan');
}
return redirect('/about');
// dd($request->all());
}
This is my View that I want to display the image:
#extends('layouts.templates')
#section('title', 'Detail')
#section('content')
<div class="container">
<div class="row">
<h1>Student Detail</h1>
<div class="my-3">
<img src="{{asset('image'.$student->image)}}" alt="{{ $student->name}}">
</div>
<h3>Nama : {{$student->name}}</h3>
<h3>Gender :
#if ($student->gender == 'P')
Perempuan
#else
Laki - laki
#endif</h3>
<h3>NIM : {{$student->NIM}}</h3>
Back
</div>
</div>
#endsection
This is my Form
#extends('layouts.templates')
#section('title', 'Add Student')
#section('content')
<div class="container">
<div class="row">
<div class="col-8 m-auto">
<h2 class="my-3">Form Add Student</h2>
<form action="save" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="name">Nama </label>
<input name="name" type="text" class="form-control" id="name" aria-describedby="emailHelp"
placeholder="Masukkan Nama" required>
</div>
<div class="form-group">
<label for="gender">Gender</label>
<select name="gender" id="gender" class="form-control" required>
<option value="">Pilih</option>
<option value="L">L</option>
<option value="P">P</option>
</select>
</div>
<div class="form-group mb-3">
<label for="NIM">NIM</label>
<input name="NIM" type="text" class="form-control" id="NIM" placeholder="Masukkan NIM">
</div>
<label for="NIM">Image</label>
<div class="input-group mb-3">
<input type="file" class="form-control" id="image" name="image"
aria-describedby="inputGroupFileAddon04" aria-label="Upload">
</div>
<div class="form-group row">
<div class="col-sm-10 mb-5">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</div>
</form>
Back
</div>
</div>
</div>
#endsection
Here's the error
In database
In laravel folder
Image name in laravel folder
Database column name
Column name
You are storing the filename from request which is temp filename instead of Laravel stored.
The method storeAs() will return the path Laravel stored, try below.
public function save(Request $request)
{
$data = $request->all();
if ($request->file('image')) {
$extension = $request->file('image')->getClientOriginalExtension();
// $newName = $request->name . '-' . now()->timestamp . '.' . $extension; No need for this.
$path = $request->file('image')->storeAs('image', $newName, 'public'); // Catch the path Laravel stored.
}
$data['image'] = basename($path); // Suggest save filename.ext only, if you need origin path just remove basename function.
$student = Student::create($data);
if ($student) {
session()->flash('success', 'Data berhasil ditambahkan');
session()->flash('pesan', 'Data berhasil ditambahkan');
}
return redirect('/about');
// dd($request->all());
}

When I'm trying to insert the image in the database, it just shows me the path only, e.g. 'http://127.0.0.1:8000/storage/images'

I'm new to Laravel 8 and I'm trying to insert the data with an image, so when I try to insert the data it just shows me the inserted data and image path only. How can I solve this?
File RestaurantController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Restaurant;
class RestaurantController extends Controller
{
function add(Request $request)
{
$resto = new Restaurant;
$resto->name = $request->input('name');
$resto->email = $request->input('email');
$resto->address = $request->input('address');
$resto->create_at = $request->input('create_at');
$resto->uploaded_at = $request->input('uploaded_at');
$resto->image = $request->input('image');
// $resto->image = $request->file('image')->store('images');
if($request->hasFile('image'))
{
$image = $request->file('image');
$image_name = $image->getClientOriginalName();
$image->move(public_path('/images'), $image_name);
$image_path = "/images/" . $image_name;
}
$resto->save();
$request->session()->flash('status', 'Client entered successfully');
return redirect('list');
}
}
File add.blade.php
#extends('layout')
#section('content')
<div class="col-sm-6">
<form method="POST" action="" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" id="name" placeholder="Enter Your Name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" class="form-control" id="email"
placeholder="name#example.com">
</div>
<div class="form-group">
<label for="address">Address</label>
<textarea class="form-control" name="address" id="address" rows="3"></textarea>
</div>
<div class="form-group">
<label for="create_at">Create At Date</label>
<input type="date" name="create_at" class="form-control" id="create_at">
</div>
<div class="form-group">
<label for="uploaded_at">Uploaded At Date</label>
<input type="date" name="uploaded_at" class="form-control" id="uploaded_at">
</div>
<div class="form-group">
<label for="image">Image</label>
<input type="file" name="image" class="form-control" id="image">
</div>
<button type="Submit" clas="btn btn-primary">Submit</button>
</form>
</div>
#stop
File web.php
Route::get('/', [RestaurantController::class, 'index']);
Route::view('/add', 'add');
Route::post('/add', [RestaurantController::class, 'add'])->name('add');
I got <img src=http://127.0.0.1:8000/storage/images alt="image" height="50" width="50" > and what I want is http://127.0.0.1:8000/storage/images/`my_image_name`
When I perform return $request->all();, it shows me
{"_token":"ExiC1hv4sX3qrz6ZcQJJNfIL6bjblw938hfRkG8J","name":"test","email":"test#gmail.com","address":"testing address","create_at":"2022-05-30","uploaded_at":"2022-06-01","image":{}}
as a output.
You can use this code:
if($file = $request->hasFile('image')) {
$file = $request->file('image');
$fileName = $file->getClientOriginalName();
$destinationPath = public_path() . '/images';
$file->move($destinationPath, $fileName);
}
You can simply use the store() method.
...
if ($request->hasFile('image')) {
$image = $request->image->store('image'); // See store()
}
$restro->image = $image;
$restro->save();
Inside the blade template, you can retrieve the stored file like this:
<img src="{{ asset('storage/' . $restro->image) }}" />
Make sure you have created the symbolic link of your storage folder in your public folder. If you haven't, you can create it by this artisan command:
php artisan storage:link

Image is not storing in the database Laravel 5.8?

The image is not storing in the database
I already tried looking at other possible solutions but nothing work I also tried with using guessextension
public function store(Request $request)
{
$student = new student();
$this->validateRequest();
$student->name = $request->name;
$student->address = $request->address;
if ($request->hasFile('image')) {
$image = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename=time() .'.'. $extension;
$file->move('uploads/student/',$filename);
$student->image = $filename;
}
else {
return $request;
$student->image ='';
}
$student->save();
return redirect()->route('show')->with('response', 'Registered Successfully');
}
Here is the form
#extends('layouts.app')
#section('content')
<div class="container">
<form method="get" action="/student" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" name="name" id="email">
</div>
<div class="form-group">
<label for="pwd">Address:</label>
<input type="text" class="form-control" name="address" id="email">
</div>
<div class="custom-file">
<input type="file" name="image" class="custom-file-input" >
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
#stop
What I need is the image to be stored in the database.
actually, when you upload an image to the server you save only the path of the image into your database
so firstly you need to Create a symbolic link from "public/storage" to
"storage/app/public"
by artisan command: php artisan storage:link
after that, you can optimize this part of your code from this
if ($request->hasFile('image')) {
$image = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename=time() .'.'. $extension;
$file->move('uploads/student/',$filename);
$student->image = $filename;
}
to this simple one
if ($request->hasFile('image')) {
$image = $request->image->store('uploads');
}

Why did not update category name and image in Laravel?

working with Laravel 5.6 and MySQL. I am going to update categoryname and image in my categories table using the following controller function?
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('categories.form', ['image' => Category::find($id)]);
else {
$rules = [
'categoryname' => 'required',
];
$this->validate($request, $rules);
$image = Category::find($id);
if ($request->hasFile('image')) {
$dir = 'images/';
if ($image->image != '' && File::exists($dir . $image->image))
File::delete($dir . $image->image);
$extension = strtolower($request->file('image')->getClientOriginalExtension());
$fileName = str_random() . '.' . $extension;
$request->file('image')->move($dir, $fileName);
$image->categoryimage = $fileName;
} elseif ($request->remove == 1 && File::exists('images/' . $image->image)) {
File::delete('images/' . $image->post_image);
$image->categoryimage = null;
}
}
$image->categoryname = $request->description;
$image->save();
return redirect()->route('categories.index');
}
and route
Route::match(['get', 'put'], 'category/update/{id}', 'CategoryController#update');
and edit form
#if(isset($image))
<form method="PUT" action="http://localhost:8000/category/update/{{$image->id}}" enctype="multipart/form-data">
<input type="hidden" name="_method" value="put">
<label for="description" class="col-form-label col-md-3 col-lg-2">Description</label>
<div class="col-md-8">
<input class="form-control" autofocus placeholder="Description" name="description" type="text" id="description" value="{{ isset($image) ? $image->categoryname : '' }}">
<label for="image" class="col-form-label col-md-3">Image</label>
<div class="col-md-5">
<img id="preview"
src="{{asset((isset($image) && $image->categoryimage!='')?'images/'.$image->categoryimage:'images/noimage.png')}}"
height="200px" width="200px"/>
<input class="form-control" style="display:none" name="image" type="file" id="image" name="_token" value="{{ csrf_token() }}">
<br/>
Add Image |
<a style="color: red" href="javascript:removeImage()">Remove</a>
<input type="hidden" style="display: none" value="0" name="remove" id="remove">
but when I try to update data it is not updating. only refresh to the same page. no, any error. how can I fix this problem?

Upload image fail when using mobile

I am trying to upload an image through the use of mobile and it is not working for some reason. I tried to upload from my laptop and it worked, and I have no idea what is happening here
Here is what is happening:
When I try to upload with my mobile device, it just redirect me back to the upload page and the image was not uploaded but if I were to use my laptop to do it, it worked and redirect me to /home page, can anyone help me out here, thanks a lot
Here is the controller I used to upload photo:
public function store1(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id;
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$userImage = new UserImage;
$PersonalInfo = new PersonalInfo;
$userImage->name = $name;
$userImage->size = $size;
$user= PersonalInfo::find($id);
$user->UserImages()->save($userImage);
}
return redirect('/home');
}
uploadImg.blade.php
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2" style="padding-left: 30px">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>

Categories