Photo don't display in shop cart LARAVEL 6 - laravel

i'm using laravel in my project , so when i add a product in the shop cart all the data is displayed except the product image.
This is the cartcontroller.php:
public function add(Request $request) {
$produit=productmodel::find($request->id);
Cart::add(array(
'id' =>$request->id, // inique row ID
'name' =>$request->product_name,
'price' => $request->product_price,
'quantity' =>$request->product_quantity,
'attributes' => array('photo'=>$request->product_image)));
return redirect ('shop-cart');
}
and this is the shop-cart.blade.php
<tbody>
#foreach(\Cart::getContent() as $item)
<tr>
<td class="cart__product__item">
<div class="cart__product__item__title">
<img src="{{asset('storage/product/September2020/'.$item->attributes['photo'])}}" alt="">
<h6> {{Str::words($item->name,20) }}</h6>
#foreach($item->attributes as $key => $value)
<dl class="dlist-inline small">
<dt>{{ ucwords($key) }}: </dt>
<dd>{{ ucwords($value) }}</dd>
</dl>
#endforeach
</div>
</td>
<td class="cart__price"> {{$item->price}} TND</td>
<td class="cart__quantity">
{{ $item->quantity }}
</td>
<td class="cart__total"> {{ $item->price * $item->quantity }} TND</td>
<td class="cart__close"><i class="fa fa-times"></i>
</td>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endif

If you are using darryldecode/cart for cart. You can go to your vendor folder and make some slight changes to add method of Cart.php file.
public function add($id, $name = null, $price = null, $quantity = null, $image = null, $attributes = array(), $conditions = array(), $associatedModel = null)
{
// if the first argument is an array,
// we will need to call add again
if (is_array($id)) {
// the first argument is an array, now we will need to check if it is a multi dimensional
// array, if so, we will iterate through each item and call add again
if (Helpers::isMultiArray($id)) {
foreach ($id as $item) {
$this->add(
$item['id'],
$item['name'],
$item['price'],
$item['quantity'],
$item['image'],
Helpers::issetAndHasValueOrAssignDefault($item['attributes'], array()),
Helpers::issetAndHasValueOrAssignDefault($item['conditions'], array()),
Helpers::issetAndHasValueOrAssignDefault($item['associatedModel'], null)
);
}
} else {
$this->add(
$id['id'],
$id['name'],
$id['price'],
$id['quantity'],
$id['image'],
Helpers::issetAndHasValueOrAssignDefault($id['attributes'], array()),
Helpers::issetAndHasValueOrAssignDefault($id['conditions'], array()),
Helpers::issetAndHasValueOrAssignDefault($id['associatedModel'], null)
);
}
return $this;
}
$data = array(
'id' => $id,
'name' => $name,
'price' => Helpers::normalizePrice($price),
'quantity' => $quantity,
'image'=>$image,
'attributes' => new ItemAttributeCollection($attributes),
'conditions' => $conditions
);
if (isset($associatedModel) && $associatedModel != '') {
$data['associatedModel'] = $associatedModel;
}
// validate data
$item = $this->validate($data);
// get the cart
$cart = $this->getContent();
// if the item is already in the cart we will just update it
if ($cart->has($id)) {
$this->update($id, $item);
} else {
$this->addRow($id, $item);
}
$this->currentItemId = $id;
return $this;
}
Now you can simply store image in cart as below
$userId = auth()->user()->id;
\Cart::session($userId)->add(array(
'id' => $request->id,
'name' =>$request->item_name,
'price' =>$request->item_price,
'quantity' => $request->quantity,
'image'=>$request->image,
'attributes' => array(),
));
And view your stored image from path like
#foreach(Cart::session(auth()->user()->id)->getContent() as $items)
<div class="row pt-5">
<div class="col-md-3 offset-md-2">
<img class="card-img-top" src="{{asset('photos').'/'.$items->image}}"
style="height:120px; width:120px;"alt="Card image cap">
</div>
<div class="col-md-6 ">
<h5 class="font-weight-bold">{{$items->name}}</h5>
Rate: Rs {{$items->price}}<br>
Qty: {{$items->quantity}}<br>
<?php
$price="";
$price=$items->quantity*$items->price;
?>
Price: Rs {{$price}}<br>
<button class="btn-sm btn-outline-danger"><i class="far fa-trash-alt"></i></button>
</div>
</div>
<hr>
#endforeach

