how to save multiple data using array in laravel - laravel

this is a part of my code:
<div class="row">
<div class="col-lg-2 col-md-12 col-xs-12">
<div class="form-group">
<label for="exampleInputEmail1">Title*</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="title[]">
</div>
</div>
<div class="col-lg-5 col-md-12 col-xs-12">
<div class="form-group">
<label for="exampleInputEmail1">First Name*</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="f_name[]">
</div>
</div>
<div class="col-lg-5 col-md-12 col-xs-12">
<div class="form-group">
<label for="exampleInputEmail1">Last Name*</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="l_name[]">
</div>
</div>
</div>
and if i click add button, it will show the second form same like above. so how to save all input data into database? this is what i've done in my controller.
public function store(Request $request){
$title = $request->title;
$f_name = $request->f_name;
$l_name = $request->l_name;
$form = new Conference;
$form->name = $title.' '.$f_name.' '.$l_name;
$form->email = $request->email;
$form->phone = $request->phone;
$form->position = $request->position;
$form->category = $request->optradio;
$form->price = $request->price;
$form->t_price = $request->t_price;
$form->company = $request->company;
$form->save();
return redirect()->back()->with('message','REGISTRATION SUCCESS');
}
but it returned an error "Array to string conversion". I know i have to write something in my controller but i don't know what to do. can someone help me?

You can loop through elements and then bulk insert as below
public function store(Request $request){
$title = $request->title;
$f_name = $request->f_name;
$l_name = $request->l_name;
$data = [];
foreach($title as $key => $value) {
$data[] = [
"name" => $value." ".$f_name[$key]." ".$l_name[$key];
]
}
$Conference::insert($data);
return redirect()->back()->with('message','REGISTRATION SUCCESS');
}

Related

Laravel : Call to a member function getClientOriginalName() on null when Update Data

I will update the data its contain image, then when I will send to update here's the error Call to a member function getClientOriginalName()
This is my Controller
public function updateBook(Request $request, $id){
$book = DB::table('books')->where('id',$id);
$old = $book->select('images');
$ChecK = 0;
$file = var_dump($request->file('images')->getClientOriginalName());
$filename = time().$file;
$path = public_path('/Uploads');
if($request->hasFile('images')){
$file = $request->file('images');
$file->move($path, $filename);
Storage::delete($old);
$ChecK = 1;
}
else {
dd('Request Hash No File!');
}
$data = [
'name'=> $request->input('bookName'),
'year'=> $request->input('tahunT'),
'author'=> $request->input('author'),
'summary'=> $request->input('Summary'),
'publisher'=> $request->input('publishers'),
'pageCount' => $request->input('pageCount'),
'readPage'=> $request->input('ReadPage'),
'finished' => '$pageCount' == '$readPage' ? true : false,
'reading' => '$readPage' > 0 ? true : false,
'updatedAt'=> new DateTime()
];
if( $ChecK == 1){
$data = ['images' => $filename];
$book->update($data);
return redirect('home')->with('status', 'update succesfully');
}
else {
$data = ['images' => $old];
$book->update($data);
return redirect('home')->with('status', 'Update with old image ');
}
}
Here is the view
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
#foreach ($toEdit as $dt)
<form class="row g-3" enctype="multipart/form-data" method="POST" action="{{ route('update', $dt->id) }}" value="PUT">
{{ csrf_field() }}
<div class="col-md-6">
<label for="bookName" class="form-label">Nama Buku:</label>
<input type="text" class="form-control" name ="bookName"id="bookName" value="{{ ($dt->name) }}">
</div>
<div class="col-md-3">
<label for="tahunT" class="form-label">Tahun Terbit : </label>
<input type="number" class="form-control" name="tahunT" id="tahunT" value="{{ ($dt->year) }}">
</div>
<div class="col-md-3">
<label for="author" class="form-label">Author : </label>
<input type="text" class="form-control" name="author" id="author" value="{{ ($dt->author) }}">
</div>
<div class="col-md-6">
<label for="publishers" class="form-label">Publisher : </label>
<input type="text" class="form-control" name="publishers" id="publishers" value="{{ ($dt->publisher) }}">
</div>
<div class="col-md-3">
<label for="pageCount" class="form-label">Page Count :</label>
<input type="number" class="form-control" name="pageCount" id="pageCount" value="{{ ($dt->pageCount) }}">
</div>
<div class="col-md-3">
<label for="ReadPage" class="form-label">Read Page :</label>
<input type="number" class="form-control" name="ReadPage" id="ReadPage"value="{{ ($dt->readPage) }}">
</div>
<div class="col-12">
<label for="Summary" class="form-label">Summary :</label>
<textarea class="form-control" name="Summary" id="Summary">{{ ($dt->summary) }}</textarea>
</div>
<div class="col-md-12">
<label for="images" class="form-label">Book Image :</label>
<input type="file" class="form-group" name="images">
<br>
<img src="{{ asset('Uploads/'.$dt->images) }}" widht="300px"/>
<br>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
#endforeach
</div>
Here, I will update the data, if user want to change the images, so the image will be update and if no, the images use the old one. It's rull same as the other input. But, when I try to upload the new one, the error Call to a member function getClientOriginalName() happen.
Do you have any suggestion to this? I already add the code enctype="multipart/form-data" and var_dump() but the error was same. Thank you :)
You have to check, with a condition, if your image is null or not in order to avoid this error.
Try something like :
if ( isset($request->file('images')) != null ) {
$ChecK = 0;
$file = $request->file('images')->getClientOriginalName();
$filename = time().$file;
$path = public_path('/Uploads');
}
//..
Just add a simple condition :
If($request->file('image')) {
...
$request->images->getClientOriginalNe();
.....
}

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');
}
}

