I've looked at code from other people and try to implement the same thing, but the application could not store the image to the desire folder, would you please have a look at what the reason is? Thank you!
Here is my code for route:
Route::post('upload_pic', 'UploadController#storePhoto');
Here is my code for the php laravel template:
<div class="panel-body">
<form action="{{url('/upload_pic')}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="upload-user-photo">Upload Photos</label>
<input type="file" name="image" class="form-control" placeholder="Upload Student Image, Size:207(W)x408(H)">
</div>
<div class="row">
<div class="col-sm-4">
<input class="btn btn-success" type="submit" value="Upload Student Photo" name="submit">
</div>
</div>
</form>
</div>
Here is my code in the controller:
public function storePhoto(Request $request){
$valid = $request->validate([
'image' => 'required|image|mimes:jpg,png,jpeg,|dimensions:max_width=272,max_height=408,min_width=271,min_height=407'
]);
$data = new Postimage();
$file = $request->file('image');
$filename = $file->getClientOriginalName();
// dd($filename);
$file -> move(public_path('./public/img/student_photos'),$filename);
$data['image'] = $filename;
$data->save();
return redirect('/upload')->with('success', 'Photo Uploaded');
}
Your problem is somewhere here
$filename = $file->getClientOriginalName();
$file -> move(public_path('./public/img/student_photos'),$filename);
First, the file comprises only the file extension. Instead, you should have something like this $filename = 'name.' . $file->getClientOriginalName(); Notice the dot in 'name.'
Secondly, no need to add public to the file path string. So it should be $file->move(public_path('img/student_photos'),$filename);
Finally, make sure the upload folder exists and is writeable
i am new using codigniter. i am trying to display images from the mysql database by sending them to the database using a create page where you can type in a title, some info and select an image, everything displays after creating a project except for the image. once i open phpmyadmin it shows that there is data for the image but it looks like it's only MetaData and not the actual image itself. i have been stuck on this for a couple of days now so i hope you guys could help me out!
create function in The Controller (edited):
public function create(){
$model = new ProjectModel();
$file = $this->request->getFile('image');
if ($this->request->getMethod() === 'post' && $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'info' => 'required',
'image' => 'uploaded[image]',
]))
{
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'info' => $this->request->getPost('info'),
$tempfile = $file->getTempName(),
$imgdata = file_get_contents($tempfile),
]);
var_dump($imgdata);
#echo view('project/success');
}
else
{
echo view('site/create');
}
}
My Model
namespace App\Models;
use CodeIgniter\Model;
class ProjectModel extends Model
{
protected $table = 'projects';
protected $allowedFields = ['title', 'slug', 'info', 'image'];
public function getProjects($slug = false)
{
if ($slug === false)
{
return $this->findAll();
}
return $this->asArray()
->where(['slug' => $slug])
->first();
}
}
this is the file that creates a div element once you press the create button
<?php if (! empty($projects) && is_array($projects)) : ?>
<?php foreach ($projects as $project_item): ?>
<div class="project-box" href="/projects/<?= esc($project_item['slug'], 'url') ?>">
<?php echo '<img class="project-image" src="data:image/jpeg;base64,'.base64_encode($project_item['image']).'" alt="image" ">'?>
<p class="project-name"><?=esc($project_item['title'])?></p>
<div class="bottom-border">
<p class="project-creator"><i class="far fa-user-circle"></i> <?=esc($project_item['creator'])?></p>
<div class="statistics">
<p class="project-likes"><i class="fas fa-heart"></i> <?=esc($project_item['likes'])?></p>
<p class="project-views"><i class="far fa-eye"></i> <?=esc($project_item['views'])?></p>
</div>
</div>
</div>
<?php endforeach; ?>
<?php else : ?>
<h3>No Projects</h3>
<?php endif ?>
this is the create file in which you can create a project
<div class="parent">
<?= \Config\Services::validation()->listErrors() ?>
<form action="/site/create" method="post">
<h1>Create Project</h1>
<?= csrf_field() ?>
<div class="form-group">
<input class="ph-title" type="input" name="title" placeholder="Title" /><br/>
</div>
<div class="grow-wrap">
<textarea class="ph-info" name="info" placeholder="Type in project info"></textarea>
</div>
<!-- <div class="file-input">
<label for="file">
Select file
<p class="file-name"></p>
</label>
</div> -->
<input class="file-btn" type="file" name="image" value=""/><br/>
<input class="create-btn" type="submit" name="submit" value="Create Project"/>
</form>
</div>
What am i doing wrong?
There are a few things wrong here. First off, your form is set for image uploading, but needs the enctype added to the form tag so that your backend PHP can recieve the $_FILES object
<form action="/site/create" method="post" enctype="multipart/form-data">
Remove the value="" from the input...
<input class="file-btn" type="file" name="image" />
Now you're ready to receive a file - see https://codeigniter4.github.io/userguide/libraries/uploaded_files.html
Your validation should be altered
$this->validate([
//... your other validations...
'image' => 'uploaded[image]' // instead of required
]);
If you want to store the image on your server and then record the name of the image in the database to retrieve later:
$imageDirectory="/path/to/where/you/store/images";
$imageName = $file->getRandomName();
$path = $this->request->getFile('image')->store($imageDirectory, $imageName);
// path is now the full path to the image on your server.
if you want to store the image BLOB data instead (like your example):
$tempfile = $file->getTempName();
$imgdata = file_get_contents($tempfile);
Then your insert would look like this...
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'info' => $this->request->getPost('info'),
'image' => $imgdata,
]);
I want to upload more than one image at a time through an in Laravel 8 to my SQL database, and I am not able to do it. I have managed to upload only one, but when I try with more I get failure.
My Database
Imagenes
id
nombre
id_coche
01
name.jpg
0004
...
...
...
My Code
Blade with the Form
#foreach ($Vehiculo as $obj) /*this is to take the Car ID*/
<form method="POST" action="{{ route('añadirImagen')}}" enctype="multipart/form-data" >
#csrf
<div class="form-row">
<div class="form-group col-md-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">ID</span>
</div>
<input type="text" class="form-control" name="id_coche" value="{{$obj->id}}" style="background: white" required readonly>
</div>
</div>
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" required multiple/>
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-success">AÑADIR IMAGENES</button>
</div>
</div>
</form>
#endforeach
Controller
"To upload only one image"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'nombre.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->file("imagen")!=null){
$nombre = $request->file('imagen');
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
$Imagenes->save();
return redirect()->back()->with('error','Se han añadido las imagenes correctamente.');
}
}
"My attempt to upload more than one"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'imagen.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->hasfile("imagen")){
$nombre_img = $request->file('imagen');
foreach($nombre_img as $nombre) {
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
}
$Imagenes->save();
When doing this, it adds in the database a single row, with the correct id_coche, the Auto_Increment does well the ID, but the name remains NULL.
Thank You.
You currently have:
<input type="file" class="form-control" name="imagen" required multiple/>
and it needs to be:
<input type="file" class="form-control" name="imagen[]" required/>
multiple attribute is not required.
Then you can do in your controller:
if($request->hasfile('imagen')) {
foreach($request->file('imagen') as $file)
{
...
}
}
I keep getting this error, when I try to create a skill on my project
Method App\Http\Controllers\SkillController::show does not exist.
I don't need a show() method because I don't need a show view of my skill object.
This is my route block look like
//Skill
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/store','SkillController#store');
Route::get('skill/{id}/edit', 'SkillController#edit');
Route::post('skill/{id}/update','SkillController#update');
Route::delete('skill/{id}/destroy','SkillController#destroy');
This is my entire SkillController
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Skill;
use Input, View, File, Image, SSH, Redirect,Response;
class SkillController extends Controller {
public function index(){
$skills = Skill::orderBy('updated_at', 'desc')->orderBy('created_at', 'asc')->where('img_path','==',NULL)->get();
$first_color = $skills[0]->color_code;
$second_color = $skills[1]->color_code;
$third_color = $skills[2]->color_code;
$fourth_color = $skills[3]->color_code;
$fift_color = $skills[4]->color_code;
return View::make('layouts.be.skills.index', get_defined_vars());
}
public function all(){
return Skill::all()->pluck('name');
}
public function create(){
$skillTypes = ['Build System','Development Environment','Server Management','Operating System','IDE','Creative Suite','Video Editing','Package Management','Git Repository','Web Scaffolding','CSS Precompiler','Scripting','Framework','DBMS','Unit Test','Automation Testing','Cloud Platform','Hosting Provider','Content Management', 'API', 'Authentication' , 'Integration','Language','Web Server','Project Managment','Documentation','Utility','Network Analyzer' ];
sort($skillTypes);
return View::make('layouts.be.skills.create', get_defined_vars());
}
public function edit($id){
$skillTypes = ['Build System','Development Environment','Server Management','Operating System','IDE','Creative Suite','Video Editing','Package Management','Git Repository','Web Scaffolding','CSS Precompiler','Scripting','Framework','DBMS','Unit Test','Automation Testing','Cloud Platform','Hosting Provider','Content Management', 'API', 'Authentication' , 'Integration','Language','Web Server','Project Managment','Documentation','Utility','Network Analyzer' ];
sort($skillTypes);
$skill = Skill::findOrFail($id);
return View::make('layouts.be.skills.edit', get_defined_vars());
}
public function store(){
$skill = new Skill;
$skill->type = Input::get('type');
$skill->name = Input::get('name');
$skill->value = Input::get('value');
$skill->color_code = Input::get('color_code');
$skill->save();
if (Input::hasFile('logo_path')) {
$image_path = '/assets/img/skill/';
$path = public_path() . $image_path;
$file = Input::file('logo_path');
$img_name = $skill->id.'.png';
$uploadSuccess = $file->move($path, $img_name);
$file_path = $path . $img_name;
$skill->img_path = $image_path . $img_name;
$crop_file = Image::make($file_path)->fit(20,20);
$crop_file->save($path . 'crop-'.$img_name, 65);
}else {
$skill->img_path = Input::get('logo_path');
}
$skill->save();
return Redirect::to('/skill') ->with('success','The skill was created succesfully!');
}
public function update($id){
$inputs = Input::all();
$skill = Skill::find($id);
$skill->name = Input::get('name');
$skill->type = Input::get('type');
$skill->value = Input::get('value');
$skill->color_code = Input::get('color_code');
$skill->save();
if (Input::hasFile('logo_path')) {
$image_path = '/assets/img/skill/';
$path = public_path() . $image_path;
$file = Input::file('logo_path');
$img_name = $skill->id.'.png';
$uploadSuccess = $file->move($path, $img_name);
$file_path = $path . $img_name;
$skill->img_path = $image_path . $img_name;
$crop_file = Image::make($file_path)->fit(20,20);
$crop_file->save($path . 'crop-'.$img_name, 65);
} else {
$skill->img_path = Input::get('logo_path');
}
$skill->save();
return Redirect::to('/skill') ->with('success','The skill was updated succesfully!');
}
public function destroy($id){
$skill = Skill::find($id);
$skill->delete();
$image_path = '/assets/img/skill/';
$path = public_path() . $image_path;
File::deleteDirectory($path);
return Redirect::to('/skill') ->with('success','The skill was deleted succesfully!');
}
public function skilldata(Request $request){
$skill = str_replace("-"," ",$request->skill);
$data = Skill::where(DB::raw('LOWER(type)'),'=',$skill)->get();
return response()->json($data, 200);
}
}
I also tried this 2 commands already
┌──[root#bheng]──[/home/forge/bheng]
└── php artisan cache:clear
Application cache cleared!
┌──[root#bheng]──[/home/forge/bheng]
└── composer dumpauto
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> #php artisan package:discover
Discovered Package: nesbot/carbon
Discovered Package: laravel/slack-notification-channel
Discovered Package: laravel/nexmo-notification-channel
Discovered Package: laravelcollective/remote
Discovered Package: htmlmin/htmlmin
Discovered Package: intervention/image
Discovered Package: laravelcollective/html
Package manifest generated successfully.
You have new mail in /var/mail/root
┌──[root#bheng]──[/home/forge/bheng]
└──
skill.create.blade.php
#extends('layouts.be.master')
#section('content')
<div class="card-body card-padding">
<div class="row">
{!! Form::open(array('class' => 'form-horizontal', 'role' =>'form', 'url'=>'skill/store','files' => true)) !!}
<div class="col-sm-4">
{{-- Name --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" value="{{Request::old('name')}}" value="" name="name" class="form-control" id="name" placeholder="Name">
</div>
</div>
{{-- Type --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Type</label>
<div class="col-sm-10">
<select name="type" class="form-control">
#foreach($skillTypes as $item)
<option value="{{ $item }}">{{ $item }}</option>
#endforeach
</select>
</div>
</div>
{{-- Value --}}
<div class="form-group">
<label class="col-sm-2 control-label">Value</label>
<div class="col-sm-8">
<br>
<input type="range" id="range-value" value="93" name="value">
</div>
<div class="col-sm-2">
<h3 id="text-value"></h3>
</div>
</div>
{{-- Color --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Color</label>
<div class="col-sm-2">
<input type="color" name="color_code" class="form-control" placeholder="Color" id="example-color-input">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<a class="btn btn-default" href="/skill"> Cancel </a>
<button type="submit" class="btn btn-info">Create</button>
</div>
</div>
</div>
<div class="col-sm-8">
{{-- Icon --}}
<div class="form-group">
<label class="col-sm-2 control-label" >Icon</label>
<div class="col-sm-10">
<img name="logo_path" id="skill-icon" width="300px"><br><br>
<input type="file" class="form-control" name="logo_path" aria-describedby="fileHelp">
</div>
<label class="col-sm-2 control-label" >Icon URL </label>
<div class="col-sm-10">
<input id="url-logo" name="logo_path" type="text" class="form-control">
</div>
</div>
</div>
{!!Form::close()!!}
</div>
</div>
#stop
#section('custom-scripts')
<script type="text/javascript" src="/js/Vibrant.js"></script>
<script type="text/javascript">
function readLogo(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#skill-icon').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
// Update media preview with base64 image
$( "input[name*='logo_path']" ).change(function(){
readLogo(this);
});
$( "#url-logo" ).on('keyup',function(){
$('#skill-icon').attr('src', $( "#url-logo" ).val());
});
$('#text-value').text($('#range-value').val());
$('#range-value').change(function(){
$('#text-value').text($('#range-value').val());
});
// Icon
var icon = $('#skill-icon');
icon.attr('src', $( "#url-logo" ).val());
$( "#url-logo" ).on('keyup',function(){
var vibrant = new Vibrant(icon[0]);
var swatches = vibrant.swatches()
for (var swatch in swatches)
if (swatches.hasOwnProperty(swatch) && swatches[swatch])
// console.log(swatches[swatch].getHex());
var color = swatches[swatch].getHex();
$( "input[name*='color_code']" ).val(color)
console.log('%c >>>>>>>>>>>>>>', "color:" + String(color) + ";");
console.log('color',color);
// Vibrant #3c62ac
// Muted #7484ab
// DarkVibrant #345cab
// DarkMuted #101010
// LightVibrant #849ccc
});
</script>
#stop
Please let me know if you spot anything I should not do.
It just route ordering issue.
Make Route Order Like This :
//Skill
Route::post('skill/store','SkillController#store');
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/{id}/update','SkillController#update');
Route::delete('skill/{id}/destroy','SkillController#destroy');
Route::get('skill/{id}/edit', 'SkillController#edit');
OR
If your making CRUD module then use Laravel 'Resource Controllers' routing method https://laravel.com/docs/5.7/controllers#resource-controllers
First Create Resource Controller : Run Below command In terminal
php artisan make:controller SkillController --resource
Then Put Below Line In 'routes/web.php' file
Route::resource('skill', 'SkillController');
You don't have a method= on your
And that is why assume Route::resource set up it will assume you're trying to access the show method.
Form::open(array('url' => 'foo/bar', 'method' => 'POST'))
Yeah as I thought in my initial comment, you haven't specified an action for the form - this should resolve your issues:
{!! Form::open(array('class' => 'form-horizontal', 'role' =>'form', 'url'=>'skill/store', 'action' => 'SkillController#store' ,'files' => true)) !!}
also, your routes are incorrect - your routes should be:
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/store','SkillController#store');
Route::get('skill/{id}/edit', 'SkillController#edit');
Route::patch('skill/{id}/update','SkillController#update'); //this should be put or patch not post
Route::delete('skill/{id}/destroy','SkillController#destroy');
if you already manually wrote routes like this
//Skill
Route::get('skill','SkillController#index');
Route::get('skill/create','SkillController#create');
Route::post('skill/store','SkillController#store');
Route::get('skill/{id}/edit', 'SkillController#edit');
Route::post('skill/{id}/update','SkillController#update');
Route::delete('skill/{id}/destroy','SkillController#destroy');
then you dont need this one, this code should be somewhere on your routes
Route::resource('skills','SkillController');
or
you can remove your entire manual written routes of skillcontroller
change it into this one
Route::resource('skills', 'SkillController', ['only'=> ['index','create','store','delete','edit','update']]);
i want to store image in my database as client agreement but i can't save any thing in database just the path i give manually here is what i have done
controller :
$filename = $request->file('agreement')->store('public/images');
$client = Client::create([
'title' => $request->title,
'description' => $request->description,
'fax'=>$request->fax,
'adrress1'=>$request->adrress1,
'telephone1'=>$request->telephone1,
'client_type'=>$request->client_type,
'sellpercent'=>$request->sellpercent,
'agreement'=>'uploads/agreement/'. $filename,
view :
.
.
.
<div class="form-group row">
<label class="col-form-label col-lg-2">test image</label>
<div class="col-lg-10">
<input type="file" name="agreement" class="form-control-plaintext">
</div>
</div>
<button type="submit" class="btn btn-primary btn-raised legitRipple">submit</button>
with this code i get this error on store function
Call to a member function store() on null
and if i remove store function i just save null in database
Firstly add enctype='multipart/form-data' in your form tag as an attribute.
Secondly,
replace $filename = $request->file('agreement')->store('public/images'); with $filename = $request->file('agreement')->move('public/images');
Hope that helps.