Related

Updating many-to-many relational data with attach() from multiple checkboxes in Laravel

I am creating an online bookstore in Laravel, and upon creating a new book, the administrator is able to define which warehouses that are able to stock this book, by checking the specific warehouses checkboxes.
To give insight in how it works, this is my create function:
public function create()
{
$authors = Author::all();
$selectedAuthor = Book::first()->author_id;
$publishers = Publisher::all();
$selectedPublisher = Book::first()->publisher_id;
$warehouses = Warehouse::all();
$selectedWarehouse = Book::first()->warehouse_id;
return view('books.create', compact(['authors', 'publishers', 'warehouses'],
['selectedAuthor', 'selectedPublisher', 'selectedWarehouse']
));
}
and my store method:
public function store(Request $request)
{
$request->validate([
'ISBN' => 'required',
'author_id' => 'required',
'publisher_id' => 'required',
'year' => 'required',
'title' => 'required',
'price' => 'required',
]);
try {
$book = Book::create($request->all());
foreach ($request->checked as $value){
$book->warehouses()->attach([$value]);
}
return redirect()->route('books.index')
->with('success','Book created successfully.');
} catch (\Illuminate\Database\QueryException $e) {
var_dump($e->errorInfo);
}
}
But when an administrator edits a book, the checkboxes that were checked upon creating the book, should be "checked", and the administrator should be able to attach more warehouses, and be able to "unselect" a warehouse, so if an already checked value gets unchecked and sumbitted, it should get detached from the many-to-many table.
This is what i currently have:
My edit method:
public function edit(Book $book)
{
$authors = Author::all();
$selectedAuthor = Book::first()->author_id;
$publishers = Publisher::all();
$selectedPublisher = Book::first()->publisher_id;
$warehouses = Warehouse::all();
$selectedWarehouse = Book::first()->warehouse_id;
return view('books.edit', compact(['book', 'authors', 'publishers', 'warehouses'],
['selectedAuthor', 'selectedPublisher', 'selectedWarehouse']));
}
And my update method:
public function update(Request $request, Book $book)
{
$request->validate([
'ISBN' => 'required',
'publisher_id' => 'required',
'author_id' => 'required',
'year' => 'required',
'title' => 'required',
'price' => 'required',
]);
try {
$book->update($request->all());
// TODO: Update warehouses
return redirect()->route('books.index')
->with('success','Book updated successfully.');
} catch (\Illuminate\Database\QueryException $e) {
var_dump($e->errorInfo);
}
}
And the checkboxes in my edit.blade view:
#foreach($warehouses as $warehouse)
<input type="checkbox" name="checked[]" value="{{ $warehouse->id }}">
{{ $warehouse->address }}
<br/>
#endforeach
My Book model:
public function warehouses()
{
return $this->belongsToMany(Warehouse::class);
}
And my warehouse model:
public function books()
{
return $this->belongsToMany(Book::class);
}
Any help on being able to attach / detach upon editing an existing book, would be highly appreciated!
Try this on create and update method for storing
// Your method
foreach ($request->checked as $value){
$book->warehouses()->attach([$value]);
}
// Try This
$book->warehouses()->sync($request->checked); // $request->checked must be an array
Update Blade
#foreach($warehouses as $warehouse)
<input #if($book->warehouses()->where('warehouse_id', $warehouse->id)->exists()) checked #endif type="checkbox" name="checked[]" value="{{ $warehouse->id }}">
{{ $warehouse->address }}
<br/>
#endforeach
I will left this example with a logic according your problem. In this case are roles:
public function edit(Role $role){
//get roles ids
$permission_role = [];
foreach($role->permissions as $permission){
$permission_role[] = $permission->id;
}
//get permissions
$permissions = Permission::all();
return view("role.edit", compact('role', 'permission_role', 'permissions'));
}
In the blade:
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>Select the permissions for the current role</label>
#foreach ($permissions as $permission)
<div class="valid-feedback d-block" style="font-size: 15px !important;">
<input type="checkbox" value="{{ $permission->id }}" name="permissions[]"
#if(is_array(old('permissions')) && in_array("$permission->id", old('permissions')))
checked
#elseif(is_array($permission_role) && in_array("$permission->id", $permission_role))
checked
#endif>
<strong> {{ $permission->description }} </strong>
</div>
#endforeach
</div>
<div class="invalid-feedback d-block">
#foreach ($errors->get('permissions') as $error)
{{ $error }}
#endforeach
</div>
</div>
</div>
Of this way you can also keep the old checkboxes when nothing is select. You should validate it as required.

