Unable to store uploaded image using PHP and Laravel - php

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

Related

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

Existing image is not displaying in edit form to update in larvel(5.8)

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;

Can't update user in laravel

I want some help with my code.
I try to update user data but it's not update anything.
User Name, Email, Posisson, Image.
Any help please.
My Route :
I used URL because route didn't work.
Route::get('editusers/{id}','UsersController#update');
My Controller:
public function edit($id)
{
$editusers=User::findOrFail($id);
return view('admin.users.EditUser', compact('editusers'));
}
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'posission' => 'required',
]);
$useredit = User::find($id);
$useredit->name = $request->input('name');
$useredit->email = $request->input('email');
$useredit->posission = $request->input('posission');
if($request->hasFile('file'))
{
$file = $request->file('file');
$filename = time().'.'.$file->getClientOriginalExtension();
Image::make($file)->resize(150, 150)->save(public_path('/admin/images/'.$filename));
$useredit->UserImg = $filename;
}
$useredit->save();
return redirect()->back();
}
HTML :
<form class="" action="{{url('editusers',Auth::user()->id)}}" role="form" enctype="multipart/form-data">
{!! csrf_field() !!}
<input type="hidden" name="_method" value="PUT">
<label>Edit Your Profile :</label>
<div class="form-group">
<label>Name :</label>
<input class="form-control" value="{{$editusers->name}}" name="Name">
</div>
<div class="form-group">
<label>Email :</label>
<input class="form-control" value="{{$editusers->email}}" name="email">
</div>
<div class="form-group">
<label>Posisson :</label>
<input class="form-control" value="{{$editusers->posission}}" name="posission">
</div>
<div class="form-group">
<label>Image :</label>
<img src="{{ asset('admin') }}/images/{{$editusers->UserImg}}" alt="avatar" class="img-circle" style="max-height: 100px;">
<input type="file" id="file" name="file"/>
</div>
<input class="btn btn-success btn-mini deleteRecord" type="submit" name="submit" value="Update">
What I expect is that it updates my database.
As your form has
<form class="" action="{{url('editusers',Auth::user()->id)}}" role="form" enctype="multipart/form-data" method="POST">
{!! csrf_field() !!}
<input type="hidden" name="_method" value="PUT">
so your route must have put(),
so it should be Route::put('editusers/{id}','UsersController#update');
also you can use #method('PUT') instead of <input type="hidden" name="_method" value="PUT"> and #csrf instead of {!! csrf_field() !!}
either change $useredit->name = $request->input('name'); to $useredit->name = $request->input('Name'); or in form
<input class="form-control" value="{{$editusers->name}}" name="Name"> to
<input class="form-control" value="{{$editusers->name}}" name="name">
Your route is wrong
Route::get('editusers/{id}','UsersController#update');
it supposed to be PUT
Route::put('editusers/{id}','UsersController#update');
The problem because you put wrong method at your route. Change it
// From
Route::get('editusers/{id}', 'UsersController#update')
// To
Route::put('editusers/{id}', 'UsersController#update')
Anyways, you should change your route to be standard. It should be:
//To show data you should use:
Route::get('users/edit/{id}', 'UsersController#show');
//To update user data.
Route::put('users/edit', 'UsersController#update');
i think you should use resources route to solve this:
Route::resource('editusers','UserController');
but first you need to run this command
php artisan make:controller UserController --resource

How to fix edit interface getting only first word of a column in table in Laravel 5.7?

My edit interface edit.blade.php only gets the first word of the name from my database, this is what the index.blade.php looks like
and when i click on the edit icon of the 3rd line it leads me to edit.blade.php which gives me this
"Nom d'établissement" textfield only gets the first word from the database
Everything looks fine in the database:
this is my edit.blade.php form:
<form method="post" action="{{ route('etablissements.update', $etablissement->id) }}">
#method('PATCH')
#csrf
<div class="col-5">
<div class="form-group">
<label for="nom">Nom Etablissement :</label>
<input type="text" class="form-control" name="nom" value={{ $etablissement->nom }} />
</div>
<div class="form-group">
<label for="price">E-Mail :</label>
<input type="text" class="form-control" name="email" value={{ $etablissement->email }} />
</div>
<div class="form-group">
<label for="quantity">Telephone:</label>
<input type="text" class="form-control" name="telephone" value={{ $etablissement->telephone }} />
</div>
</div>
<button type="submit" class="btn btn-primary">Confirmer</button>
</form>
this is edit function in the controller:
public function edit($id)
{
$etablissement = Etablissement::find($id);
return view('etablissements.edit', compact('etablissement'));
}
and this is update function in the controller:
public function update(Request $request, $id)
{
$request->validate([
'nom'=>'required',
'email'=> 'required',
'telephone' => 'required|numeric'
]);
$etablissement = Etablissement::find($id);
$etablissement->nom = $request->get('nom');
$etablissement->email = $request->get('email');
$etablissement->telephone = $request->get('telephone');
$etablissement->save();
return redirect('/etablissements')->with('success', 'Utilisateur édité');
}
Quote the value attribute.
<input type="text" class="form-control" name="nom" value="{{ $etablissement->nom }}" />
Without quotes, the second word in$etablissement->nom is interpreted as another attribute rather than part of the value of the value attribute.
The email and telephone values are showing up correctly because there are no spaces, but you should quote those as well just in case.

$file->move() function not showing moved file in the new folder?

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();

Categories