I want to delete JSON from database but I can't
My delete function in controller:
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
$photo = json_decode($product->photo_list,true);
$photos = $photo[$id-1];
unset($photos);
$product->save();
Flash::success('Photo deleted successfully.');
return back();
}
UPDATE
Here my edit controller:
public function edit($id)
{
$product = $this->productRepository->findWithoutFail($id);
$store = Store::pluck('name', 'id')->all();
$photo = json_decode($product->photo_list);
//dd($photo);
$category = Category::pluck('name','id')->all();
if (empty($product)) {
Flash::error('Product not found');
return redirect(route('products.index'));
}
return view('products.edit',compact('product','store','category','photo'));
}
Here my view blade.php. I'm using button to delete it.
#foreach($photo as $pro)
<div style="margin-right:10px" class="form-group col-sm-1">
<p><img src="{{ env('FRONTEND_URL') . "/img/products/$product->id/$pro->name"}}" width="100" height="100"/></p>
Delete
</div>
#endforeach
I clik my button delete but it doesn't work.
LASTEST UPDATE
My Delete Function
public function deletephoto($productid,$photoid)
{
$product = $this->productRepository->findWithoutFail($productid);
$photo = json_decode($product->photo_list,true);
foreach($photo as $key => $value) {
if($value['id'] == $photoid) {
unset($photo[$key]);
}
}
return back();
}
my view blade.php
#foreach($photo as $pro)
<div style="margin-right:10px" class="form-group col-sm-1">
<p><img src="{{ env('FRONTEND_URL') . "/img/products/$product->id/$pro->name"}}" width="100" height="100"/></p>
Delete
</div>
#endforeach
I use that code but it doesnt work too...
Currently you are getting photo_list column using $id and trying to remove it using the same $id that's why it is not working. Suppose $id is 23, then you don't have 23 id in your json array of photo_list
Now if you want to remove en element you need to have id of single a image, using that id you can remove like:
To remove key from all array
foreach($photo as $key => $value) {
if($value['id'] == '1') { // assumed 1 to be removed
unset($photo[$key]);
}
}
if you want to remove whole JSON, you can update that photo_list column's value as NULL
EDIT
please check the below example:
$photo ='[{"id": "1","name": "test"},{"id": "2","name": "test"}]';
$photo_obj = json_decode($photo,true); // to get array
$result =[];
foreach($photo_obj as $key => $value) {
if($value['id'] != '1') { // assumed id = 1 to be removed
$result[] = $value;
}
}
print_r(json_encode($result));
seems like your function, findWithoutFail($id) fail on finding the $id.
try dumping the $product and $photo to see if it really returning the data of the $id
Related
I am trying to delete multiple images using product_id, I am able to delete one image at a time but am figuring out how i can insert a variable like $i=0 to a loop over but it does not work in laravel.
so far this is my code
public function ImageDelete($slider_id)
{
//int $i=0; Had introduced this but doesn't work
$slider = Products::findOrFail($slider_id);
foreach($slider as $product){
$product_images=$slider->images()->get();
$image_path = public_path().'\images2\\'.$product_images[0]->filename;
File::delete($image_path);
//$i++;
}
$slider->delete();
return response()->json(['success'=>'Pics deleted successfully!']);
}
The findOrFail method return only one item. So you cannot iterate over it.
You can use the each method
$product = Products::findOrFail($id);
$images = $product->images()->get();
$images->each(function ($file, $key) {
$filePath = public_path("images2/") . $file->filename;
File::delete($filePath);
});
// Delete the product
$product->delete();
Try this:
public function ImageDelete($slider_id)
{
$product = Products::find($slider_id);
$product_images=$product->images()->get();
foreach($product_images as $product_image){
$image_path = public_path().'\images2\\'.$product_image->filename;
File::delete($image_path);
}
$product->delete();
return response()->json(['success'=>'Pics deleted successfully!']);
}
how can I fetch one particular index from the array to delete? e.g. if I have array[a, b, c] in the array list and want to delete b which is index array[1] from it? Any help would be great.
I need to pass index to the controller so I can delete it
View
#foreach (json_decode($p->filename) as $picture)
<ul>
Delete
</ul>
#endforeach
Controller
public function deleteProductImageName($id) {
if(Auth::check()) {
$products = Product::where('id', $id)->first();
foreach($products as $p) {
if(($products->user_id == Auth::user()->id) && ($products->id == $id)) {
$product = Product::where('user_id', Auth::user()->id)
->where('id', $id)->first();
$filename_index = $product->filename;
echo $filename_index; '<br/>';
echo $filename_index . '[' . $index . ']';
}
}
} else {
Session::flash("message", "OOPS! You dont have permission to delete the items. Please login first.");
return redirect("/register-user");
}
}
UPDATED
Have a look at the Loop Variables.
To get the current index, you can use:
$name = $request->query('name');
EDIT
Ok I understand the question better. You want to add additional parameters to the request.
View Example
#foreach($items as $item)
Delete
#endforeach
Controller Example
public function delete($id) {
// get the query parameter
$index = $request->query('index');
}
in laravel 5.1 using maatweb / Excel package i need to export specific row records to excel file where the current page id is viewing
in my VlistController
public function export()
{
Excel::create('Company List', function($excel)
{
$excel->sheet('companies', function($sheet)
{
$data = Vlist::all();
$data = json_decode(json_encode($data),true);
$companies = [];
foreach ($data as $key => $value) {
$company['vname']= $value['vname'];
$company['vaddress']= $value['vaddress'];
$companies[] = $company;
}
$sheet->fromArray($companies);
});
})->download('xlsx');
}
in my routes file
Route::get('/vlist/{vlist}/export' , 'VlistController#export');
in my show view
<li><i class='fa fa-link'></i> <span>Export Supplier : {!! $vlist->vname !!}</span></li>
the above controller code list all the records in excel sheet and i need only one specific record with the active id .
If I understand you problem,you can try this code.You can query by your primary key to retrieve specific row.
public function export($id)
{
Excel::create('Company List', function($excel) use ($id)
{
$excel->sheet('companies', function($sheet) use ($id)
{
$data = Vlist::where('id', $id)->get();
$data = json_decode(json_encode($data),true);
$companies = [];
foreach ($data as $key => $value) {
$company['vname']= $value['vname'];
$company['vaddress']= $value['vaddress'];
$companies[] = $company;
}
$sheet->fromArray($companies);
});
})->download('xlsx');
}
and I don't think the following code is necessary.
$data = json_decode(json_encode($data),true);
$companies = [];
foreach ($data as $key => $value) {
$company['vname']= $value['vname'];
$company['vaddress']= $value['vaddress'];
$companies[] = $company;
}
You can simply use the retrieve specific data
$data = Vlist::where('id', $id)->get(['vname', 'vaddress']);
and pass it to the method
$sheet->fromArray($data);
Thanks
I am in not sure about your Question, in my point of view you want to put(show) record form a specified row then my solution will work.
$projectArr[] = ["col1","col2","col3","col4","col5","col6"];
Excel::create('project_directory_result_sheet', function($excel) use($projectArr) {
$excel->sheet('Project_Directory_Result', function($sheet) use( $projectArr ) {
$sheet->fromArray($projectArr,null, 'A3');
}
}
In my solution noticeable point is $sheet->fromArray($projectArr,null, 'A3');
here i am giving 3 parameter value that are
first:Project Value Array.
second: show header true or false
third: row number where you want to represent record.
I'm using Magento which is on the zend framework and the following code currently outputs the first row matching the criteria is_read != 1', 'is_remove != 1'. I need to modify this code to output the last 4 table rows that matches said criteria. I tried a few things but none worked. Please Help!
ModuleName/Model/Resource/
public function loadLatestNotice(Mage_AdminNotification_Model_Inbox $object)
{
$adapter = $this->_getReadAdapter();
$select = $adapter->select()
->from($this->getMainTable())
->order($this->getIdFieldName() . ' DESC')
->where('is_read != 1')
->where('is_remove != 1')
->limit(1);
$data = $adapter->fetchRow($select);
if ($data) {
$object->setData($data);
}
$this->_afterLoad($object);
return $this;
}
Here are some other codes that are used...
ModuleName/Model/
public function loadLatestNotice()
{
$this->setData(array());
$this->getResource()->loadLatestNotice($this);
return $this;
}
ModuleName/Block/
public function getLatestNotice()
{
return $this->_getHelper()
->getLatestNotice()->getTitle();
}
Template/
href="<?php echo $latestNoticeUrl ?>" onclick="this.target='_blank';"><?php echo $this->getLatestNotice() ?>
I was able to solve the problem myself, by using the following method.
The first thing i tried to produce is 4 notification table rows instead of 1, is to change ->limit(1); to ->limit(4); and $adapter->fetchRow($select); to $adapter->fetchAll($select);. The issue is, the solution requires more than just changing these 2 values.
ModuleName/Model/Resource/
public function loadLatestNotice(Mage_AdminNotification_Model_Inbox $object)
{
$adapter = $this->_getReadAdapter();
$select = $adapter->select()
->from($this->getMainTable())
->order($this->getIdFieldName() . ' DESC')
->where('is_read != 1')
->where('is_remove != 1')
->limit(4);
$data = $adapter->fetchAll($select);
if ($data) {
$object->setData($data);
}
$this->_afterLoad($object);
return $this;
}
After changing this, the template will stop outputting information, In order for the template to output the new array, you must duplicate some code and remove ->getTitle() line in the block file, then change a few line of codes in the template .phtml file as follows.
ModuleName/Block/
public function getNewFuncName()
{
return $this->_getHelper()
->getLatestNotice();
}
Template/
<?php
$notice = $this->getNewFuncName();
foreach ($notice as $item) {
foreach ($item as $value) {
echo '<div class="notemssg"><p id="notetitle" href='.$value['url'].' >'.$value['title'].'</p><p id="notedate">'.$value['date_added'].'</p></div>';
}
}
?>
Changing the code to properly call and display the array will result it 4 table rows being displayed. the code can be modified to be used and any way you would like to display the info on the fronted.
Hope this helps Someone!
I have 2 table :
product_group
product
which is every product have group_id as Foreign Key in the table.
I try to call every product by group_id.
this is my list_group view :
<i class="icon-line-ellipsis"></i>
I try to attach the group_id in URL.
this is my controller :
public function get_product_by_group($group_id)
{
if($this->uri->segment(3))
{
$this->load->database();
$group_id = $this->input->get('group_id', TRUE);
$data['product_data'] = $this->group_model->list_product_by_group($group_id);
$this->load->view('fend/list_product', $data);
}
else
{
redirect('list_group');
}
}
This is my model :
function list_product_by_group($group_id)
{
$this->db->select('*');
$this->db->where('group_id', $group_id);
$query = $this->db->get('product');
return $query->result();
}
and the last is list_product view :
<?php
foreach($product_data as $value)
{
?>
<div class="masonry-thumbs col-3" data-big="2" data-lightbox="gallery">
<img class="image_fade" src="<?= base_url('uploads/'. $value->product_picture);?>" alt="Gallery Thumb 1">
</div>
<?php
}
?>
I got no error, but the data did not appear in product_view.
Thanks for your help :))
If you remove the line $group_id = $this->input->get('group_id', TRUE); it will solve your problem.
Here is the explanation:
Your controller function name is public function get_product_by_group($group_id) so when you go to this link localhost/norwin/list_group/get_product_by_group/1 1 will be passed as $group_id into your get_product_by_group function.So your final function will be like this
public function get_product_by_group($group_id='')
//write this way so that you can call the url like
//localhost/norwin/list_group/get_product_by_group
{
if($group_id)//no need to check uri->segment
{
$this->load->database();
$data['product_data'] = $this->group_model->list_product_by_group($group_id);
$this->load->view('fend/list_product', $data);
}
else
{
redirect('list_group');
}
}