I have a view where I pull the data with an "onclick" of the "Asisgnar" button and when I click on the "Enviar formulario" button, an email is sent directly with the loaded data... this works perfectly, but I would like it to be sent the mail without redirecting me to another page.
My form code
<form action="{{route('contactanos.store')}}" method="POST">
{{ csrf_field() }}
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="inspector">Inspector</label>
<select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" id="inspector" for="inspector" name="inspector" >
<option selected></option>
#foreach($users as $user)
<option value="{{ $user->name }}">{{ $user->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<label for="estado">Estado</label>
<select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" id="estado" for="estado" name="estado">
<option selected></option>
<option value="Pendiente">Pendiente</option>
<option value="Coordinado">Coordinado</option>
<option value="Peritando">Derivado a inspector</option>
<option value="Baja">Baja</option>
</select>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="localidad">Localidad</label>
<input type="text" name="localidad" id="localidad" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="fechaip">Fecha IP</label>
<input type="date" name="fechaip" id="fechaip" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="siniestro">Siniestro</label>
<input type="text" name="siniestro" id="siniestro" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="inspector">Inspector</label>
<select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" id="emailperito" for="emailperito" name="emailperito" >
<option selected></option>
#foreach($users as $user)
<option value="{{ $user->email }}">{{ $user->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="email">Email taller</label>
<input type="text" name="email" id="email" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="patente">Patente</label>
<input type="text" name="patente" id="patente" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="modalidad">Tipo de inspección</label>
<input type="text" name="modalidad" id="modalidad" class="form-control" >
</div>
</div>
<input type="hidden" id="id">
<button type="submit" id="updateButton" class="btn btn-success" onclick="updateData(event)">Guardar</button>
<button type="submit" class="btn btn-primary float-right">Enviar formulario</button>
</form>
Controller Code to send mail
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
//mail
use App\Mail\ContactanosMailable;
use Illuminate\Support\Facades\Mail;
use App\Models\Siniestro;
class CoordinacionesController extends Controller
{
public function index(){
return view('contactanos.index');
}
public function store(Request $request){
$siniestro = Siniestro::paginate(1000);
$this->siniestro = $siniestro;
$email = $this->siniestro['emailperito'];
$cc = $this->siniestro['email'];
$correo = new ContactanosMailable($request->all());
Mail::to($email)->cc($cc)->send($correo);
return redirect()->route('siniestros.index');
}
}
View.blade
My view
I have tried removing the post method and removing the "return redirect()->route('sinisters.index');" of the controller, but it doesn't work.
you can do it with an ajax like this
$.ajax({
url: '{{route("your-route")}}',
method: "POST",
data: {
_token: '<?php echo csrf_token() ?>',
... // the rest of your form
}
})
Try this solution
add jquery in your blade file
jquery cdn
<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
Give class to your form
<form action="{{route('contactanos.store')}}" method="POST" class="my_form">
Change your javascript code as per below
$(document).on('submit', '.my_form', function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (response) {
if(response.success){
//handle success message
} else {
//handle error message
}
},
error: function (xhr, textStatus, errorThrown) {
console.log("ERROR");
}
});
});
change your controller->store function
public function store(Request $request){
try {
$siniestro = Siniestro::paginate(1000);
$this->siniestro = $siniestro;
$email = $this->siniestro['emailperito'];
$cc = $this->siniestro['email'];
$correo = new ContactanosMailable($request->all());
Mail::to($email)->cc($cc)->send($correo);
return response()->json([
'success' => true,
'message' => 'Your success message'
]);
} catch (\Throwable $th) {
return response()->json([
'success' => false,
'message' => 'Your error message'
]);
}
}
iam new in laravel i have problem to add data in data base using laravel , i get only validation response in form but after i submit data i don't get any response only just page refresh . without any message appear in view
ac any on help me ?
this is man categories request for validation
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MaincategoryRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'id' => 'integer|required',
'name' => 'min:2|required|max:50|unique:category_translations',
'slug' => 'required|unique:categories,slug,'.$this->id,
'url' => 'required|url',
'status' => 'integer'
];
}
// validation messages
public function messages()
{
return [
'id.required'=>trans('dashboard\validate.required'),
'id.integer'=>trans('dashboard\validate.integer'),
'id.exists'=>trans('dashboard\validate.exists'),
'name.required'=>trans('dashboard\validate.required'),
'name.min'=>trans('dashboard\validate.min'),
'name.max'=>trans('dashboard\validate.max'),
'name.unique'=>trans('dashboard\validate.unique'),
'slug.required'=>trans('dashboard\validate.required'),
'slug.min'=>trans('dashboard\validate.min'),
'slug.max'=>trans('dashboard\validate.max'),
'slug.unique'=>trans('dashboard\validate.unique'),
'url.active_url'=>trans('dashboard\validate.url'),
'url.required'=>trans('dashboard\validate.required'),
'status.integer'=>trans('dashboard\validate.integer'),
];
}
}
this is my route in details
Route::get('create','MainCategoriesController#create') -> name('maincategories.create');
Route::post('store','MainCategoriesController#store') -> name('maincategories.store');
this is my controller in details
public function store(MaincategoryRequest $request )
{
try{
DB::beginTransaction();
// prepare data
$validatedData = array(
'name' =>$request->name,
'url' =>$request->url,
'slug' =>$request->slug,
'last_updated_by' =>auth('admin')->user()->id,
'created_by' =>auth('admin')->user()->id,
'created' =>time(),
);
//check if status is sent
$request->has('status') ? $validatedData['status'] = 1: $validatedData['status'] = 2;
// check if category is exist
$add = Category::create($validatedData);
if (!$add){
return redirect()->route('maincategories.create')->with(['error'=> trans('dashboard\messages.addfailed')]);
}
// start add translated data
$add->name=$request->name;
$add->save();
return redirect()->back()->with('success',trans('dashboard\messages.save'));
DB::commit();
}catch (\Exception $ex){
return redirect()->back()->with('error',trans('dashboard\messages.addfailed'));
DB::rollBack();
}
}
this is my view in details
#extends('layouts.admin')
#section("title",trans('dashboard\category.title-add'))
#section('content')
<div class="app-content content">
<div class="content-wrapper">
<div class="content-header row">
<div class="content-header-left col-md-6 col-12 mb-2">
<div class="row breadcrumbs-top">
<div class="breadcrumb-wrapper col-12">
<ol class="breadcrumb">
<li class="breadcrumb-item"> {{trans('dashboard\messages.home')}}
</li>
<li class="breadcrumb-item active">{{trans('dashboard\category.title-add')}}
</li>
</ol>
</div>
</div>
</div>
</div>
<div class="content-body">
<!-- Basic form layout section start -->
<section id="basic-form-layouts">
<div class="row match-height">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4 class="card-title" id="basic-layout-form"> {{trans('dashboard\category.title-add')}} </h4>
<a class="heading-elements-toggle"><i
class="la la-ellipsis-v font-medium-3"></i></a>
<div class="heading-elements">
<ul class="list-inline mb-0">
<li><a data-action="collapse"><i class="ft-minus"></i></a></li>
<li><a data-action="reload"><i class="ft-rotate-cw"></i></a></li>
<li><a data-action="expand"><i class="ft-maximize"></i></a></li>
<li><a data-action="close"><i class="ft-x"></i></a></li>
</ul>
</div>
</div>
#include('dashboard.includes.alerts.success')
#include('dashboard.includes.alerts.errors')
<div class="card-content collapse show">
<div class="card-body">
<form class="form"
action="{{route('maincategories.store')}}"
method="post"
enctype="multipart/form-data">
#csrf
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="projectinput1"> {{trans('dashboard\category.name')}} </label>
<input type="text" value="{{old('name')}}"
id="name"
class="form-control"
placeholder=" "
name="name">
#error("name")
<span class="text-danger">{{$message}}</span>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="projectinput1"> {{trans('dashboard\category.slug')}} </label>
<input type="text"
value="{{old('slug')}}"
id="email"
class="form-control"
placeholder=" "
name="slug">
#error("slug")
<span class="text-danger">{{$message}}</span>
#enderror
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="projectinput1"> {{trans('dashboard\category.url')}} </label>
<input type="text"
value="{{old('url')}}"
id="plain_value"
class="form-control"
placeholder=" "
name="url">
#error("url")
<span class="text-danger">{{$message}}</span>
#enderror
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label> {{trans('dashboard\category.image')}} </label>
<label id="projectinput7" class="file center-block">
<input type="file" id="file" name="image">
<span class="file-custom"></span>
</label>
#error('image')
<span class="text-danger">{{$message}}</span>
#enderror
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group mt-1">
<input type="checkbox" value="1"
name="status"
id="switcheryColor4"
class="switchery" data-color="success"
checked />
<label for="switcheryColor4"
class="card-title ml-1">{{trans('dashboard\messages.status')}} </label>
#error("status")
<span class="text-danger"> </span>
#enderror
</div>
</div>
</div>
<div class="form-actions">
<button type="button" class="btn btn-warning mr-1"
onclick="history.back();">
<i class="ft-x"></i> {{trans('dashboard\messages.back')}}
</button>
<button type="submit" class="btn btn-primary">
<i class="la la-check-square-o"></i> {{trans('dashboard\messages.save')}}
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- // Basic form layout section end -->
</div>
</div>
</div>
#stop
#section('script')
<script >
$(document).ready(function() {
//start update password
$("#EditPassword").submit(function(){
var formData = $(this).serialize();
var allData = formData + "&action=editPass";
$('#repassword_error').text('');
$('#password_error').text('');
$.ajax({
url: "{{url("admin/category/update_password/{id}")}}",
type:"PUT",
data: allData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
beforeSend:function(){
//alert(allData)
},
statusCode: {
404: function() {
alert( "page not found" );
},
},
success:function(valdata) {
//alert(valdata);
//alert("")
if(valdata.status == "success")
{
$("#updatePasswordResult").html(valdata.message);
setTimeout(function(){$('#changepassword').modal('hide');}, 2000);
}else{
$("#updatePasswordResult").html(valdata.message);
}
},
error: function (reject) {
var response = $.parseJSON(reject.responseText);
$.each(response.errors, function (key, val) {
$("#" + key + "_error").text(val[0]);
});
}
});
return false;
});
});
</script>
#stop
You don't need to use transaction here, However, move DB::commit before return .
besides, check $guarded and $fillable in your model.
also you can dd($ex->getMessage()) to track the error.
This question already has answers here:
Stop form refreshing page on submit
(20 answers)
How can I prevent refresh of page when button inside form is clicked?
(16 answers)
Closed 4 years ago.
Im trying to insert data with ajax, but i got error :
Symfony \ Component \ HttpKernel \ Exception \
MethodNotAllowedHttpException
This is my form in add-gallery.blade.php:
<form method="post" action="" enctype="multipart/form-data" autocomplete="off" class="mt-4 mb-4 card p-4">
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="gallery_name">Name</label>
</div>
<div class="col-md-6 align-self-center">
<input type="text" name="gallery_name" id="gallery_name" class="form-control" placeholder="Type Gallery Name" />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="category">Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="category" id="category">
<option value="">Select Category</option>
<option value="Home">Home</option>
<option value="Office">Office</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="subcategory">Sub Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="subcategory" id="subcategory">
<option value="">Select Sub Category</option>
<option value="Interior">Interior</option>
<option value="Eksterior">Eksterior</option>
<option value="Decoration">Decoration</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="subsubcategory">Subsub Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="subsubcategory" id="subsubcategory">
<option value="">Select Subsub Category</option>
<option value="Room">Room</option>
<option value="Bathroom">Bathroom</option>
<option value="Kitchen">Kitchen</option>
<option value="Terrace">Terrace</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label for="gallery_image">Image</label>
</div>
<div class="col-md-10">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail w-100" style="display: none;">
<img src="http://placehold.it/1186x800" />
</div>
<div id="toAnnotate" class="fileinput-preview fileinput-exists thumbnail w-100"></div>
<div>
<span class="btn btn-xs btn-success btn-file"><span class="fileinput-new">Select image</span><span class="fileinput-exists">Change</span><input type="file" name="gallery_image" id="gallery_image"></span>
Remove
</div>
</div>
<p><small><em>Image Size : 1186px (width), 800px (height)</em></small></p>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center"> </div>
<div class="col-md-10 align-self-center">
<button type="button" class="btn btn-secondary">Cancel</button>
<button type="submit" class="btn btn-success" id="save">Save</button>
</div>
</div>
</div>
</form>
And below is my ajax in same page add-gallery.blade.php:
<script type="text/javascript">
$(document).ready(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//Save
$('#save').on('click', function () {
var gallery_name = $('#gallery_name').val();
var category = $('#category').val();
var subcategory = $('#subcategory').val();
var subsubcategory = $('#subsubcategory').val();
var gallery_image = $('#gallery_image').val();
var dataSubmit = $(this).serialize();
var top = top;
var left = left;
var file_data = $('#gallery_image').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : "{{ url('galleries/store') }}",
dataType : 'text', // what to expect back from the server
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
dataType : 'json',
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
});
</script>
This is my routes file web.php:
Route::post('galleries/store','Dashboard\GalleryController#store');
And this is my controller GalleryController.php:
public function store(Request $request){
if($request->hasFile('gallery_image')){
$fileImage = $request->file('gallery_image');
$fileImageExtension = $fileImage->extension();
$renameFileImage = 'ImageGalleries'.time().'.'.$fileImageExtension;
$pathFileImage = $fileImage->storeAs('public/galleries_documents/images_galleries', $renameFileImage); /images_articles
$galleries = new Gallery;
$points = new Point;
$galleries->name = $request->gallery_name;
$galleries->category = $request->category;
$galleries->sub_category = $request->subcategory;
$galleries->sub_subcategory = $request->subsubcategory;
$galleries->image = $renameFileImage;
$galleries->lang_id = session('lang_id');
$galleries->save();
$lastInsertId = $galleries->id;
for($i = 0; $i < count($request->node); $i++) {
$node[] = [
'node_position_top' => $request->node[$i],
'node_position_left' => $request->node[$i],
'id_gallery' => $lastInsertId,
];
$points->lang_id = session('lang_id');
}
Point::insert($node); //save to table
print_r($node[]);
exit();
}
}
I am new to Laravel. I want to use MongoDB with laravel so I have installed mongodb and configured php extension also(copied mongo dll file) and it works fine.
Now I want to use CRUD operation in laravel using mongoDB. How can I use. How to create model. What I need to modify in model.
Note: show me model code. In model what I have to write.
Thank You
It seems that there's a package that enables you to use MongoDB with Eloquent. I'm not a fan of linking external sources without quoting information here, but copying their readme sounds counterproductive as well. The instructions seem easy enough, so I hope this can help you: Laravel MongoDB.
Example code MongoDb + Php:
Insert:
$mongo = new MongoClient();
$db = $mongo->mydb1;
$data = array('emp_id' => '1', 'first_name' => 'Tiger' , 'last_name' => 'Nixon', 'position' => 'System Architect', 'email' => 't.nixon#datatables.net', 'office' => 'Edinburgh', 'start_date' => '2011-04-25 00:00:00', 'age' => '61', 'salary' => '320800', 'projects' => array('Project1', 'Project2', 'Project3'));
$collection = $db->createCollection("emp_details");
if($collection->insert($data))
{
echo '<p style="color:green;">Record inserted successfully</p>';
}
Update:
$mongo = new MongoClient();
$db = $mongo->mydb1;
/* Note: Here we are using the update() method. The update() method update values in the existing document */
$collection = $db->createCollection("emp_details");
$newdata = array('$set' => array("age" => "55", "salary" => "320000"));
// specify the column name whose value is to be updated. If no such column than a new column is created with the same name.
$condition = array("emp_id" => "1");
// specify the condition with column name. If no such column exist than no record will update
if($collection->update($condition, $newdata))
{
echo '<p style="color:green;">Record updated successfully</p>';
}
else
{
echo '<p style="color:red;">Error in update</p>';
}
Delete:
$mongo = new MongoClient();
// name of database which is to be created
$db_name = 'local';
// get the list of database and check if DB exist, if not than create it.
$dblists = $mongo->listDBs();
if(count($dblists) > 0)
{
$count = 0;
$exist = false;
foreach($dblists['databases'] as $databases)
{
if($databases['name'] == $db_name)
{
$exist = true;
break;
}
}
}
if($exist)
{
$db = $mongo->db_name; // select the db which is to be deleted
if($db)
{
if($db->drop())
{
echo '<p style="color:green;">Database deleted successfully</p>';
}
}
}
else
{
echo '<p style="color:red;">No such database exist</p>';
}
In case of Laravel, you have to study the basic CRUD operation then you will use this very well.
Create Customer Controller
<?php
namespace App\Http\Controllers;
use App\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Hash;
class CustomerController extends Controller
{
public function index(Request $request)
{
$search = $request->get('search');
$field = $request->get('field') != '' ? $request->get('field') : 'firstname';
$sort = $request->get('sort') != '' ? $request->get('sort') : 'asc';
$customers = new Customer();
$customers = $customers->where('firstname', 'like', '%' . $search . '%')
->orderBy($field, $sort)
->paginate(5)
->withPath('?search=' . $search . '&field=' . $field . '&sort=' . $sort);
return view('theme.customers_list', compact('customers'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
public function add()
{
return view('theme.customer_form');
}
public function add_record(Request $request)
{
$this->validate($request,
[
'firstname' =>'required|max:20',
'lastname' =>'required|max:20',
'email' =>'required|email|unique:users',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password',
'phone' =>'required|numeric|phone',
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048'
], [
'firstname.required' => ' The first name field is required.',
//'firstname.min' => ' The first name must be at least 5 characters.',
'firstname.max' => ' The first name may not be greater than 20 characters.',
'lastname.required' => ' The last name field is required.',
//'lastname.min' => ' The last name must be at least 5 characters.',
'lastname.max' => ' The last name may not be greater than 20 characters.',
]);
$customers = new Customer;
$customers->firstname = $request->input('firstname');
$customers->lastname = $request->input('lastname');
$customers->email = $request->input('email');
$customers->phone = $request->input('phone');
$customers->password = Hash::make($request->input('password'));
$customers->confirm_password = $request->input('confirm_password');
if($request->hasFile('image'))
{
$filename = $request->image->getClientOriginalName();
$request->image->storeAs('public/uploads',$filename);
}
$customers->image = $filename;
$customers->save();
return redirect()->action('CustomerController#index');
}
public function edit($id)
{
$customers = Customer::find($id);
return view('theme.customer_edit',compact('customers'));
}
public function update(Request $request, $id)
{
$this->validate($request,
[
'firstname' =>'required|max:20',
'lastname' =>'required|max:20',
'email' =>'required|email|unique:users',
'password' =>'required|min:3|max:20',
'confirm_password' =>'required|min:3|max:20|same:password',
'phone' =>'required|numeric|phone',
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048'
], [
'firstname.required' => ' The first name field is required.',
//'firstname.min' => ' The first name must be at least 5 characters.',
'firstname.max' => ' The first name may not be greater than 20 characters.',
'lastname.required' => ' The last name field is required.',
//'lastname.min' => ' The last name must be at least 5 characters.',
'lastname.max' => ' The last name may not be greater than 20 characters.',
]);
$customers = Customer::find($id);
$customers->firstname = $request->input('firstname');
$customers->lastname = $request->input('lastname');
$customers->email = $request->input('email');
$customers->phone = $request->input('phone');
$customers->password = $request->input('password');
$customers->confirm_password = $request->input('confirm_password');
if($request->hasFile('image'))
{
$filename = $request->image->getClientOriginalName();
$request->image->storeAs('public/uploads',$filename);
}
$customers->image = $filename;
$customers->save();
return redirect()->action('CustomerController#index');
}
public function delete($id)
{
Customer::find($id)->delete();
return redirect()->action('CustomerController#index');
}
public function search()
{
$name = Input::get('search');
if ($name != "")
{
$customers = Customer::where('firstname','Like','%' . $name . '%')
->orWhere('email','Like','%' . $name . '%')
->get();
return view('theme.customers_list',compact('customers'));
}
else
{
dd('no data found');
}
}
public function login()
{
return view('theme.login');
}
public function do_login(Request $request)
{
$email=$request->input('email');
$password = Hash::check($request->input('password'));
dd($password);exit();
$data=with(new Customer)->SignIn($email,$password);
$row=count($data);
if($row > 0){
echo "Login success";
}else{
echo "usename and password Mismatch!";
}
}
}
Now create customer_form.blade.php
#extends('theme.default')
#section('content')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Customer</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<!-- #if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif -->
<form role="form" action="<?php echo url('customer/add_record')?>" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="Firstname">
<span class="text-danger">{{ $errors->first('firstname') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('lastname') ? 'has-error' : '' }}">
<label for="lastname">Lastname</label>
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Lastname">
<span class="text-danger">{{ $errors->first('lastname') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="form-control" placeholder="Email">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('phone') ? 'has-error' : '' }}">
<label for="phone">Contact Number</label>
<input type="text" name="phone" id="phone" class="form-control" placeholder="Contact Number">
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Password">
<span class="text-danger">{{ $errors->first('password') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('confirm_password') ? 'has-error' : '' }}">
<label for="confirm_password">Confirm Password</label>
<input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm Password">
<span class="text-danger">{{ $errors->first('confirm_password') }}</span>
</div>
</div>
</div>
<div class="row">
<div class= "col-lg-6">
<div class="form-group">
<label>Image</label>
<input type="file" name="image" id="image">
</div>
</div>
<!-- <div class= "col-lg-6">
<div class="form-group">
<label>Text area</label>
<textarea class="form-control" rows="3"></textarea>
</div>
</div> -->
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
<!-- /.col-lg-6 (nested) -->
<!-- /.col-lg-6 (nested) -->
<!-- /.row (nested) -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#add_customer').validate({
rule: {
firstname: {
required: true,
}
},
messages: {
firstname: {
required:"firstname name cannot be blank."
}
},
});
});
</script>
#endsection
create list view customer_list.blade.php
#extends('theme.default')
#section('content')
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Users
<a class="pull-right btn btn-primary" href="<?php echo url('customer/add') ?>">Add Customer</a></h1>
</div>
<!-- /.col-lg-12 -->
</div>
<form action="<?php echo url('customer/index')?>" method="post">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="pull-right btn btn-primary" href="<?php echo url('customer/index') ?>">view all</button>
<div class="pull-right col-lg-3 input-group custom-search-form">
<input class="form-control" name="search" placeholder="Search..." type="text" value="{{ request('search') }}">
<span class="input-group-btn ">
<button class="btn btn-default" type="submit">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<input type="hidden" value="{{request('field')}}" name="field"/>
<input type="hidden" value="{{request('sort')}}" name="sort"/>
<!-- <button type="button" class="pull-right btn btn-primary">Add Customer</button> -->
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>Iamge</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=firstname&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
FirstName
</a>
{{request('field','firstname')=='firstname'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=lastname&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
LastName
</a>
{{request('field','lastname')=='lastname'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=email&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Email
</a>
{{request('field','email')=='email'?(request('sort','asc')=='asc'?'▴':'▾'):''}}</th>
</th>
<th>
<a href="{{url('customer/index')}}?search={{request('search')}}&field=phone&sort={{request('sort','asc')=='asc'?'desc':'asc'}}">
Phone Number
</a>
{{request('field','phone')=='phone'?(request('sort','asc')=='asc'?'▴':'▾'):''}}
</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody>
#php
$i=1;
#endphp
<?php foreach ($customers as $customer)
{
?>
<tr>
<td><?php echo $i++;?></td>
<td> <img height="50px" width="50px" class="user-pic" src="<?php echo asset("/storage/uploads/$customer->image")?>"></td>
<td><?php echo $customer->firstname;?></td>
<td><?php echo $customer->lastname;?></td>
<td><?php echo $customer->email;?></td>
<td><?php echo $customer->phone;?></td>
<td><a href ='edit/<?php echo $customer->id?>'>Edit</a></td>
<td><a href ='delete/<?php echo $customer->id?>'>Delete</a></td>
</tr>
<?php
}
?>
</tbody>
</table>
<nav>
<ul class="pagination justify-content-end pull-right">
{{$customers->links('vendor.pagination.bootstrap-4')}}
</ul>
</nav>
</form>
#endsection
create edit form customer_edit.blade.php
#extends('theme.default')
#section('content')
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script> -->
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Customer</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<!-- #if (count($errors) > 0)
<div class = "alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif -->
<form role="form" action="{{ url('customer/update', $customers->id)}}" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $customers->firstname;?>" class="form-control" placeholder="Firstname">
<span class="text-danger">{{ $errors->first('firstname') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('lastname') ? 'has-error' : '' }}">
<label for="lastname">Lastname</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $customers->lastname;?>" class="form-control" placeholder="Lastname">
<span class="text-danger">{{ $errors->first('lastname') }}</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('email') ? 'has-error' : '' }}">
<label for="email">Email</label>
<input type="text" name="email" id="email" value="<?php echo $customers->email;?>" class="form-control" placeholder="Email">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group {{ $errors->has('phone') ? 'has-error' : '' }}">
<label for="phone">Contact Number</label>
<input type="text" name="phone" id="phone" value="<?php echo $customers->phone;?>" class="form-control" placeholder="Contact Number">
<span class="text-danger">{{ $errors->first('phone') }}</span>
</div>
</div>
</div>
<div class="row">
<div class= "col-lg-6">
<div class="form-group">
<label>Image</label>
<div class="fileinput-preview thumbnail" id="profile" data-trigger="fileinput" style="width: 60px; height: 60px;">
<img height="90px" width="70px" class="user-pic" src="<?php echo asset("/storage/uploads/$customers->image")?>">
</div>
<input type="file" name="image" id="image">
</div>
</div>
<!-- <div class= "col-lg-6">
<div class="form-group">
<label>Text area</label>
<textarea class="form-control" rows="3"></textarea>
</div>
</div> -->
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
<!-- /.col-lg-6 (nested) -->
<!-- /.col-lg-6 (nested) -->
<!-- /.row (nested) -->
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection
create Model Customer.php
<?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function SignIn($email,$password)
{
$sql=DB::table('customers')->where('email',$email)->where('password',$password)->get();
return $sql;
}
}
create routing in web.php
Route::get('home/my-home', 'HomeController#myHome');
Route::get('customer/index', 'CustomerController#index');
Route::get('customer/add', 'CustomerController#add');
Route::post('customer/add_record', 'CustomerController#add_record');
Route::get('customer/edit/{id}', 'CustomerController#edit');
Route::post('customer/update/{id}', 'CustomerController#update');
Route::get('customer/delete/{id}','CustomerController#delete');
Route::post('customer/index','CustomerController#index');
Route::get('customer/login','CustomerController#login');
Route::post('customer/do_login','CustomerController#do_login');
for validation create function in AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
return substr($value, 0, 3) == '+91';
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
Create Routes
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/role', 'RoleController#index')->name('role');
Route::get('/create', 'RoleController#create')->name('role.create');
Route::post('/store', 'RoleController#store')->name('role.store');
Route::get('/edit/{id}', 'RoleController#edit')->name('role.edit');
Route::post('/update/{id}', 'RoleController#update')->name('role.update');
Route::any('/destroy/{id}', 'RoleController#destroy')->name('role.destroy');
Create Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Role;
use Validate;
use Collective\Html\FormFacade;
class RoleController extends Controller
{
public function index(){
$roles = Role::all();
return view('role.index',compact('roles'));
}
public function create(){
return view('role.create');
}
public function store(Request $request)
{
request()->validate([
'name' => 'required',
]);
Role::create($request->all());
return redirect()->route('role')
->with('success','Role created successfully');
}
public function edit($id){
$roles = Role::find($id);
return view('role.edit',compact('roles'));
}
public function update(Request $request, $id){
request()->validate([
'name' => 'required',
]);
Role::find($id)->update($request->all());
return redirect()->route('role')
->with('success','Role updated successfully');
}
public function destroy($id)
{
Role::find($id)->delete($id);
return redirect()->route('role')
->with('success','Role updated successfully');
}
}
Create Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $fillable = [ 'name' ];
}
create layoyt file in layouts folder
<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.5 CRUD Application</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
#yield('content')
</div>
</body>
</html>
create index.blade.php
#extends('layouts.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Role</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('role.create') }}"> Create New role</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th width="280">Action</th>
</tr>
#foreach ($roles as $role)
<tr>
<td>{{ $role->id }}</td>
<td>{{ $role->name}}</td>
<td>
<a class="btn btn-primary" href="{{ route('role.edit',$role->id) }}">Edit</a>
<form action="{{ route('role.destroy', $role->id) }}" method="DELETE">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
<!-- <button class="deleteRecord" data-id="{{ $role->id }}" >Delete Record</button> -->
</td>
</tr>
#endforeach
</table>
#endsection
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$(".deleteRecord").click(function(){
var id = $(this).data("id");
//var token = $("meta[name='csrf-token']").attr("content");
$.ajax(
{
url: "destroy/"+id,
type: 'Post',
data: { "id": id, "_token": "{{ csrf_token() }}",},
dataType: "JSON",
success: function (){
console.log("it Works");
}
});
});
});
</script>
Create create.blade.php
#extends('layouts.layout')
#section('content')
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Role</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form role="form" action="{{ route('role.store') }}" id="add_customer" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Name">
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
</div>
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection
Create edit.blade.php
#extends('layouts.layout')
#section('content')
<div id="">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Role</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<form role="form" action="{{ route('role.update',$roles->id) }}" id="update_role" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row">
<div class="col-lg-6">
<div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" value="<?php echo $roles->name ?>" placeholder="Name">
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
</div>
</div>
<button type="submit" valur="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
#endsection
I am using Rivets to bind my form data. Is there any way to bind my input type file with the help rivet binders.
Like in this example https://jsfiddle.net/steinbring/v29vnLuh/ You can see that we bind text area . But how will we bind over input file .
Let me explain more
here is my form
<form class="product-inputs full-width-inputs" method="post" action="/create/save-manual-products-shopify">
<section id="rivettest">
<ul class="no-bullet">
<li class="product-input-header">
<div class="row no-padding">
<div class="small-2 columns">
<p>Product Name</p>
</div>
<div class="small-2 columns">
<p>Product Detail</p>
</div>
<div class="small-2 columns">
<p>Product Type</p>
</div>
<div class="small-2 columns">
<p>Price</p>
</div>
<div class="small-2 columns floatleft">
<p>Sku</p>
</div>
<div class="small-2 columns floatleft">
<p>Image</p>
</div>
</div>
</li>
<li class="product-input" rv-each-product="products">
<div class="row no-padding">
<div class="small-2 columns" style="position: relative">
<input class="product-name-input" type="text" rv-value="product.name" placeholder="New Product"/>
<span class="icon-error remove-btn" rv-on-click="controller.removeItem"></span>
</div>
<div class="small-2 columns">
<input type="text" rv-value="product.product_detail"/>
</div>
<div class="small-2 columns">
<input type="text" rv-value="product.product_type"/>
</div>
<div class="small-2 columns">
<input type="text" rv-value="product.price">
</div>
<div class="small-2 columns">
<input type="text" rv-value="product.sku">
</div>
<div class="small-2 columns">
<input type="file" rv-value="product.image">
<!-- <input type="file"> -->
<!-- <span class="icon-upload"></span> Upload Image -->
</div>
</div>
</li>
<li class="additem">
<span class="icon-plus"></span>Add Product Manually
</li>
</ul>
</section>
<input type="submit" value="Submit for KF Approval" class="button radius add-product-shopify" >
</form>
And here is my script
var products = [];
var controller = {
addItem: function(e, model) {
model.products.push({name: "New Product", product_detail: "", product_type: "", price: null, sku: null, image: ""});
e.preventDefault();
return false;
},
removeItem: function(e, model) {
var index = model.index;
if (index > -1) {
products.splice(index, 1);
}
},
};
rivets.bind($('#rivettest'), {products: products, controller: controller});
But when i submit my form i got this response
image: ""
name: "a"
price: "12"
product_detail: "b"
product_type: "c"
sku: "12"
Here you see that image param is empty ... please help me .Thanks
Here's a working example written in coffescript
controller = (el, data) ->
that = this
#email_valid = false
#update = ->
if #type == "file"
data[#id] = #files[0]
else
data[#id] = #value
#submit = ->
_data = new FormData()
Object.keys(data).forEach( (key) ->
_data.append(key, data[key])
)
req = new XMLHttpRequest()
req.open('POST', 'addUser', true)
req.onreadystatechange = (aEvt) ->
if req.readyState == 4
if req.status == 200
return req.responseText
else
return "Erreur pendant le chargement de la page.\n"
req.send(_data)
#email_validate = ->
re = /\S+#\S+\.\S+/
return re.test data.email
return this
rivets.components['user'] = {
# Return the template for the component.
template: ->
return tpl
# Takes the original element and the data that was passed into the
# component (either from rivets.init or the attributes on the component
# element in the template).
initialize: (el, data) ->
return new controller(el, data)
}
the form
<form enctype="multipart/form-data" class="form-horizontal" id="userForm">
<fieldset>
<!-- Form Name -->
<legend>Form Name</legend>
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="picture">Photo</label>
<div class="col-md-4">
<input rv-value="picture" rv-on-change="update" id="picture" name="picture" class="input-file" type="file">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Name</label>
<div class="col-md-4">
<input rv-value="name" id="name" rv-on-input="update" name="name" type="text" placeholder="Name" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="password">Password</label>
<div class="col-md-4">
<input rv-value="password" id="password" rv-on-input="update" name="password" type="text" placeholder="Password" class="form-control input-md">
</div>
</div>
<!-- Password input-->
<div class="form-group">
<label class="col-md-4 control-label" for="password-validate">Password Validate</label>
<div class="col-md-4">
<input rv-value="password-validate" rv-on-input="update" id="password-validate" name="password-validate" type="password" placeholder="Password" class="form-control input-md">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="save">Save</label>
<div class="col-md-4">
<button type="button" rv-on-click="submit" id="save" name="save" class="btn btn-primary">Save</button>
</div>
</div>
</fieldset>
</form>
and the server side
multipart = require('connect-multiparty');
multipartMiddleware = multipart();
app.post '/addUser', multipartMiddleware, (req, resp) ->
console.log(req.body, req.files)
You need to set your form to allow file upload using the enctype attribute.
<form enctype="multipart/form-data">
You can try to bind an onchange event to the file input:
<input type="file" rv-on-change="update" rv-value="product.image">
and create an update method in your controller that update the product.image value with the value of form.
this.update = function(){
model[this.id] = this.value
}