last day (14 days later) » 

10:53 AM
1
A: Query two tables with Laravel and two WHERE conditions

Calin Blaga$query = Order::select(DB::Raw('payments.processed')) ->join('payments', 'orders.user_id', '=', 'payments.userID') ->where('orders.user_id', 2) ->where('payments.userID', 2) ->get(); It's almost the same

 
'Invalid argument supplied for foreach() in my view ... I have there @foreach($orders as $order)
 
dump dd($orders) and show as the result
 
I've added dump of orders. I can see ["processed"]=> string(1) "1" in the dump which is the value in database
 
Please share the full dump result
 
This is the full dump of $orders
 
10:53 AM
It must be object(Illuminate\Database\Eloquent\Collection)
 
It is object(Illuminate\Database\Eloquent\Collection)#264 (1) {...
 
we can discuss here
 
This is:

`object(Illuminate\Database\Eloquent\Collection)#264 (1) { ["items":protected]=> array(1) { [0]=> object(Order)#260 (20) { ["table":protected]=> string(6) "orders" ["primaryKey":protected]=> string(8) "order_id" ["connection":protected]=> NULL ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(1) { ["processed"]=> string(1) "1" } ["original":protected]=> array(1) { ["processed"]=> string(1) "1" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["a
full dump which I see on the page
 
and you get Invalid argument supplied for foreach() trying to iterate this object?
 
Yes
 
10:55 AM
put ->toArray() after get()
 
got this production.ERROR: exception 'ErrorException' with message 'Trying to get property of non-object'
but after forech
<td>{{ $order->order_id }}</td>
where I start to load information
here
 
yes because now you have $order['order_id']
toArray forces the result as array not as object
 
now is 'Undefined index: order_id
 
please show me the result of dd($orders) now
 
array(1) { [0]=> array(1) { ["processed"]=> string(1) "1" } }
 
11:01 AM
Order::select(DB::Raw('orders.order_id, payments.proccessed'))
->join('payments', 'orders.user_id', '=', 'payments.userID')
->where('orders.user_id', 2)
->where('payments.userID', 2)
->toArray();
you need to include the column in your query
orders.order_id
 
just a sec to try
 
it's get()->toArray()
Order::select(DB::Raw('orders.order_id, payments.proccessed'))
->join('payments', 'orders.user_id', '=', 'payments.userID')
->where('orders.user_id', 2)
->where('payments.userID', 2)
->get()
->toArray();
 
Call to a member function getOrderData() on a non-object'
how to write this now
 
have you used my last one?
 
@foreach($order->getOrderData() as $itemId => $item)
<?php
$price = doubleval($item->price) * doubleval($item->quantity);
$total += $price;
?>
<li><strong>{{ $item->title }}</strong> x {{ $item->quantity }} ({{ $price }} $)</li>
@endforeach
I have this foreach inside
 
11:04 AM
why getOrderData() ?
 
It's from Order model
public function getOrderData($asArray = false) {
    return json_decode($this->data, $asArray);
}
 
then you must use get without toArray()
and $order->order_id not $order['order_id']
 
and - 'Invalid argument supplied for foreach()
:(
 
using this:
Order::select(DB::Raw('orders.order_id, payments.proccessed'))
->join('payments', 'orders.user_id', '=', 'payments.userID')
->where('orders.user_id', 2)
->where('payments.userID', 2)
->get()
?
 
yes
 
11:07 AM
please show me all the code from blade where you're using $orders
 
got error on first $order->order_id in the foreach loop
@if(count($orders) > 0)
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Order data</th>
<th>Created at</th>
<th>Paid?</th>
</tr>
</thead>
<tbody>
@foreach($orders as $order)

<?php $total = 0; ?>
<tr class="info">
<td>{{ $order->order_id }}</td>
<td>
<ul>
@foreach($order->getOrderData() as $itemId => $item)
<?php
$price = doubleval($item->price) * doubleval($item->quantity);
$total += $price;
?>
<li><strong>{{ $item->title }}</strong> x {{ $item->quantity }} ({{ $price }} $)</li>
 
remove for now the second foreach
and see if the problem is there
 
yes
it's working
without this foreach
 
no it's not :)
now
 
when I removed the @foreach($order->getOrderData() as $itemId => $item) .... page is loaded
 
11:11 AM
now instead of the second foreach put this
<ul>
<?php
var_dump($order->getOrderData());
?>
</ul>
 
NULL
But when I run it with my query where is only order table is showing me all the info
with this one: $orders = self::$user->orders()->orderBy('order_id', 'asc')->get();
 
what do you expect from this:
public function getOrderData($asArray = false) {
return json_decode($this->data, $asArray);
}
where do you have price, quantity, title columns?
in which table?
 
{"21":{"title":"Testing prices","description":"Testing prices","quantity":1,"image":"\/img\/noimage.png","price":"500.00"},"shipping":{‌​"quantity":1,"image":"\/img\/noimage.png","description":"","title":"Normal Delivery","price":0}}
table orders
column data
saves this when order is made
 
then you can try :
public function getOrderData($data) {
return json_decode($data);
}
@foreach($order->getOrderData($order->data) as $itemId => $item)
<?php
$price = doubleval($item->price) * doubleval($item->quantity);
$total += $price;
?>
<li><strong>{{ $item->title }}</strong> x {{ $item->quantity }} ({{ $price }} $)</li>
@endforeach
 
'Invalid argument supplied for foreach()
here: @foreach($order->getOrderData($order->data) as $itemId => $item)
 
11:20 AM
have you modyfied the getOrderData implementation?
 
i didn't touch anything other
only what you telling me here
 
public function getOrderData($data) {
return json_decode($data);
}
did you updated this function
 
yes
 
put this inside first foreach
<?php
$order_data = $order->getOrderData($order->data);

var_dump($order->data, $order_data);
?>
and remove the second foreach for now
 
NULL NULL
 
11:24 AM
omg, change the query to
Order::select(DB::Raw('orders.*, payments.proccessed'))
->join('payments', 'orders.user_id', '=', 'payments.userID')
->where('orders.user_id', 2)
->where('payments.userID', 2)
->get()
and payments.* if you need all the data from payments table
 
sec
 
in that select you must specify all the needed columns
it's just the orders.order_id -> orders.*
 
ok, now the data is there
 
all done then?
 
big question now is how to make this 2 to be current user
 
11:28 AM
are you using auth?
the current logged user?
 
I'm not sure
this is when user loggin
$validatorRules = array(
'captcha' => 'required|captcha',
'username' => 'required|alpha_dash',
'password' => 'required|min:6'
);

Input::merge(array_map('trim', Input::all()));
$validator = Validator::make(Input::all(), $validatorRules);

if ($validator->fails()) {
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}

$user = User::where('username', Input::get('username'))->first();
if (!$user) {
$validator->messages()->add('username', 'Invalid login or password.');
and the class
class User extends Eloquent {

/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';

/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password');
protected $primaryKey = 'user_id';
}
 
that seems to be where a new user is added not logged
 
omg sorry
wrong controller
 
AuthController
 
public static function isLoggedIn() {
$user = Session::get('user', null);
if ($user !== null) {
return true;
} else {
return false;
}
}

public static function isAdmin() {
if (!self::isLoggedIn()) {
return false;
}

$user = self::getCurrentUser();
return (bool)$user->is_admin;
}

public static function getCurrentUser() {
if (!self::isLoggedIn()) {
return null;
}

$user = Session::get('user', null);
if (self::$user == null) {
$user = User::where('user_id', $user['user_id'])->first();
self::$user = $user;
I'm still not that familiar with laravel and using some tutorials and sometimes i'm not sure what really is going on
but this is in my BaseController
+
/* @var User */
protected static $user;
at the top
 
11:33 AM
Order::select(DB::Raw('orders.*, payments.proccessed'))
->join('payments', 'orders.user_id', '=', 'payments.userID')
->where('orders.user_id', YourController::getCurrentUser()->user_id)
->where('payments.userID', YourController::getCurrentUser()->user_id)
->get();
change YourController with the actual controller name
 
YourController = BaseController?
where it's checking logged_in...is_admin ?
 
from where did you copied the code?
 
which I posted
 
yes
 
yes BaseController
 
11:35 AM
then yes it's BaseController
 
not good
 
what's not good?
 
I just take all orders from database ... for all users
and all of them show that paid = 1
 
don't understand, you need to fetch orders based on user or not?
 
yes
currently I'm logged with user_id=2
this user has only 1 order
 
11:38 AM
what BaseController::getCurrentUser() returns?
 
but when I put BaseController::getCurrentUser()->user_id to the query I've got results with all orders from database
how to dump BaseController::getCurrentUser()?
 
var_dump(BaseController::getCurrentUser()->user_id)
somewhere
 
ok, i saw the problem
some cache or something
logged out and logged in again and now shows correct order
but
user_id has now 2 orders
one is paid and one isn't
should show me 1 for the paid and 0 for unpayed one
but is 1 for both
 
I don't know what your's orders table content
 
orders table doesn't have anything for the pay/not pay .. have order_id, user_id, data, address, created_at
 
11:42 AM
the payments
where are you displaying proccessed ?
 
payments are saved in payment table
 
where are you displaying proccessed ?
 
in the loop
first one
                    <td class="text-center">
                        {{ $order->processed }}
                    </td>
also I just noticed that I've got double results
I get 1 product twice
one paid=1
and second time paid=0
hm
 
put the whole content of the blade
 
@extends('layouts.master')
@section('title', 'Orders')

@section('content')
<h3>My Orders</h3>
<p>At this page you can view you orders history.</p>
<hr />
@if(Session::has('message'))
<div class="alert alert-info">{{ Session::get('message') }}</div>
<hr />
@endif
@if(count($orders) > 0)
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Order data</th>
<th>Created at</th>
<th>Paid?</th>
</tr>
</thead>
<tbody>
@foreach($orders as $order)

<?php $total = 0; ?>
 
11:46 AM
sorry but there is no proccessed
ah wait
 
is processed with one C :)
 
it is wrong in the query
 
i've changed in there
 
and?
 
every order is doubled on the page
one paid
one not paid
 
11:49 AM
do you see order_id twice?
 
yes
 
please make a screenshot
 
just a sec
 
what is the output of var_dump($orders->count())?
 
int(4) int(4) int(4) int(4)
for 2 orders
 
11:55 AM
did you placed the query inside the controller?
and pass it to the view?
 
yes,
class UsersController extends BaseController
{
public function viewOrders() {
/// query
return View::make('site.users.orders', [
'orders' => $query
]);
}
}
 
put var_dump($orders->count()) bofore the return
 
I extend basecontrolloer
 
int(4)?
you have to be faster cause I don't have that much time :)
 
before return?
inside the controller?
 
11:59 AM
yes
 
int(4)
 
so the user has 4 orders
 
but in database he has 2
 
foreach($orders as $order) { var_dump($order_id) }
put this instead of var_dump($orders->count())
$order->order_id
 
in the blade?
 
12:01 PM
in controller
foreach($orders as $order) { var_dump($order->order_id) }
the output is?
 
in controller before return I've got error
syntax error, unexpected '}''
 
then put a ; after var_dump
:)
 
yes yes :)
 
you're new to PHP?
 
string(3) "142" string(3) "142" string(3) "143" string(3) "143"
not that much
 
12:04 PM
can you dump the orders table?
 
so in database orders there is one time order_id=142 and one time order_id=143
 
and send me the sql file
 
sec
 
what the query now?
do you have a order_id in the payments table too?
 
$query = Order::select(DB::Raw('orders.*, payments.processed'))
->join('payments', 'orders.user_id', '=', 'payments.userID')
->where('orders.user_id', BaseController::getCurrentUser()->user_id)
->where('payments.userID', BaseController::getCurrentUser()->user_id)
->get();
no
 
12:06 PM
did you managed to export the orders table?
I suppose it contains testing data
right?
 
yes
CREATE TABLE IF NOT EXISTS `orders` (
`order_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`data` text,
`address` text,
`created_at` timestamp NULL DEFAULT NULL,
`price` double(20,8) DEFAULT '0.00000000',
PRIMARY KEY (`order_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=144 ;

--
-- Dumping data for table `orders`
--

INSERT INTO `orders` (`order_id`, `user_id`, `data`, `address`, `created_at`, `price`) VALUES
(142, 3, '{"21":{"title":"Testing prices","description":"Testing prices","quantity":1,"image":"\\/img\\/noima
 
can't import it
#1136 - Column count doesn't match value count at row 2
 
INSERT INTO `orders` (`order_id`, `user_id`, `data`, `address`, `created_at`, `price`) VALUES
(142, 3, '{"21":{"title":"Testing prices","description":"Testing prices","quantity":1,"image":"\\/img\\/noimage.png","price":"500.00"},"shipping":{"quantity":1,"image":"\\/img\\/noimage.png","description":"","title":"Normal Delivery","price":0}}', 'dsadsadasdasdasdsadsa', '2016-06-17 13:21:52', 500.00000000),
(143, 3, '{"20":{"title":"Product with Price","description":"Product with Price","quantity":1,"image":"\\/img\\/noimage.png","price":"0.50"},"shipping":{"quantity":1,"image":"\\/img\\/noimage
try this
 
please dump payments too
 
just a min because there has some data.. not test data
will send yo unow
 
12:14 PM
get rid of sensible data after dump
 
yes
just a sec
can you try this
CREATE TABLE IF NOT EXISTS `payments` (
`paymentID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`orderID` varchar(50) NOT NULL DEFAULT '',
`userID` varchar(50) NOT NULL DEFAULT '',
`countryID` varchar(3) NOT NULL DEFAULT '',
`amountUSD` double(20,8) NOT NULL DEFAULT '0.00000000',
`txDate` datetime DEFAULT NULL,
`processed` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`paymentID`),
KEY `userID` (`userID`),
KEY `countryID` (`countryID`),
KEY `orderID` (`orderID`),
KEY `amountUSD` (`amountUSD`),
 
