gallery images does not get updated in database - laravel

I have an event management company website. https://redcarpetevents.in. the only issue is i cannot update the image gallery. i can upload new images, that works fine. but when i edit the images already in the database, it is not getting updated.
routes.php
Route::get('admin/editGalleryForm/{type}/{editId}', array('as'=>'editGalleryForm','before'=>'authAdmin','uses'=>'AdminController#editGalleryForm'));
Route::post('admin/editGallery', array('as'=>'editGallery','before'=>'csrf|xss_clean|authAdmin','uses'=>'FormController#editGallery'));
Model.php
public static function editGallery($data){
$gallery = Gallery::find($data['editId']);
$gallery->type = $data['type'];
$gallery->tag = $data['tag'];
$gallery->position = $data['order'];
if (isset($data['status'])) {
$gallery->status = $data['status'];
}else{
$gallery->status = 'off';
}
if (isset($data['home'])) {
$gallery->home = $data['home'];
}else{
$gallery->home = 'off';
}
if (isset($data['title'])) {
$gallery->title = $data['title'];
}
if($gallery->update()){
return true;
}else{
return false;
}
}
public static function getGalleryCounts(){
$galleryCounts = array();
$galleryCounts['all'] = count(Gallery::all());
$galleryCounts['allActive'] = count(Gallery::where('status','=','on')->get());
$galleryCounts['allInActive'] = count(Gallery::where('status','=','off')->get());
$galleryCounts['personal'] = count(Gallery::where('type','=','1')->get());
$galleryCounts['personalActive'] = count(Gallery::where('type','=','1')->where('status','=','on')->get());
$galleryCounts['personalInActive'] = count(Gallery::where('type','=','1')->where('status','=','off')->get());
$galleryCounts['corporate'] = count(Gallery::where('type','=','2')->get());
$galleryCounts['corporateActive'] = count(Gallery::where('type','=','2')->where('status','=','on')->get());
$galleryCounts['corporateInActive'] = count(Gallery::where('type','=','2')->where('status','=','off')->get());
return $galleryCounts;
}
Admincontroller.php
public function editGalleryForm($type,$id){
$data['id'] = $id;
$data['type'] = $type;
$data['galleryCounts'] = Gallery::getGalleryCounts();
$data['image'] = Gallery::getGalleryById($id);
$data['personalTags'] = GalleryTag::getPersonalActive();
$data['corporateTags'] = GalleryTag::getCorporateActive();
return View::make('admin.editGalleryForm', $data);
}
Formcontroller.php
public function editGallery(){
$type = Input::get('type');
$editId = Input::get('Id');
$filename=Input::get('image');
$rules = array(
'order'=>'Numeric');
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
$data['type'] = $type;
$data['Id'] = $editId;
return Redirect::route('editGalleryForm',$data)->withInput()->withErrors($validation);
}
if ($validation->passes()) {
$fileName='';
if (Input::hasFile('image')) {
$name = Input::file('image')->getClientOriginalName();
$destinationPath = 'assets/img/gallery/';
$data['Id'] = $Id;
$fileName = $name;
Input::file('image')->move($destinationPath, $fileName);
//Gallery::convertImage($destinationPath,$fileName);
}
$editGallery = Gallery::editGallery(Input::all());
if ($editGallery) {
$data['success'] = 'Gallery Image Updated!';
$data['type'] = $type;
return Redirect::route('newGallery',$data);
}
else
{
$data['failure'] = 'Operation failed!';
$data['type'] = $type;
return Redirect::route('newGallery',$data);
}
}
}
this is the form
#extends('admin.layouts.master')
#section('pageHeader')
<h2>Edit Gallery Image</h2>
<ol class="breadcrumb">
<li>{{HTML::linkRoute('adminHome','Dashboard')}}</li>
<li>{{HTML::linkRoute('newGallery','Gallery',array('type'=>$type))}}</li>
<li class="active">Edit Gallery Image</li>
</ol>
#stop
#section('content')
<div class="cl-mcont">
<div class="status_bar">
<div class="butpro butstyle {{($type=='1')? 'status_active':''}}"><a href="{{URL::route('newGallery',array('type'=>'1'))}}">
<div class="sub"><h2>PERSONAL</h2><span id="total_clientes">{{$galleryCounts['personal']}} Image{{($galleryCounts['personal'] > 1)? 's':''}}</span></div>
<div class="stat">{{$galleryCounts['personalActive']}} <i style="color:#00FF00" class="fa fa-check"></i> {{$galleryCounts['personalInActive']}} <i style="color:#FF0000" class="fa fa-times"></i></div>
</a></div>
<div class="butpro butstyle {{($type=='2')? 'status_active':''}}"><a href="{{URL::route('newGallery',array('type'=>'2'))}}">
<div class="sub"><h2>CORPORATE</h2><span id="total_clientes">{{$galleryCounts['corporate']}} Image{{($galleryCounts['corporate'] > 1)? 's':''}}</span></div>
<div class="stat">{{$galleryCounts['corporateActive']}} <i style="color:#00FF00" class="fa fa-check"></i> {{$galleryCounts['corporateInActive']}} <i style="color:#FF0000" class="fa fa-times"></i></div>
</a></div>
</div>
<div class="row">
<div class="col-md-12">
{{Form::open(array('action'=>'editGallery','method'=>'POST','files'=>true,'class'=>'form-horizontal'))}}
<div class="form-group">
{{Form::label('forType', 'Type', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::select('type', array('1'=>'personal','2'=>'corporate'), ($image->type=='2')? '2':'1', array('class'=>'form-control','onChange'=>'tagChange(this)'))}}
<div class="color-danger">{{$errors->first('type')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forTag', 'Tag', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<select class="form-control" id="tags" name="tag">
#if($type == 2)
#foreach($corporateTags as $tag)
<option {{($image->tag == $tag->id)? 'selected':''}} value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
#else
#foreach($personalTags as $tag)
<option {{($image->tag == $tag->id)? 'selected':''}} value="{{$tag->id}}">{{$tag->name}}</option>
#endforeach
#endif
</select>
<div class="color-danger">{{$errors->first('tag')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forTitle', 'Title', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::text('title', $image->title, array('class'=>'form-control','placeholder'=>'Image Title'))}}
<div class="color-danger">{{$errors->first('title')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forImage', 'Gallery Image', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::file('forimage', array('class'=>'form-control','placeholder'=>'image'))}} (600 X 400)px
<div class="color-danger">{{$errors->first('image')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('', '', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="col-md-2 padding photo">
<img src="{{asset('assets/img/gallery/'.$image->image)}}" width="200px" height="120px">
</div>
</div>
</div>
<div class="form-group">
{{Form::label('forOrder', 'Order', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
{{Form::text('order', $image->position, array('class'=>'form-control','placeholder'=>'Image Order'))}}
<div class="color-danger">{{$errors->first('order')}}</div>
</div>
</div>
<div class="form-group">
{{Form::label('forStatus', 'Publish Status', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="switch" data-on="success">
<input type="checkbox" name="status"{{($image->status=='on')? 'checked':''}}>
</div>
</div>
</div>
<div class="form-group">
{{Form::label('forShow', 'Show on Homepage', array('class'=>'col-sm-2 control-label'))}}
<div class="col-sm-6">
<div class="switch" data-on="success">
<input type="checkbox" name="home"{{($image->home=='on')? 'checked':''}}>
</div>
</div>
</div>
{{Form::text('editId', $image->id, array('style'=>'display:none'))}}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
{{Form::submit('Update Gallery', array('class'=>'btn btn-primary'))}}
{{HTML::linkRoute('newGallery','Cancel',array('type'=>$type),array('class'=>'btn btn-default'))}}
</div>
</div>
{{Form::token().Form::close()}}
</div>
</div>
</div>
#stop
#section('customScripts')
<script type="text/javascript">
function tagChange(element){
console.log(element.value);
$('#tags').empty();
$.ajax({
url:'{{URL::route("getTagsAjax")}}',
type:'POST',
data:{'type':element.value},
dataType:'JSON',
success:function(data){
console.log(data);
for (var i = 0; i <= data.length; i++) {
$('#tags').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
};
}
});
}
</script>
#stop

Related

laravel blade - show only one data from database

I have a table with multiple fields called "skills" . how do I show only one(first) data associated with "skills" .
#foreach ($others as $other )
#if ($other->type == 'skills')
<div class="col-md-6 p-0">
<img src="{{$other->photoOrVideo}}" class="imgbg-col" alt="imghome">
</div>
<div class="col-md-6 centered">
<div class="detailcontent">
<div class="subheading">{{$other->type}}</div>
<div class="heading">{{$other->titleOrName}}</div>
<div class="textdetail">{{$other->description}}</div>
</div>
</div>
#endif
#endforeach
in my controller-
public function index()
{
$sliders = Slider::latest()->with('service')->get();
$clients = OurClient::all();
$galleries = Gallery::all();
$services = Service::all();
$others = Others::all();
return view('frontend.pages.home',compact('services','galleries','clients','others','sliders'));
}
this is showing the same data twice. I want only the first data
I solved it. changed the blade file
<div class="row">
<?php $count = 0; ?>
#foreach ($others as $other )
#if ($other->type == 'skills')
<?php if($count == 1) break; ?>
<div class="col-md-6 p-0">
<img src="{{$other->photoOrVideo}}" class="imgbg-col" alt="imghome">
</div>
<div class="col-md-6 centered">
<div class="detailcontent">
<div class="subheading">{{$other->type}}</div>
<div class="heading">{{$other->titleOrName}}</div>
<div class="textdetail">{{$other->description}}</div>
</div>
</div>
<?php $count++; ?>
#endif
#endforeach
</div>

Last input added to a form in Laravel not inserting to database

I bought a ready made Laravel Tailor application, I am trying to add an additional input to it but after doing so, I tried to submit it to the database but the last one I added wasn't inserting. The input is in array.
All other values are inserting except for service_description[] which is newly added to the form.
What exactly could I be doing wrong?
Database Structure
HTML Codes:
#extends('admin.layouts.master')
#section('content')
<style type="text/css">
</style>
#if(Session::has('success'))
<div class="alert alert-success" role= "alert">
<strong>Successful:</strong>
{!! session('success') !!}
</div>
#endif
#if (count($errors) > 0)
<div class="row">
<div class="col-md-06">
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Alert!</h4>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</div>
</div>
</div>
#endif
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<i class="icon-equalizer font-red-sunglo"></i>
<span class="caption-subject font-red-sunglo bold uppercase">Order Submission</span>
<span class="caption-helper">Service Details</span>
</div>
<div class="tools">
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="{{url('admin/save-order')}}" class="form-horizontal" method="POST">
<input name="order_create_by" type="hidden" value="{{ Auth::user()->id }}">
<div class="form-body">
{{ csrf_field() }}
<h3 class="form-section">Customer Info</h3>
<!--Start Customer Area-->
<div class="row">
<div class="col-md-6">
<!-- text input -->
<div class="form-group">
<label class="control-label col-md-4">Customer Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" placeholder="Enter ..." name="service_cus_name" id="service_cus_name">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4">Email Address:</label>
<div class="col-md-8">
<input type="email" class="form-control" placeholder="Enter ..." name="service_cus_email" id="service_cus_email">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4">Order Create Date:</label>
<div class="col-md-8">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right createdpicker" name="service_crete_date" id="service_crete_date">
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-4">Cell Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" placeholder="Enter ..." name="cell_number" id="cell_number">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4">Order Delivery Date:</label>
<div class="col-md-8">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right dpicker" name="service_delivery_date" id="service_delivery_date">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label col-md-2">Cutomer Address:</label>
<div class="col-md-10">
<textarea class="form-control" rows="3" placeholder="Enter ..." name="service_cus_address" id="service_cus_address"></textarea>
</div>
</div>
</div>
</div>
<!--End Customer Area-->
<!--Start Service Order Area-->
<div class="form-section">
<h3 class="inlineBlock">Service Details with Measurement</h3>
<button type="button" class="btn dark flot-right " id="addService" disabled="disabled"> Add Another Service </button>
</div>
<div class="row">
<div class="col-md-3">
<div class="col-md-11">
<label>Select Service</label>
</div>
</div>
<div class="col-md-2">
<div class="col-md-10">
<label>Rate:</label>
</div>
</div>
<div class="col-md-2">
<div class="col-md-10">
<label>Quantity:</label>
</div>
</div>
<div class="col-md-2">
<div class="col-md-10">
<label>Amount:</label>
</div>
</div>
<div class="col-md-3">
<div class="col-md-10">
<label>Action</label>
</div>
</div>
</div>
<div class="row serviceRow redBorder" id="orderBox">
<div class="col-md-3">
<div class="form-group">
<div class="col-md-11">
<select class="form-control service_id" name="service_id[]" id="service_id">
<option selected="selected" disabled="disabled" value="0">Select Service</option>
#foreach($services as $service)
<option value="{{$service->id}}">{{$service->service_name}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<div class="col-md-10">
<input type="text" class="form-control service_price" placeholder="Rate" name="service_price[]" id="service_price" readonly>
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<div class="col-md-10">
<input type="text" class="form-control service_qty" placeholder="Quantity" id="service_qty" name="service_quantity[]">
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<div class="col-md-10">
<input type="text" class="form-control amount" placeholder="Total" id="amount" name="service_amount[]" readonly>
</div> </div>
</div>
<div class="col-md-3">
<div class="form-group">
<div class="col-md-10">
<button type="button" class="btn removeService red btn-block" id="removeService" disabled="disabled"> Delete</button>
</div>
</div>
</div>
<div class="row pading-margin-zero">
<div class="col-md-12 col-md-offset-1">
<div class="form-group">
<div class="col-md-5" >
<textarea type="text" class="form-control service_measer" placeholder="Enter Measurement of Service ..." name="service_measer[]"></textarea>
</div>
<div class="col-md-5" >
<textarea type="text" class="form-control description service_description" placeholder="Description(s)" name="service_description[]" id="description"></textarea>
</div>
</div>
</div>
</div>
</div>
<!--End Service Order Area-->
</div>
<!--Start Form Footer Area-->
<div class="form-action">
<div class="row">
<div class="col-md-3">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-success">Total Amount</button>
</div>
<!-- /btn-group -->
<input type="text" class="form-control" id="total" name="total_amount" style="font-size:25px; font-weight: bold">
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-info">Discount Amount</button>
</div>
<!-- /btn-group -->
<input type="text" class="form-control" id="discount" name="discount_amount" style="font-size:25px; font-weight: bold">
</div>
</div>
<div class="col-md-3">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-warning">Advance Amount</button>
</div>
<!-- /btn-group -->
<input type="text" class="form-control" id="advance_amount" name="advance_amount" style="font-size:25px; font-weight: bold">
</div>
</div>
<div class="col-md-3">
<button type="submit" class="btn purple btn-block">Submit Order</button>
</div>
</div>
</div>
<!--End Form Footer Area-->
</form>
</div>
<script>
jQuery(document).ready(function() {
//Commom Script
$('.dpicker').datepicker({
autoclose: true
})
var currentDate = new Date();
$(".createdpicker").datepicker("setDate",currentDate);
$("#loader").css("display",'none');
$("#myDiv").removeAttr("style");
$("#addService").removeAttr("disabled");
//Start Order Form
$('form').submit(function() {
if ($.trim($("#service_cus_name").val()) === "") {
alert('Customer Name Field Empty');
return false;
}else if( $.trim($("#service_cus_email").val()) === ""){
alert('Email Address Field Empty');
return false;
}else if( $.trim($("#cell_number").val()) === ""){
alert('Cell Number Field Empty');
return false;
}else if( $.trim($("#service_crete_date").val()) === ""){
alert('Create Date Field Empty');
return false;
}else if( $.trim($("#service_delivery_date").val()) === ""){
alert('Delivery Date Field Empty');
return false;
}else if( $.trim($("#service_cus_address").val()) === ""){
alert('Customer Address Field Empty');
return false;
}
var flag = 0;
$(".service_qty").each(function(i){
if ($(this).val() == "")
flag++;
});
if(flag==0){
flagNew=0
$(".service_measer").each(function(i){
if ($(this).val() == "")
flagNew++;
});
if(flagNew==0){
return true;
}else{
alert("All Measurement Fileds Requried");
return false;
}
}else{
alert("All Service Quantity Fileds Requried");
return false;
}
});
$("#addService").click(function(){
//
//alert('addButton');
var serviceRowQty = $('.serviceRow').length;
//alert(serviceRowQty);
$("#orderBox:last").clone(true).insertAfter("div.serviceRow:last");
$("div.serviceRow:last input").val('');
$("div.serviceRow:last textarea").val('');
$("div.serviceRow:last select").prop('selectedIndex',0);
$("div.serviceRow:last label").text('');
$("div.serviceRow .removeService").prop('disabled', false);
return false;
})
$(document).on("click" , "#removeService" , function() {
//alert('deletebutton');
var serviceRowQty = $('.serviceRow').length;
if (serviceRowQty == 1){
$("div.serviceRow .removeService").prop('disabled', true);
return false;
$(".serviceRow").css("display", "block");
}else{
$(this).closest('.serviceRow').remove();
if(serviceRowQty==1){
//return false;
$("div.serviceRow .removeService").prop('disabled', true);
return false
}else{
$("div.serviceRow .removeService").prop('disabled', false);
}
//$(".serviceRow").remove();
return false;
}
alert();
return false;
});
$('.serviceRow').delegate('.service_id','change',function(){
;
var subdiv = $(this).parent().parent().parent().parent();
var cat_id = $(this).closest('.serviceRow').find('.service_id option:selected').attr('value');
subdiv.find('.service_price').val('');
//alert(cat_id);
//var a =
//alert(totalamount());
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type : 'get',
url : 'get-orders-list-jason/'+cat_id+'',
dataType : 'json',
//date : { cat_id: cat_id},
success:function(data){
console.log(data);
subdiv.find('.service_price').val(data.service_price);
var price = subdiv.find('.service_price').val();
var qty = subdiv.find('.service_qty').val();
var total = data.service_price * qty ;
subdiv.find('.amount').val(total);
$('#total').val(totalamount());
//alert(alert(JSON.stringify(subdiv)));
},
error: function(error) {
//alert("Data retrive faield");
}
});
$(".serviceRow").delegate('.service_qty', "keyup",function(){
//alert('keyup');
var subdiv = $(this).parent().parent().parent().parent();
var price = subdiv.find('.service_price').val();
var qty = subdiv.find('.service_qty').val();
var discount = $('#discount').val();
var total = price * qty ;
subdiv.find('.amount').val(total);
$('#total').val(totalamount());
//alert('background-color');
//$("p").css("background-color", "pink");
});
$("#discount").keyup(function(){
$('#total').val(totalamount());
});
function totalamount(t){
var t=0;
$('.amount').each(function(i,e){
var amt = $(this).val()-0;
t+=amt;
});
var d = $('#discount').val();
total = t-d;
return total;
$('.total').html(t);
}
});
$('.serviceRow').each(function() {
$(this).find('select').change(function(){//alert($(this).val())
if( $('.serviceRow').find('select option[value='+$(this).val()+']:selected').length>1){
$(this).val($(this).css("border","1px red solid"));
alert('option is already selected');
$(this).val($(this).find("option:first").val());
}else{
$(this).css("border","1px #D2D6DE solid");
}
});
});
});
</script>
#endsection
Order Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Service;
use Validator;
use Illuminate\Support\Facades\Input;
use App\lib\Custom;
use App\lib\DBQuery;
use App\Order;
use DB;
use App\Orderdetail;
use App\Session;
use App\ShopInfo;
use App\Payment;
use Auth;
class OrderController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function getOrders(){
$orders = Order::All();
//return $orders;
return view('order.allorderlist',compact('orders'));
}
public function getOrderajax($cat_id)
{
$orders = Service::where('id',$cat_id)->first();
return $orders;
}
public function addOrder()
{
$services = Service::where('active_status',0)->get();
return view('order.addneworder',compact('services'));
}
public function saveOrder(Request $request)
{
if($request->discount_amount==""){
$validator = Validator::make(Input::all(), Order::$rules);
$request['discount_amount']=0;
}else{
$validator = Validator::make(Input::all(), Order::$numberrules);
}
if($validator->fails()){
$services = Service::where('active_status',0)->get();
return view('order.addneworder',compact('services'))->withErrors($validator);
}else{
$order = DBQuery::saveOrder($request);
//return $order;
$shopinfo = ShopInfo::find(1);
$total_bill_word = Custom::convert_number_to_words($number = $order->total_amount);
return view('report.invsaveprint',compact('order','shopinfo','total_bill_word'));
}
}
public function addOrderExCustomer($order_id)
{ $order = Order::where('id',$order_id)->first();
$services = Service::where('active_status',0)->get();
return view('order.addneworderexcus',compact('services','order'));
}
public function saveOrderExCustomer(Request $request)
{
$validator = Validator::make(Input::all(), Order::$rules);
if($validator->fails()){
$services = Service::where('active_status',0)->get();
$order = Order::where('id',$request->order_id)->first();
return view('order.addneworderexcus',compact('services','order'))->withErrors($validator);
}else{
$order = DBQuery::saveOrder($request);
$shopinfo = ShopInfo::find(1);
$total_bill_word = Custom::convert_number_to_words($number = $order->total_amount);
return view('report.invupdateprint',compact('order','shopinfo','total_bill_word'));
}
}
public function updateOrderById($order_id){
$order = Order::where('id',$order_id)->first();
$services = Service::All();
return view('order.editOrder',compact('services','order'));
}
public function saveUpdateOrderById(Request $request){
$validator = Validator::make(Input::all(), Order::$rules);
if($validator->fails()){
$services = Service::where('active_status',0)->get();
$order = Order::where('id', '=', $request->order_id)->first();
//return $order;
return view('order.editOrder',compact('services','order'))->withErrors($validator);
}else{
DBQuery::saveUpdateOrder($request);
$order = Order::where('id', '=', $request->order_id)->first();
//return $order ;
$shopinfo = ShopInfo::find(1);
$total_bill_word = Custom::convert_number_to_words($number = $order->total_amount);
return view('report.newinvoice',compact('order','shopinfo','total_bill_word'));
}
}
public function deliveryOrderById($order_id){
$order = Order::where('id',$order_id)->first();
//return $order;
$services = Service::All();
return view('order.deliveryorder',compact('services','order'));
}
public function saveDeliveryOrderById($order_id){
//$a = Auth::user()->is_permission;
//return $order_id;
//if(Auth::user()->is_permission==1){
Order::where('id',$order_id)
->update(array('service_status' => 3));
// }
$order = Order::where('id',$order_id)->first();
return view('order.deliveryorder',compact('order'));
}
}
**The order codes**
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $table = "orders";
protected $fillable = [
'service_ref',
'service_status',
'order_create_by',
'service_crete_date',
'service_delivery_date',
'service_cus_name',
'cell_number',
'service_cus_email',
'service_cus_address',
'total_amount',
'discount_amount',
];
public static $numberrules = array(
'service_cus_name' =>'required',
'service_cus_address' =>'required',
'service_cus_email' =>'required',
'service_crete_date' =>'required',
'service_delivery_date' =>'required',
'total_amount' =>'required',
'discount_amount' =>'numeric|',
'cell_number' =>'required|numeric',
'service_quantity.*' =>'required|numeric',
'service_id.*' =>'required',
'service_measer.*' =>'required',
'service_description.*' =>'required',
);
public static $rules = array(
'service_cus_name' =>'required',
'service_cus_address' =>'required',
'service_cus_email' =>'required',
'cell_number' =>'required|numeric',
'service_crete_date' =>'required',
'service_delivery_date' =>'required',
'total_amount' =>'required',
'service_quantity.*' =>'required|numeric',
'service_id.*' =>'required',
'service_measer.*' =>'required',
'service_description.*' =>'required',
);
public function orderdetails() {
//return $this->hasMany('App\OrderDetail','fid','id');
return $this->hasMany('App\Orderdetail','order_id','id');
}
public function user() {
//return $this->hasMany('App\OrderDetail','fid','id');
return $this->hasOne('App\User','id','ser_act_create_by');
}
public function payments() {
return $this->hasMany('App\Payment','order_id','id');
//return $this->>belongsTo('App\Order');
}
}
Order Details Code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Orderdetail extends Model
{
protected $table = "orderdetails";
protected $fillable = [
'order_id',
'service_id',
'service_price',
'service_quantity',
'service_amount',
'service_measer',
'service_description',
'service_id',
];
public function order() {
return $this->belongsTo('App\Order');
//return $this->>belongsTo('App\Order');
}
public function service() {
return $this->belongsTo('App\Service','service_id','id');
//return $this->>belongsTo('App\Order');
}
}

Validating forms on laravel

Hi i getting this error When I try to validate a form, with this
$this->validate($request, [
'documento' => 'required|unique:cliente|max:55',
]);
htmlentities() expects parameter 1 to be string, array given (View: C:\sisVentas\resources\views\ventas\cliente\create.blade.php)
this is my view please help.
#extends ('layouts.admin')
#section ('contenido')
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<h3>Nuevo Cliente</h3>
#if (count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
</div>
{!!Form::open(array('url'=>'ventas/cliente','method'=>'POST','autocomplete'=>'off', 'files'=>'true'))!!}
{{Form::token()}}
<div class="row">
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<label for="empresa">Empresa</label>
<input type="text" name="empresa" value="{{old('empresa')}}" class="form-control"
placeholder="Empresa...">
</div>
</div>
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<label for="contacto">Direccion</label>
<input type="text" name="direccion" value="{{old('direccion')}}" class="form-control"
placeholder="Direccion...">
</div>
</div>
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<label>Tipo Documento</label>
<select name="tipo_documento" class="form-control">
<option value="J">J</option>
<option value="G">G</option>
<option value="V">V</option>
<option value="E">E</option>
</select>
</div>
</div>
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<label for="Numero de documento">Numero de Documento</label>
<input type="text" name="documento" id="documento" required value="{{old('documento')}}"
onkeypress='return event.charCode >= 48 && event.charCode <= 57' class="form-control"
placeholder="Numero de Documento...">
</div>
</div>
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<label for="razon_social">Razon Social</label>
<input type="text" name="razon_social" value="{{old('razon_social')}}" class="form-control"
placeholder="Razon social...">
</div>
</div>
</div>
<div class="row">
<div class="panel panel-primary">
<div class="panel-body">
<div class="col-lg-2 col-sm-2 col-md-2 col-xs-12">
<div class="form-group">
<label for="nombre">Nombre</label>
<input type="text" name="pnombre" id="pnombre" class="form-control" placeholder="Nombre...">
</div>
</div>
<div class="col-lg-5 col-sm-5 col-md-5 col-xs-12">
<div class="form-group">
<label for="telefonos">Telefonos</label>
<input type="text" name="ptelefono" id="ptelefono" class="form-control"
value="{{old('precio')}}" placeholder="Telefonos...">
</div>
</div>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="correo">Correo</label>
<input type="text" name="pcorreo" id="pcorreo" class="form-control"
value="{{old('correo')}}" placeholder="correo...">
</div>
</div>
<div class="col-lg-2 col-sm-2 col-md-2 col-xs-12">
<div class="form-group">
<button type="button" id="bt_add" class="btn btn-primary">Agregar</button>
</div>
</div>
<div class="col-lg-8 col-sm-8 col-md-8 col-xs-12">
<table id="detalles" class="table table-striped table-bordered table-condensed">
<thead style="background-color: #ccc">
<th>Opciones</th>
<th>Nombre</th>
<th>Contacto</th>
<th>Correo</th>
</thead>
<tfoot>
<th></th>
<th></th>
<th></th>
<th></th>
</tfoot>
<tbody>
</tbody>
</table>
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<button class="btn btn-primary" id="guardar" type="submit">Guardar</button>
<button class="btn btn-danger" type="reset">Cancelar</button>
</div>
</div>
</div>
{!!Form::close() !!}
#push ('scripts') <!-- Trabajar con el script definido en el layout-->
<script>
//////////
$('#guardar').hide();
$(document).ready(function () {
$('#bt_add').click(function () {
agregar();
});
});
var cont = 0;
var total = 0;
subtotal = [];
function agregar() {
nombre = $('#pnombre').val();
telefono = $('#ptelefono').val();
correo = $('#pcorreo').val();
if (nombre != "" && telefono != "") {
total = total + subtotal[cont];
var fila = '<tr class="selected" id="fila' + cont + '"><td><button type="button" class="btn btn-warning" onclick="eliminar(' + cont + ')" >X</button></td><td><input type="text" name="nombre[]" value="' + nombre + '"</td><td><input type="text" name="telefono[]" value="' + telefono + '"</td><td><input type="text" name="correo[]" value="' + correo + '"</td></tr>';
cont++;
limpiar();
$('#detalles').append(fila);
$('#guardar').show();
} else {
alert("Error al ingresar los detalles del contacto, revise los datos del contacto ");
}
}
function limpiar() {
$('#pnombre').val("");
$('#ptelefono').val("");
$('#pcorreo').val("");
}
function eliminar(index) {
$("#fila" + index).remove();
evaluar();
}
</script>
#endpush
#endsection
and this is my controller
<?php
namespace sisVentas\Http\Controllers;
use Illuminate\Http\Request;
use sisVentas\Http\Requests;
use sisVentas\Persona;
use sisVentas\Contacto;
use Response;
use sisVentas\Evento;
use Carbon\Carbon;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use sisVentas\Http\Requests\PersonaFormRequest;
use DB;
class ClienteController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
if ($request)
{
$query=trim($request->get('searchText'));
$clientes=DB::table('cliente')
->where ('empresa','LIKE','%'.$query.'%')
->orwhere ('tipo_documento','LIKE','%'.$query.'%')
->orwhere ('documento','LIKE','%'.$query.'%')
->orwhere ('direccion','LIKE','%'.$query.'%')
->orwhere ('razon_social','LIKE','%'.$query.'%')
->orderBy('codigo_cliente','desc')
->paginate(7);
return view('ventas.cliente.index',["clientes"=>$clientes,"searchText"=>$query]);
}
}
public function create()
{
return view("ventas.cliente.create");
}
public function store (Request $request)
{
$this->validate($request, [
'documento' => 'required|unique:cliente|max:55',
]);
try {
DB::beginTransaction();
$persona=new Persona;
$persona->tipo_documento=$request->get('tipo_documento');
$persona->documento=$request->get('documento');
$persona->empresa=$request->get('empresa');
$persona->direccion=$request->get('direccion');
$persona->razon_social=$request->get('razon_social');
$persona->save();
$id = $persona->codigo_cliente;
$evento=new Evento;
$user = Auth::id();
$evento->cod_usuario=$user;
$evento->tabla='Cliente';
$evento->accion='Nuevo Ingreso';
$evento->codigo_referencia=$id;
$mytime = Carbon::now(' America/Caracas');
$evento->fecha =$mytime->toDateTimeString();
$evento->save();
$nombre=$request->get('nombre');
$telefono = $request->get('telefono');
$correo = $request->get('correo');
$cont = 0;
while ($cont < count($nombre)) {
# code...
$detalle = new Contacto();
$detalle->idempresa=$id;
$detalle->nombre=$nombre[$cont];
$detalle->telefono=$telefono[$cont];
$detalle->correo=$correo[$cont];
$detalle->save();
$cont=$cont+1;
}
DB::commit();
} catch (\Exception $e) {
DB::rollback();
}
return Redirect::to('ventas/cliente/create');
}
public function show($id)
{
return view("ventas.cliente.show",["persona"=>Persona::findOrFail($id)]);
}
public function edit($id)
{
return view("ventas.cliente.edit",["persona"=>Persona::findOrFail($id)]);
}
public function update(PersonaFormRequest $request,$id)
{
$persona=Persona::findOrFail($id);
$persona->tipo_documento=$request->get('tipo_documento');
$persona->documento=$request->get('documento');
$persona->empresa=$request->get('empresa');
$persona->direccion=$request->get('direccion');
$persona->razon_social=$request->get('razon_social');
$persona->update();
$evento=new Evento;
$user = Auth::id();
$evento->cod_usuario=$user;
$evento->tabla='Cliente';
$evento->accion='Modificacion';
$evento->codigo_referencia=$id;
$mytime = Carbon::now(' America/Caracas');
$evento->fecha =$mytime->toDateTimeString();
$evento->save();
return Redirect::to('ventas/cliente');
}
public function destroy($id)
{
$persona=Persona::findOrFail($id);
$clientes = DB::table('cliente')->where('codigo_cliente', '=', $id)->delete();
$persona->update();
$evento=new Evento;
$user = Auth::id();
$evento->cod_usuario=$user;
$evento->tabla='Cliente';
$evento->accion='Eliminar';
$evento->codigo_referencia=$id;
$mytime = Carbon::now(' America/Caracas');
$evento->fecha =$mytime->toDateTimeString();
$evento->save();
return Redirect::to('ventas/cliente');
}
}
this issue appear because one of the value that is between the {{}} returning an array instead of string.
and i think it is in the following code
<input type="text" name="pcorreo" id="pcorreo" class="form-control" value="{{old('correo')}}" placeholder="correo...">
and as I saw in your view code you have an input with name correo[] that is an array, and after the validation failure the controller redirect to the form view, the old('correo') function return an array instead of string

After uploading picture only shows blank white screen

http://127.0.0.1/masterlinkci2/admin/cpages/addpicture/33
After uploading picture 1.jpg and press upload file only a blank white screen appears I wonder why?
controllers/Cpages.php
public function addpicture() {
$gallery_id = $this->uri->segment(3);
$data['images'] = $this->Mpages->call_slideshow($gallery_id);
$this->load->view('addpicture', $data);
}
views/addpicture.php
<label><b>UPLOAD PICTURE</b></label><br><br>
<div style="margin-left: 35px">
<fieldset>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<label for="filename" class="control-label">Select File to Upload</label>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<input type="file" name="filename" size="20" />
<span class="text-danger"><?php if (isset($error)) { echo $error; } ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<input type="submit" class="edit" value="Upload File" class="btn btn-primary"/>
</div>
</div>
</div>
</fieldset>
</div>
controllers/Cuploadfile.php
//file upload function
function uploadgallerypic()
{
//set preferences
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|gif';
$config['max_size'] = '1000000';
//load upload class library
$this->load->library('upload', $config);
$this->load->model('Mpages');
if (!$this->upload->do_upload('filename'))
{
// case - failure
$upload_error = array('error' => $this->upload->display_errors());
$this->load->view('addpicture', $upload_error);
}
else
{
// case - success
$gallery_id = $this->uri->segment(3);
$upload_data = $this->upload->data();
$filename = $upload_data['file_name'];
$this->Mpages->add_picture_gallery($filename, $gallery_id);
$data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . $upload_data['file_name'] . '</strong> was successfully uploaded!</div>';
$this->load->view('addpicture', $data);
}
}
Can anyone help me figure it out why after pressing "Upload File" a blank white screen appears on the screen ?

upload image got error in codeigniter

what im trying to do is Im trying to upload an image to database but I dont know what is the reason why I've got an error like
Message: Undefined index: userfile
Message: Undefined variable: images
in my view. as you can see the name of the input file set as an array same as other tutorial
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Person Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input name="firstName" placeholder="First Name" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<input type="file" name="userfile[]" id="file" class="form-control">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select name="gender" class="form-control">
<option value="">--Select Gender--</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address</label>
<div class="col-md-9">
<textarea name="address" placeholder="Address" class="form-control"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input name="dob" placeholder="yyyy-mm-dd" class="form-control datepicker" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal
in my controller.
public function image()
{
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']); //this is line that has an error, the Message: Undefined index: userfile
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
}
$fileName = implode(',',$images); // the line that has an error, Message: Undefined variable: images
return $fileName;
}
public function ajax_add()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
//'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
'image' => $this->input->post($this->image()),
);
$insert = $this->person->save($data);
echo json_encode(array("status" => TRUE));
}
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = './upload/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
public function ajax_update()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
// 'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
);
$this->person->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
I want to insert that image name to my database but that errors block me to do that... need help.
In your Ajax Request Please add
$("#form").submit(function(e){
e.preventDefault();
var fd = new FormData();
$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
return xhrobj;
},
data: formData,
So on....
//ajax close
});
And DOnt Forgot to use
enctype="multipart/form-data"
On form tag...And You will be fine
For Undefined variable: images
Please put
$images = array();// just before for loop.
$cpt = count($_FILES['userfile']);

Resources