Test Driven Laravel : Invalid Argument supplied for foreach

So i have a form with multiple fields like below
<ul class="list-group list-group-flush">
#foreach ($group as $perm)
<li class="list-group-item">{{$perm->name}}
<div class="float-right">
<select name="perms[{{$perm->id}}]" class="form-control">
<option value="1">Yes</option>
<option value="0" selected>No</option>
</select>
</div>
</li>
#endforeach
</ul>
My controller is like below
public function permission(int $id)
{
$permission = request()->perms;
foreach ($permission as $perm => $status)
{
if($status == 1)
{
//echo $perm . " " . $status;
$user_perm = User_perms::create([
'user_id' => $id,
'perm_id' => $perm,
]);
}
}
$user = Users::find($id);
return redirect($user->path());
}
This code does what I want but I have a test
public function permissions_applied_for_user()
{
$this->withoutExceptionHandling();
//create a user
$this->post('/users/add', $this->data());
$user = Users::first();
//first clear out all data from user_perm table for specific user
$response = $this->post('/users/permission/' . $user->id, [
'user_id' => $user->id,
'perm_id' => '1',
]);
$this->assertCount(1, User_perms::all());
$response->assertRedirect('/users/view/' . $user->id);
//$response->assertOk();
//second insert all new permissions into the table
}
which throws the exception invalid argument supplied for foreach any advice on what I'm doing wrong?

codeigniter update quantity not working

