Cannot retrieve data from database using first() method - php

I have this routing:
Route::get('/item/{item_id?}',['uses'=>'ItemController#get_item_view']);
I want to redirect to the first item if no item ID is given.
public function get_item_view($id = null)
{
if($id == null)
{
#This doesnt work
$selected_item = Item::where('item_id',Auth::user()->item_id)->first();
}
else
{
#This works
$selected_item = Item::where('id',$id)
->where('item_id',Auth::user()->item_id)
->first();
}
if($selected_item === null)
{
return redirect('/');
}
return view('auth.forms.item')->with('item',$selected_item);
}
If I introduce an ID (www.myproject.com/item/2), the page works perfectly, but if I don't, and try to get just the first of the list just to generate the page. I expect www.myproject.com/item to give me the first item.
This is the error I get:
Trying to get property of non-object (View:
/var/www/myproject/resources/views/auth/forms/item.blade.php)
and when I use dd($selected_item) on both cases I get the same type of object. I have no idea why one is working and the other one isn't.

if you don't provide item id then it'll be null,
$selected_item = Item::where('item_id',null)->first();
if you want to list first item just do
if($id == null)
{
#This doesnt work
$selected_item = Item::all()->first();
}

Make sure Auth::user()->item_id has a value. the error seems to be generating from it.
you can do dd(Auth::user()->item_id) to check it

Related

How can I use null or empty in Laravel Controllers?

I want to delete a row from likes_table if the table already has a row which contain requested shop_id and user_id combination.
Or, make a new row if it not exists.
However, this following code always executes delete method (returns 204) even if there is no row.
Would you give me any advice?
public function store(Request $request)
{
$liked_id = Like::where('shop_id', $request->shop_id)
->where('user_id', $request->user_id)
->get('id');
$liked = Like::find($liked_id);
if (!empty($liked)) {
Like::where('shop_id', $request->shop_id)
->where('user_id', $request->user_id)->delete();
return 204;
} else {
return Like::create($request->all());
}
}
I solved it myself.
OK:
if ($liked->isEmpty())
NG:
if (!empty($liked))

Why model/variable keeps its value?

I have problem with my code in Laravel Framework. What I am trying to do is sell method inside model. The problem is that $variable keeps its value untill next code execution. How I should make it so it's gonna work like I want to?
/// Model method.
public function Sell()
{
$this->UserData->increment('gold', ($this->ItemData->price / 100) * 80);
$this->delete();
return null;
}
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->ItemData->name; /// Returns full data about model even if I deleted it/sold. After next refresh, returns null/error.I want it to return null since beginning.
Even if you have deleted a record from a database by $this->delete(), $user_item variable still holds a reference to the filled model until the script ends or you destroy the variable.
It seems that you want to return a result of the sell() function. In your case it would be
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->Sell();
I don't know what you are trying to do but below code will solve your issue -
/// Model method.
public function Sell()
{
$this->UserData->increment('gold', ($this->ItemData->price / 100) * 80);
$this->delete();
$this->ItemData = $this->ItemData->fresh()
return null;
}
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->ItemData->name; /// Returns full data about model even if I deleted it/sold. After next refresh, returns null/error.I want it to return null since beginning.

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

Updating line items through code in WooCommerce

I'm trying to make an interface where I can edit some of the metadata attached to a lineitem. I've tried using update_post_meta() on the line item itself, however that returns bool(false). How can I update the line item meta data manually?
Thanks!
so I managed to figure it out. I wrote a small function that's below. So, all you need to do is load up the order using the API, parse through each line item and you can call wc_update_order_item_meta. The only thing is, you need to know the variation ID of the item being sold if you only want to update a specific item.
function update_order_item_meta($orderID, $variationID, $metaID, $metaValue) {
$order = returnWC_API()->get_order($orderID)->{'order'};
if(!$order) {
return false;
}
if($variationID == "all") {
foreach ($order->{'line_items'} as $line_item) {
if(!wc_update_order_item_meta($line_item->{'id'}, $metaID, $metaValue)) {
return false;
}
}
return true;
}
foreach ($order->{'line_items'} as $line_item) {
if($line_item->{'product_id'} == $variationID) {
return wc_update_order_item_meta($line_item->{'id'}, $metaID, $metaValue);
}
}
}

Codeigniter passing parameter to controller index

I'm building a tutorialsystem with codeigniter and would like to achieve the following URL structure:
/tutorials --> an introduction page with the list of all the categories
/tutorials/{a category as string} --> this will give a list of tutorials for the given category, e.g. /tutorials/php
/tutorials/{a category as string}/{an ID}/{tutorial slug} --> this will show the tutorial, e.g. /tutorials/php/123/how-to-use-functions
/tutorials/add --> page to add a new tutorial
The problem is that when I want to use the first two types of URLs, I'd need to pass parameters to the index function of the controller. The first parameter is the optional category, the second is the optional tutorial ID. I've did some research before I posted, so I found out that I could add a route like tutorials/(:any), but the problem is that this route would pass add as a parameter too when using the last URL (/tutorials/add).
Any ideas how I can make this happen?
Your routing rules could be in this order:
$route['tutorials/add'] = "tutorials/add"; //assuming you have an add() method
$route['tutorials/(:any)'] = "tutorials/index"; //this will comply with anything which is not tutorials/add
Then in your controller's index() method you should be able to work out whether it's the category or tutorial ID is being passed!
I do think that a remap must be of more use to your problem in case you want to add more methods to your controller, not just 'add'. This should do the task:
function _remap($method)
{
if (method_exists($this, $method))
{
$this->$method();
}
else {
$this->index($method);
}
}
A few minutes after posting, I think I've found a possible solution for this. (Shame on me).
In pseudo code:
public function index($cat = FALSE, $id = FALSE)
{
if($cat !== FALSE) {
if($cat === 'add') {
$this->add();
} else {
if($id !== FALSE) {
// Fetch the tutorial
} else {
// Fetch the tutorials for category $cat
}
}
} else {
// Show the overview
}
}
Feedback for this solution is welcome!

Categories