it's ok, just a sec
the join is wrong
change it to ->join('payments', 'orders.order_id', '=', 'payments.orderID')
 
no data to display
 
and since a payment belongs to order you can remove the userID from payment and get it trought orders
 
oh
sec
 
12:22 PM
no data?
string '143' (length=3)

string '142' (length=3)
 
now is ok
 
this is what I get
 
wow
finally
 
your database needs a refactor :)
the code as well
 
I know
 
12:23 PM
do it then :P
 
just getting familiar with laravel and mvc frameworks at all
 
ok
sya
 
Thank you very very much
 
I'll modify my answer and you can accept it
 
already accepted
hm i just saw
what you mean with this
and since a payment belongs to order you can remove the userID from payment and get it trought orders
i can remove ->where('payments.userID', BaseController::getCurrentUser()->user_id)
 
12:25 PM
so,
 
from query
 
no np
no
 
do you need userID in the payments table?
 
yes
 
12:26 PM
why?
 
because the payment is over API
api update this table
 
and?
 
I just pull the info when is paid and when npo
 
you can send the orderID to API
and update on API's response based on orderID
this doesn't looks that nice
->where('orders.user_id', 3)
->where('payments.userID', 3)
 
yes I send order_id, price, user_id to api
 
12:28 PM
so on their response you're using the order_id?
 
then when this user pay i've got update in database
yes
 
:)
so once again where do you need the userID?
and you don't have to send the user_id to the API
 
I need
 
in orders table you have user_id
 
order_id+user_id
to api
 
12:30 PM
I doubt, but...
Any other question, because else I off
?
 
anyway most of this is for learning purpose
i don't have other questions
and thank you again!
 
ok, then have a great weekend
 
you too
 

last day (14 days later) »