I want to upload a picture.
I wrote a codes for this ... but this photo is not added to the database at all. And Just, "else" is executed.
public function store(Request $request){
//Get Request Input
$name = $request ->input('name');
$description = $request ->input('description');
$cover_image = $request ->file('cover_image');
$owner_id = 1;
//Check Image Upload
if($cover_image)
{
$cover_image_filename = $cover_image -> getClientOriginalName();
$cover_image -> move(public_path('images'), $cover_image_filename);
}
else{
$cover_image_filename = 'noimage.jpg';
}
//Insert Gallery
DB::table('galleries')-> insert(
[
'name' => $name,
'description' => $description,
'cover_image' => $cover_image_filename,
'owner_id' => $owner_id
]
);
//Redirect
return \Redirect::route('gallery.index') -> with('message', 'Gallery Created');
}`
what's the wrong?
1) Make sure you have added enctype="multipart/form-data" in your form and a <input type="file"> with field name="cover_image"
2) Create a new folder named images in your laravel public folder.
3) In your controller
public function store(Request $request){
//Get Request Input
$name = $request ->input('name');
$description = $request ->input('description');
$owner_id = 1;
//Check Image Upload
if( $request->hasFile('cover_image')) {
$cover_image = $request->file('cover_image');
$path = public_path(). '/images/';
$cover_image_filename = $cover_image->getClientOriginalName();
$cover_image->move($path, $cover_image_filename);
}
else{
$cover_image_filename = 'noimage.jpg';
}
//Insert Gallery
DB::table('galleries')-> insert([
'name' => $name,
'description' => $description,
'cover_image' => $cover_image_filename,
'owner_id' => $owner_id
]);
//Redirect
return \Redirect::route('gallery.index') -> with('message', 'Gallery Created');
}
Hope it's helpful.
Related
I tried to update a form including a file(image) and to have the old image deleted. The update works fine but the old image is unable to delete. I tried this code but the image is not deleted. Please, help me. Thanks in advance.
public function update(Request $request, $id)
{
$slug = SlugService::createSlug(Category::class, 'slug', $request->title);
$request->validate([
'title'=>'required',
'category_image'=>'image'
]);
if ($request->hasFile('category_image')) {
$image = $request->file('category_image');
$newImageName = uniqid().'-'.$request->title.'.'.$image->getClientOriginalExtension();
$location = public_path('/categoryImage');
$OldImage = public_path('categoryImage/'.$request->category_image);
$image->move($location, $newImageName);
Storage::delete($OldImage);
}else {
$newImageName = $request->category_image;
}
Category::where('id', $id)->update([
'slug'=>$slug,
'title'=>$request->input('title'),
'details'=>$request->input('details'),
'category_image'=>$newImageName
]);
return redirect('category')->with('success', 'Category Successfully Updated');
}
public function update(Request $request, $id)
{
...
$category = Category::find($id); #new
if ($request->hasFile('category_image')) {
$image = $request->file('category_image');
$newImageName = uniqid().'-'.$request->title.'.'.$image->getClientOriginalExtension();
$location = public_path('/categoryImage');
$OldImage = public_path('categoryImage/'.$category->category_image); #new
$image->move($location, $newImageName);
unlink($OldImage); #new
}else {
$newImageName = $request->category_image;
}
#you can simplify this as
$category->slug = $slug;
$category->title = $request->title;
$category->details = $request->details;
$category->category_image = $newImageName;
$category->save()
return redirect('category')->with('success', 'Category Successfully Updated');
}
You can delete old image like this , if image is not in root of your storage insert your file location inside storage before image name.
unlink(storage_path('/location_inside_storage/'.$OldImage));
I'm building a blog on Laravel 7 and when I try to create a post I get this error:
Call to a member function categories() on bool
Here is my store method from my controller:
public function store(Request $request)
{
// Validate incoming data
$this->validate($request, [
'title' => 'required',
'image' => 'required',
'categories' => 'required',
'body' => 'required',
]);
$data = array();
$data['title'] = $request->title;
$data['slug'] = str_slug($request->title);
$data['user_id'] = Auth::id();
$data['meta_title'] = $request->meta_title;
$data['meta_description'] = $request->meta_description;
$image = $request->file('image');
$data['body'] = $request->body;
$data['created_at'] = \Carbon\Carbon::now();
$slug = str_slug($request->title);
if($image) {
$image_name = $slug . "-" . date('dmy_H_s_i');
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name . '.' . $ext;
$upload_path = "public/assets/frontend/uploads/posts/";
$image_url = $upload_path . $image_full_name;
$success = $image->move($upload_path, $image_full_name);
$data['image'] = $image_url;
$post = DB::table('posts')->insert($data);
$post->categories()->attach($request->categories);
return redirect(route('admin.posts.index'))->with('successMsg', 'Post has been saved successfully!');
}
}
The laravel error page has a problem with this line:
$post->categories()->attach($request->categories);
I have a separate table in my database to connect a post id with a category id, it's called category_post
The post content is inserted into the database except the new record in the category_post table
So how do I change that code to work?
Thanks
DB::table('posts')->insert($data);
Returns true|false based on successful / failed execution of query. If you want to write like
$post->categories()->attach($request->categories);
Then you need mode Post and create instance like this:
$post = new Post;
$post->title = $request->title;
// ...
$post->save();
And then you will have instance of Post class
In laravel I have a field in my edit view named Profile Picture, whenever I click On edit button I got all the values from database in edit view but I don't get image, And If whenever I click on submit button everytime I have to upload image without that I can't process further I want If I not upload new image then form will automatic consider old profile pic
my blade file is like
<div class="col-md-6">
<div class="form-group">
<label for="photo">Profile Picture :<span class="danger">*</span> </label>
<div class="row">
<div class="col-md-9">
<input type="file" class="form-control" id="file" name="file">
</div>
<div class="col-md-3">
#foreach ($empProfilePic as $empProfilePicture)
#if($employee->id == $empProfilePicture->id)
<img src="uploads/images/{{ $empProfilePicture->file }}" id="profile-img-tag" height="100" width="100">
#endif
#endforeach
</div>
</div>
</div>
</div>
Controller File
public function updateEmployee(Request $request, $id)
{
$employee = User::find($id);
//Get inputs for personal detail
$firstName = $request->get('firstName');
$middleName = $request->get('middleName');
$lastName = $request->get('lastName');
$gender = $request->get('gender');
$city = $request->get('city');
$state = $request->get('state');
$localAddress = $request->get('localAddress');
$permanentAddress = $request->get('permanentAddress');
$personalEmail = $request->get('personalEmail');
$mobileNumber = $request->get('mobileNumber');
$companyEmail = $request->get('companyEmail');
$empId = $request->get('empId');
$department = $request->get('department');
$designation = $request->get('designation');
$status = $request->get('status');
$totalExperience = $request->get('totalExperience');
$aboutMe = $request->get('aboutMe');
$roleName = $request->get('role');
$role = $request->get('role');
if ($role == 'hr')
{
$role = '5c8a51ed650fbd5398503043';
}
else
{
$role = '5c8a51ed650fbd5398503044';
}
// //Store Image In Folder
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/images', $name);
if (file_exists(public_path($name = $file->getClientOriginalName())))
{
unlink(public_path($name));
};
$accountHolderName = $request->get('accountHolderName');
$accountNumber = $request->get('accountNumber');
$bankName = $request->get('bankName');
$ifscCode = $request->get('ifsc_code');
$panNumber = $request->get('panNumber');
$branchName = $request->get('branchName');
//Enter in database
$employee->role_id = $role;
$employee->role_name = $roleName;
$employee->username = $firstName;
//Update Image
$employee->file = $name;
$employee->personal_email = $personalEmail;
$employee->company_email = $companyEmail;
$employee->status = $status;
$personalDetail = ([
'emp_id' => $empId,
'first_name' => $firstName,
'middle_name' => $middleName,
'last_name' => $lastName,
'gender' => $gender,
'city' => $city,
'state' => $state,
'local_address' => $localAddress,
'permanent_address' => $permanentAddress,
'personal_email' => $personalEmail,
'mobile_number' => $mobileNumber,
'department' => $department,
'designation' => $designation,
'total_experience' => $totalExperience,
'about_me' => $aboutMe,
]);
$bankDetail = ([
'account_holder_name' => $accountHolderName,
'account_number' => $accountNumber,
'bank_name' => $bankName,
'ifsc_code' => $ifscCode,
'pan_number' => $panNumber,
'branch_name' => $branchName,
]);
$employee->status = $status;
$employee->personal_detail = $personalDetail;
$employee->bank_detail = $bankDetail;
$employee->save();
return redirect('list-of-employees')->with('Success', 'Data Updated Successfully!');
}
Will anyone will help, Thank you in advance
In controller:
Code for update file:
Its update only when you select a file for the update.
Here I use the Employee model you can replace with your model
public function update(Request $request, $id){
$employee = Employee::find($id);
if($request->file != ''){
$path = public_path().'/uploads/images/';
//code for remove old file
if($employee->file != '' && $employee->file != null){
$file_old = $path.$employee->file;
unlink($file_old);
}
//upload new file
$file = $request->file;
$filename = $file->getClientOriginalName();
$file->move($path, $filename);
//for update in table
$employee->update(['file' => $filename]);
}
}
Try this. If you get the file in post method, only then set the file variable of an employee.
// //Store Image In Folder
if (isset($_FILES['file'])) {
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/images', $name);
if (file_exists(public_path($name = $file->getClientOriginalName())))
{
unlink(public_path($name));
};
//Update Image
$employee->file = $name;
}
//Enter in database
$employee->role_id = $role;
$employee->role_name = $roleName;
$employee->username = $firstName;
Make the image input optional (don't add required) on the blade file and on the validation (controller) then check before updating as:
if ($request->hasFile('image')) {
// Perform image update
}
I have tried almost all the forums on google but can't find a solution
to this problem, i have a product upload form which have two upload
images options as well, but i can't to seem upload any image to
database, neither i can't get the upload path method working. help me
out please. what is the best possible way to upload images to db?
**Controller File**
<?php
class Admin extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('admin_model');
}
public function index(){
$data['cats'] = $this->admin_model->get_cats();
$data['brands'] = $this->admin_model->get_brands();
$this->load->view('admin_view', $data, $data);
$data['upload_data'] = $this->upload->data();
$image = base_url("uploads/". $data['raw_name'] . $data['file_ext']);
$_POST['product_img1'] = $image;
//$image_url = $this->upload->data('full_path');
$product = array(
'product_name' => $this->input->post('name'),
'brand_id' => $this->input->post('brands'),
'cat_id' => $this->input->post('catagories'),
'product_price' => $this->input->post('price'),
'product_desc' => $this->input->post('desc'),
'product_img1' => $this->input->post('img')
);
//$insert_id = $this->admin_model->form_insert($product);
/**
$config = array(
'upload_path' => "./images/",
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => true
);
$this->load->library('upload', $config);
$data = $this->upload->data();
$image = base_url("./uploads/". $data['raw_name'] . $data['file_ext']);
$_POST['image'] = $image;
$this->load->model('admin_model');
**/
//if (!empty($_POST)) {
// Loading model
//$this->upload->do_upload();
//$data = array('product_img1' => $this->upload->data());
//$file_data = $this->upload->data();
//$data['product_img1'] = base_url().'/uploads/'.$file_data['file_name'];
//$product_img1 = $_FILES['product_img1']['name'];
//$product_img2 = $_FILES['product_img2']['name'];
//$temp_name1 = $_FILES['product_img1']['tmp_name'];
//$temp_name2 = $_FILES['product_img2']['tmp_name'];
//m_checkstatus(conn, identifier)ove_uploaded_file($temp_name1, "uploads/$product_img1");
//move_uploaded_file($temp_name2, "uploads/$product_img2");
//$this->admin_model->insert($data);
// Calling model
//$id = $this->admin_model->form_insert($data);
//}
}
}
?>
**Model File**
<?php
class admin_model extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert($product){
// Inserting in Table(students) of Database(college)
$insert = $this->db->insert('products', $product);
return $insert;
}
function get_cats(){
$this->db->select("*");
$this->db->from("catagories");
$query = $this->db->get();
return $query->result_array();
}
function get_brands(){
$this->db->select("*");
$this->db->from("brands");
$query = $this->db->get();
return $query->result_array();
}
}
?>
This question was already answered here
$this->input->post('img') in model won't work to retrieve the image information. Because the images are stored in $_FILES not in $_POST. So you need to use the upload library in codeignitor like below.
Also, make sure that your form contains the enctype="multipart/form-data" attr and your column type is blob in the database.
i will give you an example.This is the controller section.
public function add()
{
if (empty($_FILES['image']['name']))
{$this->session->set_flashdata('yes', 'Please Upload an image');
redirect($_SERVER['HTTP_REFERER']);
}
else
{
$target_dir = "images/products/";
$target_file = $target_dir . time().basename($_FILES["image"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$imgName = time().basename($_FILES["image"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"],$target_file);
$this->adminmodel->addproducts($imgName);
}
}
Model section
public function addproducts($imgName)
{
$data = array(
'name' => $this->input->post('name'),
'category' => $this->input->post('category'),
'image' => $imgName
);
$this->db->insert('products', $data);
$this->session->set_flashdata('yes', 'Product added successfully');
redirect('admin/products/productlist');
}
View Section(Form)
form role="form" action="admin/products/add" method="post" enctype="multipart/form-data" id="contact-form">
Your Form should contain enctype="multipart/form-data"
I have an edit form which has an image field where a user can upload a new image if he wants to.
But if the user does not upload a new photo I don't want to validate the image field and just use the photo that's already in the database. And not update the image field at all.
Here is my edit function:
public function postEdit($id) {
$product = Product::find($id);
// This should be in product model, just testing here
$edit_rules = array(
'category_id' => 'required|integer',
'title' => 'required|min:2',
'description' => 'required|min:10',
'price' => 'required|numeric',
'stock' => 'integer'
);
// Add image rule only if user uploaded new image
if (Input::has('image')) {
$edit_rules['image'] = 'required|image|mimes:jpeg,jpg,bmp,png,gif';
}
$v = Validator::make(Input::all(), $edit_rules);
if ($product) {
if ($v->fails()) {
return Redirect::back()->withErrors($v);
}
// Upload the new image
if (Input::has('image')) {
// Delete old image
File::delete('public/'.$product->image);
// Image edit
$image = Input::file('image');
$filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
Image::make($image->getRealPath())->resize(600, 600)->save('public/img/products/'.$filename);
$product->image = 'img/products/'.$filename;
$product->save();
}
// Except image because already called save if image was present, above
$product->update(Input::except('image'));
return Redirect::to('admin/products')->with('message', 'Product updated.');
}
return Redirect::to('admin/products');
}
Using this I can update all the values except the image.
If I don't upload a new photo it saves all other updated values.
If I do upload a new photo it just ignores it and saves all other updated values, doesn't upload the new photo.
Check if the request has the file:
public function update(Request $request)
{
// Update the model.
if($request->hasFile('photo')) {
// Process the new image.
}
// ...
}
public function update() {
$id=Input::get('id');
$rules= array('name'=>'required|regex:/(^[A-Za-z]+$)+/',
'detail'=>'required|regex:/(^[A-Za-z]+$)+/',
'images' => 'required|image');
$dat = Input::all();
$validation = Validator::make($dat,$rules);
if ($validation->passes()){
$file =Input::file('images');
$destinationPath = 'image/pack';
$image = value(function() use ($file){
$filename = date('Y-m-d-H:i:s') . '.' . $file->getClientOriginalExtension();
return strtolower($filename);
});
$newupload =Input::file('images')->move($destinationPath, $image);
DB::table('pkgdetail')
->where('id', $id)
->limit(1)
->update(array('name' => Input::get('name'), 'detail' => Input::get('detail'), 'image' => $newupload));
$data=PackModel::get_all();
return View::make('pkg_dis')->with('data',$data)
->withErrors($validation)
->with('message', 'Successfully updated.');
}
}
use Illuminate\Support\Facades\Input;
public function update(Request $request, $id)
{
if ($tag = Tag::find($id))
{
$this->validate($request, [
'tag_name' => 'required|min:3|max:100|regex: /^[a-zA-Z0-9\s][a-zA-Z0-9\s?]+$/u|unique:tags,tag_name,'.$id.',id',
]);
$tag->tag_name=$request->input('tag_name');
// get the image tag_img_Val
if($request->hasFile('tag_image'))
{
$this->validate($request, [
'tag_image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:1000',
]);
$img = $request->file('tag_image');
$old_image = 'uploads/' . $tag->tag_image;//get old image from storage
if ($img != '')
{
$image = rand() . '_' . ($img->getClientOriginalName());
$path = 'uploads/';
//Storing image
if ($img->move(public_path($path), $image))
{
$tag->tag_image = $image;
if ($tag->update())
{
if (is_file($old_image)) {
unlink($old_image); // delete the old image
}
return response()->json(['message' => 'Tag has been updated successfully.'],200);
}
else
{
unlink($image); // delete the uploaded image if not updated in database
return response()->json(['message' => "Sorry, Tag not updated"],500);
}
}
else
{
return response()->json(['message' => "Sorry, Image not moved"],500);
}
}
else
{
return response()->json(['message' => "Sorry, Image not uploaded"],500);
}
}
else
{
if($tag->update(Input::except('tag_image')))
{
return response()->json(['message' => 'Tag has been updated successfully.'],200);
}
else
{
return response()->json(['message' => "Sorry, Tag not updated"],500);
}
}
}
else
{
return response()->json(['message' => 'Tag not found'], 404);
}
}
You need to use multipart for form enctype
You can use another function to delete the images from the folder. like here
private function unlinkPostImages($images)
{
if(!empty($images)){
foreach ($images as $img){
$old_image = public_path('storage/' . $img->image);
if (file_exists($old_image)) {
#unlink($old_image);
}
}
}
}
Then call this function above image delete function. like this...
$this->unlinkPostImages($getId->images); // this will delete image from folder
$getId->images()->delete(); // --> this delete from database table $post->id
same this Click here..
my update function
public function update(UpdatePostRequest $request, Post $post)
{
//
$data = $request->only(['title', 'description', 'contents', 'price']);
// صورة الإعلان //
if ($request->hasFile('image')) {
Storage::disk('public')->delete($post->image);
$imagePath = $request->image;
$filename = Str::random(10).'-'.time().'-'.$imagePath->getClientOriginalName();
$image_resize = Image::make($imagePath->getRealPath());
$image_resize->fit(120);
$image_resize->orientate();
$image_resize->save(public_path('storage/images/' .$filename), 100);
$sImg = 'images/'. $filename;
$data['image'] = $sImg;
}
// -------- //
if ($request->hasFile('images'))
{
$getId = Post::find($post->id);
$this->unlinkPostImages($getId->images);
$getId->images()->delete();
$uploadPicture = array();
foreach ($request->file('images') as $photo) {
$file = $photo;
$filename = $file->getClientOriginalName();
$picture = date('His').'-'.$filename;
$file->move(public_path('storage/images/'), $picture);
array_push($uploadPicture, new PostImages(array('image' => 'images/'. $picture)));
}
$post->images()->saveMany($uploadPicture);
}
if ($request->input('contents')) {
$data['content'] = $request->contents;
}
//dd($data);
$post->update($data);
session()->flash('SUCCESS', 'تم تحديث الإعلان بنجاح.');
return redirect()->route('post.show', [$post->id, Post::slug($post->title)]);
}
In controller part:
$destinationPath = 'uploads';
$extension = Input::file('image')->getClientOriginalExtension();
var_dump($extension);
$fileName = rand(11111,99999).'.'.$extension;
Input::file('image')->move($destinationPath, $fileName);