Ajax image upload to database not working - ajax

I am trying to upload image to database using Ajax but It store image into public/images directory only,never store image into database,I had grabbed from itsolution for test purpose but never work,Could any one tell where am I wrong?
Route
Route::get('ajaxImageUpload', ['uses'=>'AjaxImageUploadController#ajaxImageUpload']);
Route::post('ajaxImageUpload', ['as'=>'ajaxImageUpload','uses'=>'AjaxImageUploadController#ajaxImageUploadPost']);
Controller
public function ajaxImageUploadPost(Request $request) {
$validator = Validator::make($request->all(), [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($validator->passes()) {
$input = $request->all();
$input['image'] = time() . '.' . $request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $input['image']);
AjaxImage::create($input);
return response()->json(['success' => 'done']);
}
return response()->json(['error' => $validator->errors()->all()]);
}
View
<form action="{{ route('ajaxImageUpload') }}" enctype="multipart/form-data" method="POST">
<input type="text" name="title" class="form-control" placeholder="Add Title">
<input type="file" name="image" class="form-control">
<button class="btn btn-success upload-image" type="submit">Upload Image</button>
</form>
<script>
$("body").on("click", ".upload-image", function (e) {
$(this).parents("form").ajaxForm(options);
});
var options = {
complete: function (response) {
if ($.isEmptyObject(response.responseJSON.error)) {
$("input[name='title']").val('');
alert('Image Upload Successfully.');
} else {
printErrorMsg(response.responseJSON.error);
}
}};
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function (key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
</script>

Save Image Location To The Database

use intervention;
public function ajaxImageUploadPost(Request $request){
$validator = Validator::make($request->all(), ['title' => 'required','image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
if ($validator->passes()) {
$image = new AjaxImage();
$image->title = $request->title;
if ($request->hasFile('image')) {
$img=$request->file('resim');
$filename=time().".".$img->getClientOriginalExtension();
$location=public_path('img/'.$filename);
Image::make($img)->save($location);
$image->image=$filename;
}
$image->save();
return response()->json(['success'=>'done']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}

Related

How to insert record in 2 tables using single form (Laravel)?

CONTROLLER
public function store_resto(Request $request){
// dd($request->all());
$restaurant = new Restaurant();
$restaurant->name = $request->input('name');
$restaurant->email = $request->input('email');
$restaurant->address = $request->input('address');
$restaurant->save();
$image = $request->hasfile('image');
$photo = rand(1,9999).'.'.$image;
$path = public_path().'/files/';
$image->move($path, $photo);
RestoImage::create([
'image'=>$image,
'resto_id'=>$restaurant->id,
]);
$request->session()->flash('status', 'Restaurant added successfully');
return redirect('list');
}
VIEW FILE
<form method="post" action="{{route('store_resto')}}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label>Resto Name</label>
<input type="name" name="name" class="form-control">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label>Address</label>
<input type="text" name="address" class="form-control">
</div>
<div class="form-group">
<label>Image</label>
<input type="file" name="image" class="form-control">
</div><br>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
RestoImage Model
class RestoImage extends Model
{
use HasFactory;
protected $fillable = ['image','resto_id'];
public function restaurants(){
$this->belongsTo(Restaurant::class, 'resto_id');
}
}
Restaurant Model
class Restaurant extends Model
{
use HasFactory;
public $timestamps = false;
public function menus(){
$this->hasMany(Menu::class);
}
public function restoimage(){
$this->hasOne(RestoImage::class, 'resto_id');
}
}
Each restaurant will have 1 image. When an admin submits the form, 1 record should be inserted in both tables i.e. restaurants and resto_images. I tried this way but when I submit the form, It shows error "Call to a member function move() on bool". Please correct me if I am doing wrong. Thanks in advance.
Here i Worked on your code to explain how these things works.This is an example can help you. Not for two you can add so many tables from one function of controller. Approve my answer if you find solution or reason for getting error.
You have error because code doesn't find your image format or mine:type(png, jpeg)
$photo = rand(1,9999).'.'.$image;
Solution- you have to get image format or extention by this code
$extention = $emp_image_file->getClientOriginalExtension();
Your solution should be like this
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$photo_file = $request->file('image');
$photo='';
if($photo_file){
$file_size = $photo_file->getSize();
$image_name = $photo_file->getClientOriginalName();
$extention = $photo_file->getClientOriginalExtension();
$photo = value(function() use ($photo_file){
$filename = time().'.'. $photo_file->getClientOriginalExtension();
return strtolower($filename);
});
$photo_file->move($destinationPath1, $photo);
}
Put js in your view file
<script type="text/javascript">
function readURL(input) {
if (input.image && input.image[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is you input
<input type="file" class="form-control" name="image" >
I Also Worked For Other Visitors See Once
public function store_resto(Request $request){
<!-- validation code begins -->
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required|email|unique:users',
]);
<!-- validation code ends -->
$data = $request->all();
$table1 = Required_Model1::create([
'name' =>$data['emp_name'],
'email' =>$data['email'],
]);
$table2 = Required_Model2::create([
'name' => $data['emp_name'],
'code' => $data['emp_code'],
'status' => $data['emp_status'],
'email' => $data['email'],
'gender' => $data['gender'],
'table1_id' => $table1->id,
]);
$table3 = Required_Model3::create([
'role' => $data['role'],
'table1_id' => $table1->id,
'table2_id' => $table2->id,
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
}
Comment or delete this part of code if you doesn't want to validate or mandatory.
$this->validate($request, [
'name'=>'required|max:120',
'email'=>'required,
]);
Above code explains
column name must be filled with 120 characters or not be blank.
column email must be filled.
if these two doesn't satisfy it will redirect back.
This below code
If validation is set like above code this will check and work as defined. If validation is set they check two fields name and email, if they filled or not blank it will proceed further. If validation is set fields are not filled or blank they redirect back. If validation is not set it will proceed further.
if(isset($table1, $table2, $table3)) {
$request->session()->flash('status', 'Restaurant added successfully');
return redirect()->route('employee-manager');
}else{
return redirect()->back();
}
Change these two lines
<input type="name" name="name" class="form-control" required="true" />
<input type="email" name="email" class="form-control" required="true" />
Model 1 should be like this
class Required_Model1 extends Model
{
protected $fillable = ['name','email'];
}
Model 2 should be like this
class Required_Model2 extends Model
{
protected $fillable = ['name','code', 'status', 'email', 'gender', 'table1_id'];
}
Model 3 should be like this
class Required_Model3 extends Model
{
protected $fillable = ['role','table1_id', 'table2_id'];
}
Let's talk on your error as you posted
You have face error because you want to move your image name in form of boolean. Here is gave you an standard code you can use it
$path1 = 'assets/img/emp/';
$destinationPath1 = $path1;
$emp_image_file = $request->file('employee_images');
$emp_image='';
if($emp_image_file){
$file_size = $emp_image_file->getSize();
$image_name = $emp_image_file->getClientOriginalName();
$extention = $emp_image_file->getClientOriginalExtension();
$emp_image = value(function() use ($emp_image_file){
$filename = time().'.'. $emp_image_file->getClientOriginalExtension();
return strtolower($filename);
});
$emp_image_file->move($destinationPath1, $emp_image);
}
Put this in which table you wanted to save
'photo' => $emp_image,
Add this in your view make sure you edit like your requirement
<script type="text/javascript">
function readURL(input) {
if (input.employee_images && input.employee_images[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#employee_imagesPreview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
This is input
<input type="file" class="form-control" name="employee_images" >
$image = $request->hasfile('image');
This method is a boolean method. It will return true/false. Instead use
$request->file('image');
So first, here:
$image = $request->hasfile('image');
You are setting $image to a boolean by checking if it has that file and then later you want to run move on a that boolean which is not possible. Rather do:
if($request->hasfile('image'))
{
$image = $request->file('image');
$image->move($path, $photo);
}

delete if password is correct

i need to create a condition that clears the record but with a password.
if the password is correct execute the delete();
controller:
public function eliminar($id){
$registros = \App\Models\Registro::findOrFail($id);
$registros->delete();
return redirect('sistema')->with('mensaje', 'Registro Borrado con exito');
}
public function borrar($id){
// return $request->all();
$data = [
'category_name' => 'datatable',
'page_name' => 'multiple_tables',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
'fechax' => Carbon::now(),
'borrar' => \App\Models\Registro::findOrFail($id),
'password' => 'PASSCODE',
];
return view('borrar')->with($data);
}
blade.php:
<h1>Do you want to delete the record?</h1>
<form action="{{ route('eliminar', $borrar) }}" class="d-inline" method="POST">
#method('DELETE')
#csrf
<button type="submit" class="btn btn-danger btn-sm">DELETE</button>
<div class="form-group col-md-6">
<label for="telefono">Password</label>
<input name="password" type="password" class="form-control" id="telefono" required>
</div>
</form>
the password is obtained statically
How can I make it delete without the password is identical?
help please
If the password is saved statically, inside in a variable, the following should do the job for you.
routes/web.php
Route::delete('/path/here', 'SomeController#destroy');
SomeController.php
public function destroy($id)
{
$model = YourModel::find($id);
if (! $model) {
session()->flash('error_message', 'Model not found with the given id: ', . $id);
return back();
}
// $password is the password that you have saved somewhere
if (request()->password_field_value == $password) {
$model->delete();
session()->flash('success_message', 'Model deleted successfully.');
return back();
}
session()->flash('error_message', 'Invalid password. Try again');
return back();
}

How to validate Dynamic input in vuejs / Laravel

I'm catching errors via interceptors and a Toast for UI. Usually the error is caught by the interceptor and displayed via the toast for one-time inputs, i'm trying to catch errors for an uncertain number of inputs. So far looping through the input array and setting rules does not work.
Component.vue
<template>
<div>
<div class="form-group" v-for="(input,k) in inputs" :key="k">
<input type="text" id="name" placeholder="Name" v-model="input.name" />
<span>
<i class="fas fa-minus" #click="remove(k)" v-show="k || ( !k && inputs.length > 1)"></i>
<i class="fas fa-plus" #click="add(k)" v-show="k == inputs.length-1"></i>
</span>
</div>
<button #click="addName">Create</button>
</div>
</template>
<script>
export default {
data() {
return {
inputs: [{name: ''}]
}
},
methods: {
add(index) {
this.inputs.push({ name: ''});
console.log( this.inputs);
},
remove(index) {
this.inputs.splice(index, 1);
},
addName() {
axios.post('/user', {userinputs:this.inputs}).then(response => {})
.catch(error => {
console.log(error);
});
}
}
}
</script>
Controller:
public function store(Request $request)
{
$rules = [
'userinputs' => 'required|max:255',
];
foreach ($request->input('userinputs') as $key => $my_object_in_array) {
$rules[$my_object_in_array['name']] = 'required|max:10';
}
return $rules;
}
I hope this is what you wanted to achieve.
public function store(Request $request)
{
$rules = [
'userinputs.*.name' => 'required|max:255',
];
$validator = \Illuminate\Support\Facades\Validator::make($request->all(), $rules);
if ($validator->fails()) {
//Return the errors as JSON
return response()->json(['success' => 'false', 'errors' => $validator->errors()], 400);
}
//Do something
return ['success' => 'true'];
}

how to form popup model validation in codeigniter without using javascript

how to form popup model validation in codeigniter without using javascript and jquery
public function login() {
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[4]|max_length[40]');
if ($this->form_validation->run() && $this->Login_model->loginn($email, $password)) {
$this->welcome();
} else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
$this->index();
}
}
view page, how to form popup model validation in codeigniter without using javascript and jquery
<form id="register-form" onsubmit ="return validateForm()" action="<?php echo base_url(); ?>Index.php/Login_cntrl/login" method="POST" >
<div class="field-wrap">
<label class="view-label">Email Address</label>
<input type="email" placeholder="Email Address" name="email" id="email" class="input-control" value=""/>
</div>
<div class="field-wrap">
<input type="password" placeholder="Password" name="password" id="password" value="" />
<a href="javascript:void(0)" class="btn btn-link btn-nobg" id="btn-show-forgot" >Forgot ?</a>
</div>
<div class="field-wrap">
<button type="submit" class="btn btn-submit" name="ulogin" id="ulogin" value="ulogin" >Login</button>
</div>
<div class="field-wrap">
NEW User? Sign up
</div>
</form>
model code,how to form popup model validation in codeigniter without using javascript and jquery
public function loginn($email, $password) {
// $this->db->where('email', $email);
$where="(email='$email' or mobile_no='$email') and password='$password'";
$this->db->where($where);
$query = $this->db->get('customer_registration');
$count = $query->num_rows(); //counting result from query
if ($count === 0) {
// $this->db->where('email', $email);
$where="(email='$email' or mobile_no='$email') and password='$password'";
$this->db->where($where);
// $this->db->where('password', $password);
$query = $this->db->get('supplier_registration');
}
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
//add all data to session
$newdata = array(
'id' => $row->id,
'first_name' => $row->first_name,
'last_name' => $row->last_name,
'email' => $row->email,
'password' => $row->password,
'mobile_number' => $row->mobile_number,
'logged_in' => TRUE,
);
}
$this->session->set_userdata($newdata);
return true;
}
return false;
}
Below shown code is working properly
public function loginn($email, $password) {
// $this->db->where('email', $email);
$where = "(email='$email' or mobile_no='$email') and password='$password'";
$this->db->where($where);
$query = $this->db->get('customer_registration');
$count = $query->num_rows(); //counting result from query
$tablename = "customer";
if ($count === 0) {
// $this->db->where('email', $email);
$where = "(email='$email' or mobile_no='$email') and password='$password'";
$this->db->where($where);
// $this->db->where('password', $password);
$query = $this->db->get('supplier_registration');
$tablename = "supplier";
}
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
//add all data to session
$newdata = array(
'id' => $row->id,
'first_name' => $row->first_name,
'last_name' => $row->last_name,
'email' => $row->email,
'password' => $row->password,
'mobile_number' => $row->mobile_number,
'log_in' => TRUE,
);
}
$this->session->set_userdata($newdata);
return $tablename;
}
return $tablenam = " '";
}

methodNotAllowed(array('GET', 'HEAD')) in RouteCollection.php laravel 5.0

I want to login as I submit the form but I am getting an error.
The form code is as follows:
{!! Form::open() !!}
{{ $errors->first("parentPassword") }}<br />
<div>
<legend>Parent</legend>
Email<br>
<input type="email" id="email" name="parentEmail" required>
<br>
Password<br>
<input type="password" name="parentPassword">
<br><br>
</div>
{!!Form::submit('Submit',array('class' => 'btn btn-outline btn-primary')) !!} </fieldset>
{!! Form::close() !!}
The controller code is as follows:
App\Http\Controllers;
use Illuminate\Support\Facades\Redirect;
class loka extends Controller
{
public function login()
{
if ($this->isPostRequest()) {
$validator = $this->getLoginValidator();
if ($validator->passes()) {
$credentials = $this->getLoginCredentials();
if (Auth::attempt($credentials)) {
return redirect()->intended('/');
}
return Redirect::back()->withErrors([
"parentPassword" => ["Credentials invalid."]
]);
} else {
return Redirect::back()
->withInput()
->withErrors($validator);
}
}
return view("signup.index");
}
protected function isPostRequest()
{
// return Request::isMethod('post');
}
protected function getLoginValidator()
{
return Validator::make(Request::all(), [
"parentEmail" => "required",
"parentPassword" => "required"
]);
}
protected function getLoginCredentials()
{
return [
"parentEmail" => Request::input("parentEmail"),
"parentPassword" => Request::input("parentPassword")
];
}
}
The route is as follows:
Route::patch("/index", [
"as" => "login/index",
"uses" => "loka#login"
]);

Resources