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());
}
Related
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
im trying to edit an image on laravel 6, but but it does not advance to next view, stays on the form view.
I have seen many tutorials of laravel 5.8 and 6. I can't make it work in any way
This is de controller:
public function update(Request $request, $id)
{
$validator = $request->validate([
'titulo' => 'required | max:50', //campo obligatorio y máximo 50 caracteres
'contenido' => 'required | max:150',
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$image_name = time().'.'.$request->imagen->getClientOriginalExtension();
$request->image->move(public_path('images'), $image_name);
$datos = array(
'titulo' => $request->titulo,
'contenido' => $request->contenido,
'imagen' => $image_name,
);
Noticia::whereId($id)->update($datos);
return redirect('/mostrar');
}
THis is Web.php file:
Route::get('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
Route::get('/editar/{id}', 'crearNoticiaController#edit')->name('editar');
this is form file:
<div class="subir-imagen">
<form method="get" action="{{ route('actualizar', $noticia->id) }}" enctype="multipart/form-data">
#csrf
<div class="crear-titulo">
<input class="titulo" type="text" name="titulo" placeholder="Escriba el titulo" value="{{$noticia->titulo}}">
</div>
<div class="crear-contenido">
<textarea class="ckeditor" name="contenido" placeholder="Escriba el contenido" >
{{$noticia->contenido}}
</textarea>
</div>
<table border="2">
<tr>
<td><img src="{{URL::to('/')}}/images/{{$noticia->imagen}}" alt="imagen" width="250" align="left"/></td>
</tr>
</table>
<div class="form-group">
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" />
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<input type="submit" class="btn btn-primary" value="Enviar" id="btn-enviar" />
</div>
</div>
</form>
</div>
Thnaks for help
I faced same issue, but luckily i solved this problem.I added my solution below, i think this will help you to solve this problem
public function updatePost(Request $request, $id)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:25|min:4',
'image' => 'mimes:jpeg,jpg,png,JPEG,JPG,PNG | max:100000',
]);
$data = array();
$data['category_id'] = $request->category_id;
$data['title'] = $request->title;
$data['details'] = $request->details;
$image = $request->file('image');
if($image)
{
$image_name = hexdec(uniqid());
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/assets/img/';
$image_url = $upload_path.$image_full_name;
$success = $image->move($upload_path,$image_full_name);
$data['image'] = $image_url;
unlink($request->old_photo);
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
else
{
$data['image'] = $request->old_photo;
$posts = DB::table('posts')->where('posts.id', $id)->update($data);
if($posts)
{
return Redirect()->route('all.posts')->with('success','Posts are inserted successfully');
}
else
{
return back()->with('error', 'Posts are not inserted successfully');
}
}
}
edit_post.blade.php
#extends('welcome')
#section('content')
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<p>
List Posts
</p>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ url('posts.update_posts/'.$posts->id) }}" method="post" enctype="multipart/form-data">
#csrf
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<div>Category Name</div>
<label>Category ID</label>
<select class="form-control" name="category_id">
#foreach($category as $categories)
<option value="{{ $categories->id }}" <?php if ($categories->id == $posts->category_id)
echo "selected"; ?> > {{ $categories->name }} </option>
#endforeach
</select>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Title</label>
<input type="text" name="title" class="form-control" value="{{ $posts->title }}" id="title" required data-validation-required-message="Please product name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Details</label>
<textarea name="details" rows="5" class="form-control" value="{{ $posts->details }}" id="details"></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls">
<label>Product Image</label>
<input type="file" name="image" class="form-control" id="image"><br/>
Old Image : <img src="{{ URL::to($posts->image) }}" style="hight: 40px; width: 100px">
<input type="hidden" name="old_photo" value="{{ $posts->image }}">
</div>
</div>
<br>
<div id="success"></div>
<div class="form-group">
<button type="submit" class="btn btn-success" id="sendMessageButton">Update</button>
</div>
</form>
</div>
</div>
</div>
#endsection
First run on your project console command:
php artisan storage:link
Then try this code and if return any error message tell me khow:
$imagen = $request->file("imagen");
$extension = $imagen->extension();
$filename = time().".".$extension;
$request->file('imagen')->storeAs("public/images", $filename);
Finally check your public/images folder for image file exists.
Also you can read about storing uploaded files in laravel 6.x official documentation
I've solved with this way:
In web.php I put patch instead get
Route::patch('/actualizar/{id}', 'crearNoticiaController#update')->name('actualizar');
In the edit blade I put: #method('PATCH')
And this is the update in the controller:
public function update(Request $request, $id)
{
$noticia = Noticia::findOrFail($id);
$noticia->titulo = $request->get('titulo');
$noticia->contenido = $request->get('contenido');
$noticia->imagen = $request->file('imagen');
$validator = $request->validate([
'imagen' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
$imageName = time().'.'.request()->imagen->getClientOriginalExtension();
request()->imagen->move(public_path('images'), $imageName);
$noticia->imagen = $imageName;
$noticia->update();
return redirect('/mostrar'); //Redirigimos a la la vista para mostrar las noticias
}
I am trying to make todo list wherein updating form other field value is shown but for image the value is read from the folder but not display in the input field.
everything works fine else this problem.
This display the image name<?php echo $task->img; ?>
I use dd("$task->img"); to check the values.
edit.blade.php
<label for="title">Task Title</label>
<input type="text" value="{{$task->title}}" class="form-control" id="taskTitle" name="title" >
</div>
<div class="form-group col-6">
<label for="description">Task Description</label>
<input type="text" value="{{$task->description}}" class="form-control" id="taskDescription" name="description" >
</div>
<div class="form-group col-6">
<label for="img">Task Image</label>
<input type="file" value="{!! $task->img !!}" class="form-control" id="taskImg" name="img" >
</div>
taskcontroller.php
public function update(Request $request, Task $task)
{
// dd("$task");
//Validate
$request->validate([
'title' => 'required|min:3',
'description' => 'required',
'img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$task->title = $request->title;
$task->description = $request->description;
if($request->hasFile('img')) {
$file = $request->file('img');
$newVar = strtotime(date('d-m-Y h:i:s'));
$extension = $file->getClientOriginalExtension(); // getting image extension
$filename = $newVar.'.'.$extension;
$file->move('task',$filename);
$task->img = $filename;
}
$task->update();
$request->session()->flash('message', 'Successfully modified the task!');
return redirect()->route('tasks.index');
}```
Adding a file as a default value is not gonna work for an input field.
You probably want to add an extra div above the input field like:
<div>
<p>Current image</p>
<img src="{!! asset($task->img) !!}">
<p>Upload new image:</p>
<div class="form-group col-6">
<label for="img">Task Image</label>
<input type="file" class="form-control" id="taskImg" name="img" >
</div>
</div>
In your controller, you should then delete the old image if a new has been uploaded. I also added the asset(), helper. But you should use the location of your file because in your controller you don't seem to store it on a filesystem-disk.
PS: You should also read this to simplify the upload code:
https://laravel.com/docs/5.8/filesystem#storing-files
For example, this replaces all those lines between the if statement
$path = $request->file('img')->store('images');
$task->img = $path;
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')...
}
I am trying to take a file that is uploaded by the user and move it to a folder named "Images" inside of my Laravel Public file, I have managed to get it to execute successfully with no errors, my only issue is that the uploaded file wont show inside of the /Images folder.
My function is as follows:
public function contactPost(Request $request)
{
if($request->hasFile('attachment'))
{
$file = $request->file('attachment');
$file->move('Users/jvb/laravel/public/Images', $file->getClientOriginalName());
echo 'File name '.$file->getClientOriginalName();
echo "<br>";
} else {
return "No";
}
}
The blade.php file is as follows:
#extends('layouts.master')
#section('content')
<form method="POST" enctype="multipart/form-data" action="{{ route('contactPost') }}">
#csrf
<div class="form-group">
<input class="form-control" name='name' type="text" placeholder="Name">
</div>
<div class="form-group">
<input class="form-control" name='email' type="email" placeholder="Email">
</div>
<div class="form-group">
<textarea class="form-control" name="message" id="" cols="30" rows="10" placeholder="Message"></textarea>
</div>
<div class="form-group">
<input class="form-control" name="attachment" type="file">
</div>
<div class="form-group">
<button type="submit" class="form-control">Send Message</button>
</div>
</form>
#endsection
Location of image folder within my laravel project is:
What am I doing wrong and how fix this?
Use public_path() instead of absolute path
$file->move(public_path()."/Images/", $file->getClientOriginalName());
UPDATE
In order to store the image into your database
$user = new User; //model
$filename = $file->getClientOriginalName();
$file->move(public_path("Images"), $filename);
$path = '/Images/' . $filename;
$user->avatar = $path;
$user->save();