How to display selected value and image in edit page to perform update operation using laravel

Hello,
I am new learner in Laravel and my first post in Stackoverflow so applogy to me for my mistake and English language.
I can create a project shoppingcart & perform CRUD operation where create product information such as product name, brand, description, price & image. I can done create & read operation easily. Below my product list that can be show in browser
enter image description here
When I click edit button browser can show like that below image to perform edit operation
enter image description here
where brand name & image can't shown edit product form
My productController code below like that
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\brand;
use App\Product;
use Illuminate\Support\Facades\DB;
class productController extends Controller
{
public function index(){
$product = DB::table('products')
->join('brands','products.brandID','=','brands.brandID')
-> select('products.*','brands.brandName')
->get();
return view('admin.product.productList',compact('product'));
}
public function create()
{
$product = brand::pluck('brandName','brandID');
return view('admin.product.createProduct',compact('product'));
}
public function store(Request $request)
{
// image upload
$product = $request->except('image');
$image = $request->image;
if ($image) {
$imageName = $image->getClientOriginalName();
$image->move('images', $imageName);
$product['image'] = $imageName;
}
Product::create($product);
return view('admin.product.productList', compact('product'));
}
public function show($id)
{
$product = Product::find($id);
return view('admin.product.editProduct',compact('product'));
}
public function edit($id)
{
}
public function delete($id){
$product= Product::find($id);
$data=$product->delete();
return view('admin.product.productList',compact('data'));
}
}
my editProduct.blade file code below like that
#extends('layouts.master')
#section('content')
<div class="container" align="center">
<div class="col-md-6 col-md-offset-3">
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Edit Product
</div>
<div class="panel-body">
<form action="edit" class="form-horizontal" method="POST>
{{csrf_field()}}
<div class="form-group">
<label for="name" class="col-md-4 control-label">Product Name :</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" value="{!! $product->productName !!}" name="name" required autofocus>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Brand :</label>
<div class="col-md-6">
<select name=" " class="form-control" >
<option>
</option>
</select>
</div>
</div>
<div class="form-group">
<label for="description" class="col-md-4 control-label">Description:</label>
<div class="col-md-6">
<input id="description" class="form-control" name="description" value="{!! $product->description !!}" required>
</div>
</div>
<div class="form-group">
<label for="price" class="col-md-4 control-label">Price:</label>
<div class="col-md-6">
<input id="price" value="{!! $product->price !!}" class="form-control" name="price" required>
</div>
</div>
<div class="form-group">
<label for="image" class="col-md-4 control-label">Image:</label>
<div class="col-md-6">
<input id="image" type="file" value="{!! $product->image !!}" class="btn-btn-default" name="image" value="Upload" required>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
ADD
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
Here, brand name can be selected by HTML select attribute and value get another model Brand & the data can be retrieve from Brand model using join query which is included productController index method.
So how can I show brand name & image to edit in the editProduct blade file. Pls help me
There are couple of ways, here's 1 way.
In your controller.
public function edit($id)
{
$product = Product::find($id);
$data = [
'product_info' => $product
];
return view('your.edit.view.here', $data);
}
And inside your view, inside the FORM Tag, do the looping.
#foreach($product_info as $info)
// data info here
<input id="description" value="{{ $product->description }}" required>
#endforeach
EDIT::
Use Laravel Encryption, you need it especially web apps like shopping cart.
URL:: http://localhost:8000/product/show/encrypted_id_here
public function show($id) {
$id = decrypt($id);
}

