finding array index from view in laravel - php

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

Related

How to pass variables from controller to show their values in blade file

I want to show variables value in blade file. Below is the controller code:-
public function ClientListReviews()
{
// to show client list get data from users booking table
$select_clientlist =
DB::table('users_booking')>where('service_provider', '=', 1)->get();
if(count($select_clientlist) > 0)
{
return view('client-database')->with($select_clientlist);
}
else
{
return view('client-database')->withMessage('No Details Found');
}
}
I want to show the values coming in $select_clientlist variable. Below is the code in my blade file:-
#foreach($select_clientlist as $clientlist)
{{$clientlist->firstname}}
#endforeach
And below is the route file code:-
Route::post('client_list_ajax','ClientDatabase\ClientdatabaseController#ClientListReviews');
I am receiving error.
What am I doing wrong?
Pass the variable using compact method
return View::make('myviewfolder.myview', compact('view1','view2','view3'));
view1,view2,view3 are variable names
Since you only pass the variable when there is records wrap your for each inside isset
if (isset($select_clientlist)) {
foreach($select_clientlist as $clientlist) {
}
}
your query should be like this . you may be forget SELECT statement
$select_clientlist = DB::table('users_booking')->select('*')->where('service_provider', '=', 1)->get();
Either use as
return view('client-database')->with('select_clientlist',$select_clientlist);
Or
return view('client-database',compact('select_clientlist'));
Also add in select_clientlist else part to prevent undefined error
public function ClientListReviews()
{
// to show client list get data from users booking table
$select_clientlist =
DB::table('users_booking')>where('service_provider', '=', 1)->get();
if(count($select_clientlist) > 0)
{
return view('client-database')->with('select_clientlist',$select_clientlist);
}
else
{
$select_clientlist = [];
return view('client-database')->with('select_clientlist',$select_clientlist)->withMessage('No Details Found');
}
}
OR check by isset($select_clientlist) in blade file
$__currentLoopData = isset($select_clientlist)?$select_clientlist:[];
Pass that variable to your view either way .. it should be a collection. If there are no records, it is just empty. The foreach wont run if its empty. Its as simple as that. No need to check if anything is set or is empty etc... just always pass that collection.
public function ClientListReviews()
{
$select_clientlist = DB::table('users_booking')->where('service_provider', 1)->get();
$view = view('client-database', compact('select_clientlist'));
if ($select_clientlist->isEmpty()) {
$view->with('message', 'No Details Found');
}
return $view;
}

Delete one of data JSON from Database

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

Unable to fetch value at view.Laravel

I'm trying to fetch values at view passed from controller.
In my controller my syntax are:
public function index()
{
$vehicles=vehicles::orderBy('created_at', 'desc')->get();
// return $vehicles;
$ad=ads::orderBy('views','desc')->get();
// return $ad;
foreach ($ad as $ads) {
# code...
$popularvehicle[]=vehicles::where('id',$ads->id)->get();
// echo $popularvehicle;
}
return view('index',compact('vehicles','popularvehicle'));
}
In my views i've tried following:
#foreach($popularvehicle as $popularvehicle)
{{$popularvehicle->vname}}
#endforeach
It gives an error of Undefined property: Illuminate\Database\Eloquent\Collection::$vname
I've also tried {!!$popularvehicle['vname']!!}. But it throws error like undefined index.
When i echo {!!$popularvehicle!!} it gives all the values required like [{"id":3,"vname":"Pulsar","lotno":"Ba 25 Pa","engine":"150","mileage":"35","kilometers":25000,"price":"120000","negotiable":"Yes","vcondition":"New","used":"3 month","manufacture_year":"2015","description":"Almost New","Company_cid":1,"Users_id":1,"Vehicle_Type_id":1,"created_at":"2017-01-12 15:08:41","updated_at":"2017-01-12 15:08:41"}].
How can i fetch the values of $popularvehicle? Can anyone help me? Will converting array to object help solve this problem. If yes, how can i do so?
The error is because -> is trying to point to the property of object $popularvehicles[] is an array:
$ads=ads::orderBy('views','desc')->get();
foreach ($ads as $ad) {
$popularvehicles[]=vehicles::where('id',$ad->id)->get()->toArray();
}
and then,
#foreach($popularvehicles as $popularvehicle)
#foreach($popularvehicle as $vehicle)
{{$vehicle['vname']}}
#endforeach
#endforeach
Note the changes made for naming conventions. Also, Model name is good to be singular.
Consider plural name
$popularvehicles = array();
foreach ($ad as $ads) {
$popularvehicles[]=vehicles::where('id',$ads->id)->get();
}
return view('index',compact('vehicles','popularvehicles'));
And use in view
#foreach($popularvehicles as $popularvehicle)
{{$popularvehicle->vname}}
#endforeach
Try this:
Controller:
$popularvehicle = vehicles::where('id',$ads->id)->get();
// If you use $popularvehicles[] then you have to use one extra foreach() to retrieve the columns
View:
#foreach($popularvehicle as $vehicle)
{{$vehicle->id}} // for id
{{$vehicle->vname}} // for name
#endforeach
Try this:
public function index()
{
$vehicles = vehicles::orderBy('created_at', 'desc')->get();
// return $vehicles;
$ads = ads::orderBy('views','desc')->get();
// return $ad;
foreach ($ads as $ad) {
# code...
$popularvehicles[]=vehicles::find($ad->id);
}
return view('index',compact('vehicles','popularvehicles'));
}
And in your view:
#foreach($popularvehicles as $popularvehicle)
{{$popularvehicle->vname}}
#endforeach

How To Fetch And Display Multiple Rows?

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 need to call a controller function inside a view -Codeigniter

I need to call a function from view to echo a value. I use following code,
Controller (test_controller)
public function displayCategory()
{
$this->load->model('Model_test');
$data['categories'] = $this->Model_test->getCategories();
$this->load->view('test_view', $data);
}
public function display($id)
{
$this->load->model('Model_test');
$name= $this->Model_test->getName($id);
return $name;
}
Model (Model_test)
function getCategories() {
$query = $this->db->query("SELECT * FROM category");
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
function getName($userId) {
$query = $this->db->query("SELECT name FROM user where id = '$userId' ");
if ($query->num_rows() > 0) {
return $query->row()->name;
} else {
return NULL;
}
}
View
<div id="body">
<?php
foreach ($categories as $object) {
$temp = $this->test_controller->display($object->id);
echo $object->title . " ". $object->no . $temp . '<br/>';
}
?>
</div>
but some error when running the code.
error Message: Undefined property: CI_Loader::$test_controller in view
I am not sure if you use CodeIgniter 2 or 3.
Anyway, basically you don't want to use anything inside View files except perhaps helper function(s) or some kind of "presenter" layer (that should be called inside controller I guess).
Solution using Join
Go and read this manual page and search for join. There you can learn about implementation of SQL join directive.
You want to modify this (getCategories()) function so it returns data that you require
function getCategories() {
$this->db->select('category.title, category.no, user.name as username')
->from('category')
->join('user', 'user.id = category.id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
and in view you can get your username like this
foreach ($categories as $object) {
echo $object->title . " ". $object->no . $object->username . '<br/>';
}
I am not 100% sure so please post comments I will edit this answer later.
Solution "breaking rules"
https://stackoverflow.com/a/24320884/1564365
general notes
Also consider naming your tables using plural so categories, users...
Also it is a bad practise to use "category.id as user.id" (storing user id inside category table in "id" field) instead you shold use either a pivot table or in case of 1:1 relation field "user_id".

Categories