How can I get and display each element from the product json data type in laravel.
"category" => accessories
"product" => "["eyewear", "watches", "shoes"]"
Data has been saved correctly using
$casts = [
'product' => 'array'
];
When I try to display, I get the list like show down
Category :
accessories | Product : ["eyewear", "watches", "shoes"]
Is it possible to get result like
Category : accessories | Product: eyewear *****
Category : accessories | Product: watches *****
Category : accessories | Product: shoes *****
Thanks for your help
Provided the JSON has indeed been successfully converted to an array (in this case to a 1D array), you can get the value for each index like you normally would with any other array:
{{ $product[0] }}
If you want to create some sort of list out of it, you can just loop through it using foreach:
#foreach($product as $p)
{{ "Category: " . $category }}
{{ "Product: " . $p }}
#endforeach
If I understand correctly you already have some query results stored in $items, where you have stored values for category_id and product (based on your original post I assume you've already converted the JSON to an array using the $casts property inside your model, alternatively you could use PHP function json_decode()). If you want to loop through $items, it would probably look like this:
#foreach($items as $item)
#foreach($item['product'] as $product)
{{ "Category: ".$item['category_id']." | Product: ".$product }}
</br>
#endforeach
#endforeach
The code above should output something like this:
Category: 1 | Product: eyewear
Category: 1 | Product: watches
Category: 1 | Product: shoes
Category: 2 | Product: a
Category: 2 | Product: b
Category: 2 | Product: c
Related
I Have 2 tables first client_group with data like below
second table client
in Controller I have code like below:
$client = DB::table('client_group')
->where('client_group.user_id','=',$user_id)
->join('client','client_group.client_id','=','client.id')
->select('client_group.*',
'client.client_email',
)->get();
return view('client.group', ['client'=>$client]);
From this query i have results like below:
Illuminate\Support\Collection {#1278 ▼
#items: array:2 [▼
0 => {#1188 ▼
+"id": 1
+"groupname": "testowa grupa"
+"user_id": 2
+"client_id": "4,5,6"
+"created_at": "2021-02-08 13:47:03"
+"updated_at": "0000-00-00 00:00:00"
+"client_email": "test1#wp.pl"
}
1 => {#1123 ▼
+"id": 9
+"groupname": "test2"
+"user_id": 2
+"client_id": "8,14,22"
+"created_at": "2021-01-04 15:19:33"
+"updated_at": null
+"client_email": "test3#wp.pl"
}
]
}
client_id is always in one column ("client_id": "8,14,22") because is added like this.
Now is my question and issues,
how to change view and query to get insted of one email all clients emails? based on client_id, below current view.
At the moment I have only one email first from client_id lists
<td>{{ $row->groupname }}</td>
<td>{{ count(explode(',',$row->client_id)) }}</td>
<td>{{ $row->client_email }}</td>
First of all , use FIND_IN_SET to join table with comma separated values.
Something like this-
DB::table('client_group')
->where('client_group.user_id','=',$user_id)
->join('client',\DB::raw("FIND_IN_SET(client.id,
client_group.client_id)"),">",\DB::raw("'0'"))
->select('client_group.*', \DB::raw("GROUP_CONCAT(client.client_email)
as client_emails"))
->get();
And in the blade file you can get client emails like this-
{{ $row->client_emails }}
I have a json field in my database name is permissions {"read": true, "create": true}. Now, I want to show this in my blade view. I had try this way but it's show an error.
#foreach($users as $user)
<tr>
<td>{{$user->roles->permissions}}</td>
</tr>
#endforeach
show this Error Message.
Property [permissions] does not exist on this collection instance.
User Model
public function roles()
{
return $this->belongsToMany(Role::class,'user_roles');
}
I tested this scenario and was OK . i hope usefull for you :
my route :
Route::get('/test', function (Request $request) {
$users=\App\User::with('roles')->get();
return view('welcome',compact('users'));
});
define roles method inside user model :
public function roles()
{
return $this->belongsToMany(Role::class,'user_roles');;
}
and get permissions in view :
#foreach($users as $user)
#foreach($user->roles as $role)
<tr>
<td>{{$role}}</td>
</tr>
#endforea
#endforeach
I test with these tables
user_roles
user_id | role_id
-----------------
1 | 2
1 | 2
roles:
id | permissions
-----------------
1 | {"read": true, "create": true}
2 | {"read": true, "create": false}
users:
id | name | email | password | remember_token | created_at|updated_at
----------------------------------------------------------------------
1 | alihossein|ali#gmail.com|XXXXX|UIWKK67ei5CCuiv1OXilKY2aRkTfSqGLpqJch0F9YmenGSorsQGHVvWiX6kP| 2018-05-28 22:25:14 | 2018-05-28 22:25:14
I am building a popover, in which you can tick checkboxes. The options and choices are stored in a manytomany relationship inside a mysql database.
[ ] option A
[x] option B
[ ] option C
There are 3 tables. sphotos, sphoto_feedback and sphoto_has_feedbacks. sphoto_has_feedbacks stores a sphoto_id, a sphoto_feedback_id and a user_id, to reference the user that has submitted the voting.
sphoto
id | status_id | ...
1 | ...
sphoto_feedback
id | name | ...
11 | Quality |
12 | Creative |
sphoto_has_feedbacks
id | sphoto_id | sphoto_feedback_id | user_id
1 | 1 | 11 | 9999
The Input is user_id => 9999 and sphoto_id => 1. The desired output would be an array, which has all sphoto_feedback entrys, with a boolean variable, like this:
$output = [
"0" => [
"id" => 11,
"name" => "Quality",
"checked" => true
],
"1" => [
"id" => 12,
"name" => "Creative",
"checked" => false
]
]
It would look like this:
[x] Quality <-- stored in sphoto_feedback, also stored in sphoto_has_feedbacks with reference to user
[ ] Creative <-- stored in sphoto_feedback
I want to retrieve all the options from the database and check, if the user has already voted on the options or not.
I know how to do it in PHP with 2 querys, but I'd like to use just one query and would like to know if this is possible.
Use a LEFT JOIN to join the sphoto_feedback and sphoto_has_feedback tables, returning NULL for all the rows in the first table that don't have a match in the second table.
SELECT f.id, f.name, shf.id IS NOT NULL AS checked
FROM sphoto_feedback AS f
LEFT JOIN sphoto_has_feedback AS shf
ON f.id = shf.sphoto_feedback_id
AND shf.sphoto_id = 1 AND shf.user_id = 9999
I have one games table and two tables to store their scores, game_scores and thirdparty_game_scores with exactly the same structure, something like that:
-------------------------GAMES-------------------------
slug | title | technology | (other non-relevant fields)
-------------------------------------------------------
----------------------GAME SCORES----------------------
id (PK) | game_slug | user | team | score | timestamp
-------------------------------------------------------
----------------THIRDPARTY GAME SCORES-----------------
id (PK) | game_slug | user | team | score | timestamp
-------------------------------------------------------
And their Models like:
class GameScores extends BaseGamesModel {
public function initialize() {
parent::initialize();
$this->belongsTo( 'game_slug', 'Games', 'slug' );
$this->skipAttributes(array('creation_time', 'last_modified'));
}
}
I'm building a weekly ranking with game scores stored only on game_scores:
$ranking = GameScores::sum(
array(
"column" => "score",
"conditions" => $conditions,
"group" => "team",
"order" => "sumatory DESC"
)
);
Is there any way to create a Model that concatenates all data from game_scores and thirdparty_game_scores to create the same ranking without any extra effort?
Thank you so much!
You can set the source table dynamically in your model. See Can I build a Model for two Tables on PhalconPHP?
You should use the setSource() method and put your condition in there, e.g.:
$source = 'default_table';
if (class_name($this) === 'A') {
$source = 'A_table';
}
return $source;
I am trying to generate nested json data like in this example from one mysql table.
var data = {
"62" : {
"section" : "bodyImage",
"img" : "imageurl/image62.png",
"label" : "blue",
"price" : "100"
},
"63" : {
"section" : "bodyImage",
"img" : "imageurl/image63.png",
"label" : "red",
"price" : "120"
}
}
62 and 63 are from the row data_id in the following table:
+-----------+------------+-------------------------+-------+---------+
| data_id | section | img | label | price |
+-----------+------------+-------------------------+-------+----------
| 62 | bodyImage | imagpath/image62.png | blue | 100 |
| 63 | bodyImage | imagpath/image62.png | red | 120 |
+-----------+------------+-------------------------+-------+---------
+
This is the php file with the query:
$result = mysql_query("SELECT data_id, section, img, label, price FROM table WHERE active != 'no'");
$data = array();
while($row=#mysql_fetch_object($result)) {
$data[] = array (
'section' => $row['sub_section'],
'img' => $row['big_image'],
'label' => $row['label_client_en'],
'price' => $row['price']
);
}
echo json_encode( $data );
I cannot get it working. Please help me with the right syntax for the multi-dimensional array.
You cannot json_encode "sub arrays" directly on the main array
You must do json_encode for each array in your while:
$data[] = json_encode(array (
'section' => $row['sub_section'],
'img' => $row['big_image'],
'label' => $row['label_client_en'],
'price' => $row['price']
));
And then you must also encode the main array as you already do.