how to compare current and old password both are same or not before updation in DB using Codeigniter

I used this HTML for developing Form
<form method="post" action="<?php echo site_url('patients/change_patient_password'); ?>/<?php echo $this->session->userdata('patientDiseasesId'); ?>" class="form-horizontal">
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Current Password</label>
<div class="col-md-4">
<input type="text" required class="form-control" name="password" placeholder="Current Password">
<?php $pass = form_error('password'); if(isset($pass)): ?><span class="help-block"><?php echo form_error('password'); ?></span><?php endif; ?>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">New Password </label>
<div class="col-md-4">
<input type="text" required class="form-control" name="password_confirm" placeholder="New Password">
<?php $pass_confirm = form_error('password_confirm'); if(isset($pass_confirm)): ?><span class="help-block"><?php echo form_error('password_confirm'); ?></span><?php endif; ?>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">ReType New Password</label>
<div class="col-md-4">
<input type="text" required class="form-control" name="password_confirm2" placeholder="ReType New Password">
<?php $pass_confirm2 = form_error('password_confirm2'); if(isset($pass_confirm2)): ?><span class="help-block"><?php echo form_error('password_confirm2'); ?></span><?php endif; ?>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green">Update Password</button>
<button type="button" class="btn default">Cancel</button>
</div>
</div>
</div>
</form>
also please have a look my code controller.
public function change_patient_password($patientId){
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('password', 'Password', 'required|is_unique[patients.password]');
$this->form_validation->set_rules('password_confirm', 'New Password', 'required|matches[password_confirm2]');
$this->form_validation->set_rules('password_confirm2', 'ReType New Password', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->change_patient_password_form();
}
else
{
$this->load->model('patients_model');
$data['password_updated'] = $this->patients_model->change_patient_password_model($patientId);
if($data['password_updated']==true){
$data['success']=true;
$data['main_content']= 'change_patient_password_form';
$this->load->view('includes/patient_template',$data);
}else{
$data['error']=true;
$data['main_content']= 'change_patient_password_form';
$this->load->view('includes/patient_template',$data);
}
}
here is the final model code
public function change_patient_password_model($patientId){
$data = array(
'password' => md5($this->input->post('password_confirm'))
);
$this->db->where('patientDiseasesId', $patientId);
return $this->db->update('patients', $data);
}
I see you're using "is_unique" in your form validation. Will each password be unique?
How I would do this, is to query the DB before we update it, and check if the passwords match. Like so.
public function change_patient_password_model($patientId)
{
// Get this users info
$query = $this->db->get_where('patients', array('patientDiseasesId' => $patientId));
if($query->num_rows() > 0)
{
// We have the patient, so check if the passwords match
$current_password = $query->row('password');
$inputted_password = md5($this->input->post('password_confirm'));
if( $current_password != $inputted_password)
{
// They are not the same, so update it...
$data['password'] = $inputted_password;
$this->db->where('patientDiseasesId', $patientId);
return $this->db->update('patients', $data);
}
else
{
// They are the same...
return false;
}
}
else
{
// No patients with this ID
return false;
}
}
I hope this helps.

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