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();
Related
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());
}
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
I am learning Laravel and attempting to create a webpage to upload Picture albums. I have read up on the laravel documentation on verification and each field is being verified. However, upon clicking submit, the image does not post to the store method.
The route is set in web.php
Route::get('/albums/create', 'AlbumsController#create')->name("album-create");
Route::post('/albums/store', 'AlbumsController#store')->name("album-store");
The form code is shown below:
<div class="container">
<h2> Create New Album </h2>
<form method="post" action="{{ route('album-store') }}" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token(#csrf) }}">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter Name: ">
</div>
<div class="form-group">
<label for="name">Description</label>
<input type="text" class="form-control" name="description" id="description" placeholder="Enter description">
</div>
<div class="form-group">
<label for="name">Cover Image</label>
<input type="file" class="form-control" name="cover_image" id="cover-image" placeholder="cover-image">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
and finally we have the controller function below:
public function store(Request $request) {
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'cover-image' => 'required'
]);
$filenameWithExtension = $request->file('cover-image')->getClientOriginalName();
$filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);
$extension = $request->file('cover-image')->getClientOriginalExtension();
// time stamping the images uplaoded
$filenameToStore = $filename . '_' . time() . '.' . $extension;
// saving the file to the disk (can be found in 'storage/app/public/album_covers..')
$request->file('cover-image')->storeAs('public/album_covers', $filenameToStore);
$album = new Album();
$album->name = $request->input('name');
$album->description = $request->input('description');
$album->cover_image = $filenameToStore;
$album->save();
When I click submit on the form after filling the fields, I still receive the error "Cover-image" is required. enter image description here
the field in html is cover_image
while the validation is cover-image
<div class="form-group">
<label for="cover-image">Cover Image</label>
<input type="file" class="form-control" name="cover-image" id="cover-image" placeholder="cover-image">
</div>
The labels for attribute is set to target the field with id="name", not related to the issue but i thought you need to look in the html file it needs some attention.
your cover image input field name is cover_image and you take the value and validate it as cover-image write form group input filed like bellow
<div class="form-group">
<label for="name">Cover Image</label>
<input type="file" class="form-control" name="cover-image" id="cover-image" placeholder="cover-image">
</div
I tried to edit and updated the employee info, unfortunately, it doesn't work
I fetch the employee id but when I sent the updated data it's not working.
it shows Requested URL not found on the server
this is my controller
public function edit_function($id){
$user = User::find($id);
return view('employee.empedit')->with('user',$user);
}
public function update(Request $request,$id){
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phonenumber = $request->input('phonenumber');
$user->profession = $request->input('profession');
if($request->hasfile('images')){
$file= $request->file('images');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('uploads/user/', $filename);
$user->images= $filename;
}
$user->save();
return redirect('empprofile')->with('success', 'Data Updated.');
}
this is my view
<form method="post" action="/updateimages/{{ $user->id }}" enctype="multipart/form-data">
<div class="container">
<div class="jumbotron">
<h2>Update The Information Of Employee</h2>
{{ csrf_field() }}
{{ method_field('PUT') }}
<div class="form-group">
<label >Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name" value="{{ $user->name }} ">
</div>
<div class="form-group">
<label >Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email" value="{{ $user->email }} ">
</div>
<div class="form-group">
<label >Phone Number:</label>
<input type="text" class="form-control" id="phonenumber" placeholder="Enter Phone Number" name="phonenumber" value="{{ $user->phonenumber }} ">
</div>
<div class="form-group">
<label >Profession :</label>
<input type="text" class="form-control" id="profession" placeholder="Enter Profession" name="profession" value="{{ $user->profession }} ">
</div>
<div class="form-group">
<label >Image :</label>
<input type="file" class="form-control" id="images" placeholder="" name="images" value="{{ $user->images }}">
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit" name="submit" style="width:50%;">Update Data</button>
</div>
</div>
</div>
</form>
this is my route
Route::get('edit_profile/{id}' , "empController#edit_function");
Route::put('/updateimages/{id}', "empController#update");
it shows Requested URL not found on the server
Since I am not a Big fan of Url and id So i will go with
name based routing and Route Model Binding
Step 1: Refactor Routes
Route::get('edit_profile/{user}' , "empController#edit_function")
->name('user.editProfile');
Route::put('/updateimages/{user}', "empController#update")
->name('user.updateProfile');
Step 2: Refactor Controller Method
public function edit_function(User $user)
{
$user = $user;
return view('employee.empedit')->with('user',$user);
}
public function update(Request $request,User $user)
{
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phonenumber = $request->input('phonenumber');
$user->profession = $request->input('profession');
if($request->hasfile('images')){
$file= $request->file('images');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('uploads/user/', $filename);
$user->images= $filename;
}
$user->save();
return redirect('empprofile')->with('success', 'Data Updated.');
}
Step 3: Edit Html and Switch to route helper
<form method="POST" action="{{route('user.updateProfile',['user' => $user])}}" enctype="multipart/form-data">
Kindly Comment Below if you are facing any issues
Its because some other route replce your existing route. You can solve it by debugging. it will cost your time. I had a better solution,
You name your route. and call the route by route() function.
From your above information,
It may be,
in route ->
Route::put('/updateimages/{id}', "empController#update")->name('updateImage');
in view (form action) ->
<form method="post" action="{{ route('updateImage', $user->id ) }}" enctype="multipart/form-data">
So far I have been able to make a custom form which upon successful entry save the value to a MySql table called "form_entry"
Below is the code for a form:
<form method="post" class="container">
<div class="row">
<div class="col-md-6 mb-3">
<label>Name</label>
<input type="text" name="myname" class="form-control" placeholder="Name" value="John Doe" required>
</div>
<div class="col-md-3 mb-3">
<label>State</label>
<input type="text" name="statename" class="form-control" placeholder="State" required>
</div>
</div>
<button class="btn btn-primary" type="submit" name="BtnSubmit" value="submit">Submit form</button>
</form>
And I insert a few codes in the functions.php under my template folder like this :
if(isset($_POST['BtnSubmit'])) {
global $wpdb;
$data_array = array(
'myname' => $_POST['myname'],
'statename' => $_POST['statename'],
);
$table_name = 'form_entry';
$rowResult = $wpdb ->insert($table_name, $data_array, $format=NULL);
if($rowResult == 1) {
echo 'Success';
}
else {
echo ' Error in my pant';
}
die;
}
This is working fine. But I want to add a file upload option in the form and save the uploaded file location to MySql. Please help.
You have to add one field into your html form. and add parameter for into form.
<form method="post" class="container" enctype="multipart/form-data">
<div class="row">
<div class="col-md-6 mb-3">
<label>File</label>
<input type="file" name="myfile" class="form-control" required/>
</div>
</div>
then after submit you have to save uploaded file at particular location and save that file into your db.
if (isset($_POST['BtnSubmit'])) {
$target = 'uploads/' . basename($_FILES['myfile']['name']);
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target)) {
$fp = fopen($target, "r");
}
global $wpdb;
$data_array = array(
'myname' => $_POST['myname'],
'statename' => $_POST['statename'],
'filename' => $target
);
}
I think it will work for you !! feel free to ask me.