quantity not update only If I add an item with the exact same options more than once to my cart, it replaces instead of increasing the qty of the existing item
This is cart view code
`<table class="table table-bordered table-hover">
<thead ><!-- Table head -->
<tr>
<th class="active">Sl</th>
<th class="active col-sm-4">Product</th>
<th class="active col-sm-2">Real Price</th>
<th class="active ">Qty</th>
<th class="active ">Disc Price</th>
<th class="active">Total</th>
<th class="active">Action</th>
</tr>
</thead><!-- / Table head -->
<tbody><!-- / Table body -->
<?php $cart = $this->cart->contents() ;
?>
<?php $counter =1 ; ?>
<?php if (!empty($cart)): foreach ($cart as $item) : ?>
<tr class="custom-tr">
<td class="vertical-td">
<?php echo $counter ?>
</td>
<td class="vertical-td"><?php echo $item['name'] ?></td>
<td class="vertical-td"><?php echo $item['pkprice'] ?></td>
<td class="vertical-td">
<input type="text" name="qty" style="width: 50px" value="<?php echo $item['qty'] ?>" onblur ="order(this);" id="<?php echo 'qty'.$item['rowid'] ?>" class="form-control">
</td>
<td>
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" id="<?php echo 'opt'.$item['rowid'] ?>" onclick="return price_checkbox(this)" name="custom_price"
<?php echo $item['price_option'] == 'custom_price' ? 'checked':'' ?>
data-placement="top" data-toggle="tooltip" data-original-title="Custom Price">
</span>
<input type="text" name="price" value="<?php echo $item['price'] ?>" onblur ="order(this);" id="<?php echo 'pri'.$item['rowid'] ?>" class="form-control"
<?php echo $item['price_option'] == 'custom_price' ? '':'disabled' ?> >
</div>
<input type="hidden" name="product_code" value="<?php echo $item['id'] ?>" id="<?php echo 'code'.$item['rowid'] ?>">
</td>
<td class="vertical-td"><?php echo number_format($item['subtotal'], 2, '.', ',') ?></td>
<td class="vertical-td">
<?php echo btn_delete('admin/order/delete_cart_item/' . $item['rowid']); ?>
</td>
</tr>
<?php
$counter++;
endforeach;
?><!--get all sub category if not this empty-->
<?php else : ?> <!--get error message if this empty-->
<td colspan="6">
<strong>There is no record for display</strong>
</td><!--/ get error message if this empty-->
<?php endif; ?>
</tbody><!-- / Table body -->
`
This is Controller Code
public function add_cart_item_by_barcode(){
$product_code = $this->input->post('barcode', true);
$result = $this->order_model->validate_add_cart_item($product_code);
if($result){
$price = $this->check_product_rate($result->product_id, $qty=1);
//product tax check
$tax = $this->product_tax_calculate($result->tax_id, $qty=1, $price);
$data = array(
'id' => $result->product_code,
'qty' => 1,
'price' => $price,
'buying_price' => $result->buying_price,
'name' => $result->product_name,
'pkprice' => $result->p_price,
'tax' => $tax,
'price_option' => 'general'
);
$this->cart->update($data);
$this->session->set_flashdata('cart_msg', 'add');
}
redirect('admin/order/new_order/'.$flag ='add');
}
public function check_product_rate($product_id=null, $qty=null)
{
//tier Price check
$tire_price = $this->order_model->get_tire_price($product_id, $qty);
if($tire_price)
{
return $price = $tire_price->tier_price ;
}
//special offer check
$this->tbl_special_offer('special_offer_id');
$offer_price = $this->global_model->get_by(array("product_id"=>$product_id), true);
if(!empty($offer_price)) {
$today = strtotime(date('Y-m-d'));
$start_date = strtotime($offer_price->start_date);
$end_date = strtotime($offer_price->end_date);
if (($today >= $start_date) && ($today <= $end_date)) {
return $price = $offer_price->offer_price;
}
}
//return regular rate
$this->tbl_product_price('product_price_id');
$general_price = $this->global_model->get_by(array("product_id"=>$product_id), true);
return $product_price = $general_price->selling_price;
}
/*** Product tax calculation ***/
public function product_tax_calculate($tax_id, $qty ,$price)
{
$this->tbl_tax('tax_id');
$tax = $this->global_model->get_by(array('tax_id'=>$tax_id), true);
//1 = tax in %
//2 = Fixed tax Rate
if($tax){
if($tax->tax_type == 1)
{
$subtotal = $price * $qty;
$product_tax = $tax->tax_rate * ($subtotal / 100);
//return $result = round($product_tax, 2);
return $result = $product_tax;
}else
{
//$product_tax = $tax->tax_rate * $qty;
$product_tax = $tax->tax_rate * $qty;
return $result = $product_tax;
}
}
}
/*** Update Product Cart ***/
public function update_cart_item()
{
$rowid = $this->input->post('rowid');
$qty = $this->input->post('qty');
$product_price = $this->input->post('price');
$product_code = $this->input->post('product_code');
$custom_price = $this->input->post('custom_price');
if($qty !=0 )
{
//tbl product
$this->tbl_product('product_id');
$result = $this->global_model->get_by(array('product_code'=> $product_code ), true);
//product Inventory Check
$this->tbl_inventory('inventory_id');
$product_inventory = $this->global_model->get_by(array('product_id'=> $result->product_id ), true);
if($qty > $product_inventory->product_quantity)
{
$type = 'error';
$message = 'Sorry! This product has not enough stock.';
set_message($type, $message);
echo 'false';
return;
}
if($custom_price == "on")
{
$price = $product_price;
$price_option = 'custom_price';
}
else
{
//product price check
$price = $this->check_product_rate($result->product_id, $qty);
$price_option = 'general';
}
//product tax check
$tax = $this->product_tax_calculate($result->tax_id, $qty, $price);
$data = array(
'rowid' => $rowid,
'qty' => $qty,
'price' => $price,
'tax' => $tax,
'price_option' => $price_option
);
}else
{
$data = array(
'rowid' => $rowid,
'qty' => $qty,
);
}
$this->cart->update($data);
if($this->input->post('ajax') != '1'){
redirect('admin/order/new_order'); // If javascript is not enabled, reload the page with new data
}else{
echo 'true'; // If javascript is enabled, return true, so the cart gets updated
}
}
/*** Show cart ***/
function show_cart(){
$this->load->view('admin/order/cart/cart');
}
/*** cart Summery ***/
function show_cart_summary(){
$this->load->view('admin/order/cart/cart_summary');
}
/*** Delete Cart Item ***/
public function delete_cart_item($id)
{
$data = array(
'rowid' => $id,
'qty' => 0,
);
$this->cart->update($data);
$this->session->set_flashdata('cart_msg', 'delete');
redirect('admin/order/new_order/'.$flag ='delete');
}
This is working fine when add product or change its quantity all perfect working but If I add an item with the exact same options more than once to my cart, it replaces instead of increasing the qty of the existing item
Have you tried this?
<?php foreach ($this->cart->contents() as $items): ?>
<?php echo form_hidden($counter.'[rowid]', $items['rowid']); ?> // write this
and then this
<td><?php echo form_input(array('name' => $counter.'[qty]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?></td>
instead of-
<?php echo form_input(array('name' =>'rowid1[]', 'type'=>'text', 'value' => $items['rowid'], 'maxlength' => '3', 'size' => '5')); ?>
I hope this works
Check what query is generated when update query is fire, i think any signal quote is added in your query.
for check the last database query use this function:-
print_r($this->db->last_query());
After a lot of struggled i get my code correctly here is the correct code of insert and update
function add_cart_item_by_barcode(){
$product_code = $this->input->post('barcode', true);
$result = $this->order_model->validate_add_cart_item($product_code);
$rowid = $this->input->post('rowid');
$cart = $this->cart->contents();
foreach ($cart as $cart) {
if($product_code == $cart['id']){
$rowid=$cart['rowid'];
$qty=$cart['qty'];
$data=array(
'rowid'=>$rowid,
'qty'=>$qty+1
);
$data=$this->cart->update($data);
$this->session->set_flashdata('cart_msg', 'add');
redirect('admin/order/new_order/'.$flag ='add');
}
}
if ($result) {
// update rate
$price = $this->check_product_rate($result->product_id, $qty=1);
//product tax check
$tax = $this->product_tax_calculate($result->tax_id, $qty=1, $price);
$data = array(
'id' => $result->product_code,
'qty' => $qty,
'price' => $price,
'buying_price' => $result->buying_price,
'name' => $result->product_name,
'pkprice' => $result->p_price,
'tax' => $tax,
'price_option' => 'general'
);
$this->cart->insert($data);
$this->session->set_flashdata('cart_msg', 'add');
}
redirect('admin/order/new_order/'.$flag ='add');
}

I can not validate form with multi feild by variable name in laravel 5.4

I am using Laravel 5.4
my create form is multi feild for multi language. name of field in my form is variable:
{!! Form::open(['route' => 'pages.store','files'=>true]) !!}
#if( isset($languages) && $languages->count() > 0 )
#foreach($languages as $language)
<div class="form-group">
{!! Form::label('subject_'.$language->code, 'subject in '.$language->name) !!}
<div class="form-line">
{!! Form::text('subject_'.$language->code,old('subject'),['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
<!-- TinyMCE -->
{!! Form::textarea('content_'.$language->code,'',['class'=>'tinymce']) !!}
<!-- #END# TinyMCE -->
</div>
#if (!$loop->last)
<hr class="style18">
#endif
#endforeach
<div class="form-group">
{!! Form::submit('save change',['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
and my control code:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'subject' => 'required|max:255',
'content' => 'required|max:255',
]);
$languages = Languages::all();
$page = new Page();
$page->save(); // Eloquent
foreach ($languages as $language) {
$pageTrans = new PageTrans();
$pageTrans['page_id']= $page->id;
$pageTrans['locale'] = $language->locale;
$pageTrans['subject'] = $request->input('subject_' . $language->code);
$pageTrans['content'] = $request->input('content_' . $language->code);
$pageTrans->save(); // Eloquent
}
return redirect(route('pages.index'));
}
but problem with validat and not detect feild name. Do you know of a solution or a better way to do this?
You can change your controller same this. I didn't test. Please let me know if have any problem on that.
$languages = Languages::all();
if( $languages->count() ){
$data = [];
foreach ($languages as $language) {
$data['subject_'.$language->code] = 'required|max:255';
$data['content_'.$language->code] = 'required';
}
$validator = Validator::make($request->all(), $data);
if ($validator->fails()) {
return redirect(route('pages.store'))
->withErrors($validator)
->withInput();
}else{
$page = new Page();
$page->save(); // Eloquent
foreach ($languages as $language) {
$pageTrans = new PageTrans();
$pageTrans['page_id']= $page->id;
$pageTrans['locale'] = $language->locale;
$pageTrans['subject'] = $request->input('subject_' . $language->code);
$pageTrans['content'] = $request->input('content_' . $language->code);
$pageTrans->save(); // Eloquent
}
return redirect(route('pages.index'));
}
}
Thank you!

Saving data from a drop down list in CodeIgniter

I created a menu page where it has a drop down menu with a list of menus from the database and it also has a textbox to enter new menus.
The problem I'm having is that I can't seem to figure out how to save my dropdown. So for example I have a menu called "About Us" in the drop down list and I want to create a new menu called "Team", and "Team" is a child of "About Us"
So in my table I would have something like this
id | parent | title
------------------------
1 | NULL | About Us
2 | 1 | Team
Menu Controller
function get_data_from_post()
{
$data['title'] = $this->input->post('title', TRUE);
$data['parent'] = $this->input->post('parent', TRUE);
if(!isset($data)){
$data = '';
}
return $data;
}
function get_data_from_db($update_id)
{
$query = $this->get_where($update_id);
foreach($query->result() as $row){
$data['title'] = $row->title;
$data['parent'] = $row->parent;
}
return $data;
}
function create()
{
$update_id = $this->uri->segment(3);
$submit = $this->input->post('submit', TRUE);
if($submit == "Submit"){
//person has submitted the form
$data = $this->get_data_from_post();
}else{
if(is_numeric($update_id)){
$data = $this->get_data_from_db($update_id);
}
}
if(!isset($data)){
$data = $this->get_data_from_post();
}
//$titles = array();
$query = $this->get('title');
foreach($query->result() as $row){
$titles[] = $row->title;
}
$data['titles'] = $titles;
$data['update_id'] = $update_id;
$data['view_file'] = "create";
$this->load->module('templates');
$this->templates->admin_template($data);
}
function submit()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'required|xss_clean');
if($this->form_validation->run($this) == FALSE){
$this->create();
}else{
$data = $this->get_data_from_post();
$update_id = $this->uri->segment(3);
if(is_numeric($update_id)){
$this->_update($update_id, $data);
}else{
$this->_insert($data);
}
redirect('menus/manage');
}
}
create.php view
<div class="row">
<div class="col-md-12">
<h2>Create Menus</h2>
<h5>Welcome Jhon Deo , Need to make dynamic. </h5>
</div>
</div>
<hr />
<?php
echo validation_errors("<p style='color: red;'>", "</p>");
echo form_open('menus/submit/'.$update_id);
?>
<div class="row">
<div class="col-md-12">
<form role="form">
<div class="form-group">
<select name="menus">
<?php
foreach($titles as $title){
echo "<option value=".$title.">".$title."</option>";
}
?>
</select>
</div>
<div class="form-group">
<label>Title</label>
<!-- <input class="form-control" /> -->
<?php
$data = array(
'name' => 'title',
'id' => 'title',
'value' => $title,
'class' => 'form-control',
);
echo form_input($data);
?>
</div>
<?php
$data = array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Submit',
'class' => 'btn btn-success',
'style' => 'width: 100%',
);
echo form_submit($data);
?>
</form>
</div>
</div>
<?php
echo form_close();
?>
UPDATE:
this is what I have when I print_r($titles)
Array
(
[0] => About Us
[1] => Home
)
If there is anything you don't understand or if you need me to give more information please let me know.
You should have declared a model. From there, you can create a function that will save the values in the database that you initialize via controller. You should utilize the MVC pattern of it. CodeIgniter has a great documentation to read about what I am pointing out.. https://codeigniter.com/user_guide/overview/mvc.html?highlight=model

Resources