laravel- get value from json decode array - arrays

I have an array like this, after I use json_decode ($json = json_decode($items, true);), the result looks like this
array:1 [
61 => array:53 [
"id" => 2790
"name" => "ABC"
"created_at" => "2020-12-04 09:43:57.317"
"updated_at" => "2021-02-16 16:47:16.167"
"deleted_at" => null
"remark" => null
]
]
And Iwant to get the value from field name, how to do it in Laravel??
I try like this but, get error Undefined offset name
dd($array['name']);

The correct way to access the element you're trying to get to is $array[61]["name"];
$array[61] will give you:
array:53 [
"id" => 2790
"name" => "ABC"
"created_at" => "2020-12-04 09:43:57.317"
"updated_at" => "2021-02-16 16:47:16.167"
"deleted_at" => null
"remark" => null
]
Then you can use ["name"] to access the value you're after.

Related

Get key values from a collection in Laravel

I have this collection
1 => {#27
+"id": 1
+"name": "Zel"
+"age": "43"
}
2 => {#28
+"id": 2
+"name": "Kol"
+"age": "56"
}
3 => {#29
+"id": 3
+"name": "Mil"
+"age": "32"
}
and I would like to return an array with the key values as a string like this:
[
'id',
'name',
'age',
]
Can someone help me with that, please?
use array_keys :
$keys = array_keys($collection->first());
Laravel collection has a keys() method you could simply use it like this:
$keys = $collection->keys();
$get = $keys->all();
It is all clearly written in the Laravel Documentation
EDIT
After looking at your edit, my first consideration would be that if your collection is consistent you could get the first one and subsequently get the keys from there on:
$keys = $collection->first();
$get = $keys->keys()->all();
Or simply put $collection->first()->keys()->all();
EDIT
Here is how i was able to reproduce your problem:
$collection = collect([
[
'id' => 1,
'name' => 'Zel',
'age' => 43
],
[
'id' => 2,
'name' => 'Kol',
'age' => 56
],
[
'id' => 3,
'name' => 'Mil',
'age' => 32
],
]);
$keys = collect($collection->first())->keys()->all();
Here is the Result I got:
array:3 [▼
0 => "id"
1 => "name"
2 => "age"
]
If it still returns a collection or an object based on your last comment, you could try any one of these:
$keys = $keys->toArray();
$keys = collect($keys)->toArray();

Laravel notifications are saved in the database with null user_id

When I try to save a notification for a user, the user_id column is always NULL in the database.
I have the Notifiable trait assigned to the User model and this also happens when I use the Notification facade. It just doesn't save anything in the user_id column.
I get the user through a relationship, something like $this->buyer->user where Buyer model belongs to User. I can see that the user is retrieved properly and has the ID.
App\Models\User {#1532
#fillable: array:5 [
0 => "name"
1 => "last_name"
2 => "email"
3 => "password"
4 => "account_type"
]
#hidden: array:4 [
0 => "password"
1 => "remember_token"
2 => "two_factor_recovery_codes"
3 => "two_factor_secret"
]
#casts: array:1 [
"email_verified_at" => "datetime"
]
#appends: array:1 [
0 => "profile_photo_url"
]
#connection: "mysql"
#table: "users"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:14 [
"id" => 20
"name" => "Test"
"last_name" => "User"
"email" => "test _at mail com"
"email_verified_at" => "2021-03-12 18:17:28"
"password" => ""
"two_factor_secret" => null
"two_factor_recovery_codes" => null
"remember_token" => null
"account_type" => "buyer"
"current_team_id" => null
"profile_photo_path" => null
"created_at" => "2021-03-12 18:17:22"
"updated_at" => "2021-03-12 18:17:53"
]
#original: array:14 [
"id" => 20
"name" => "Test"
"last_name" => "User"
"email" => "test _at mail com"
"email_verified_at" => "2021-03-12 18:17:28"
"password" => ""
"two_factor_secret" => null
"two_factor_recovery_codes" => null
"remember_token" => null
"account_type" => "buyer"
"current_team_id" => null
"profile_photo_path" => null
"created_at" => "2021-03-12 18:17:22"
"updated_at" => "2021-03-12 18:17:53"
]
#changes: []
#classCastCache: []
#dates: []
#dateFormat: null
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [
0 => "*"
]
#rememberTokenName: "remember_token"
#accessToken: null
}
I try to send the notification like this:
$this->buyer->user->notify(new \App\Notifications\MessageReceived(
$this->message,
'user 2')
);
The MessageReceived.php file looks like this
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class MessageReceived extends Notification
{
use Queueable;
public $message;
public $sender;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($message, $sender)
{
$this->message = $message;
$this->sender = $sender;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return [ 'broadcast', 'database' ];
}
/**
* Get the broadcastable representation of the notification.
*
* #param mixed $notifiable
* #return BroadcastMessage
*/
public function toBroadcast($notifiable)
{
return new BroadcastMessage([
'message' => $this->message,
'sender' => $this->sender,
'link' => '/chat/'
]);
}
/**
* Get the type of the notification being broadcast.
*
* #return string
*/
public function broadcastType()
{
return 'broadcast.message';
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)->subject('New message received')->view();
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'message' => 'You have a new message from ' . $this->sender,
'link' => $this->business->id . '/chat/' . $this->channel,
'type' => 'broadcast.message'
];
}
}
When I log the database queries I get this for this operation:
array (
'query' => 'insert into `notifications` (`id`, `type`, `data`, `read_at`, `notifiable_id`, `notifiable_type`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, ?, ?)',
'bindings' =>
array (
0 => '960ec22c-f121-4ef7-acca-c0e6105fd760',
1 => 'App\\Notifications\\MessageReceived',
2 => '{"message":"You have a new message from user 2","link":"/chat/","type":"broadcast.message"}',
3 => NULL,
4 => 20,
5 => 'App\\Models\\User',
6 => '2021-05-20 19:37:20',
7 => '2021-05-20 19:37:20',
),
'time' => 148.9,
),
I don't see the user_id column in this query. Is this a bug or what could I be doing wrong? I have had this issue for weeks and can't find the culprit. I am using version 8.12
The user id or notifiable id is stored at the notifiable_id column.
You can get the notifications related to the user using the relation between $user->notifications or $user->unreadNotifications().

How to view data decode json in blade

I have data like this
result from
dd($data)
in blade
array:18 [▼
"id" => "5dbb3b9adbc24572692f50e1"
"external_id" => "T Shirt Cyber Jawara"
"user_id" => "5785e6334d7b410667d355c4"
"status" => "PENDING"
"merchant_name" => "Xendit Testing"
"merchant_profile_picture_url" => "https://www.xendit.co/images/logo.png"
"amount" => 300000
"payer_email" => "hendro#gmail.com"
"description" => "BayarT Shirt Cyber Jawara"
"expiry_date" => "2019-11-01T19:52:58.423Z"
]
data is from controller
return view('confirmorder',['data' => $responseObject]);
How to show in blade laravel?
I don't think I fully understood what you need, but to pass data to your blade view is simple. Just do something like so:
public function returnView()
{
$responseObject = [
"id" => "5dbb3b9adbc24572692f50e1",
"external_id" => "T Shirt Cyber Jawara",
"user_id" => "5785e6334d7b410667d355c4",
"status" => "PENDING",
"merchant_name" => "Xendit Testing",
"merchant_profile_picture_url" => "https://www.xendit.co/images/logo.png",
"amount" => 300000,
"payer_email" => "hendro#gmail.com",
"description" => "BayarT Shirt Cyber Jawara",
"expiry_date" => "2019-11-01T19:52:58.423Z"
];
return view('confirmorder', compact('responseObject'));
}
Then, on your blade view, you will be able to call the array however you want, like so:
{{ $responseObject['status'] }}
Let me know if this is what you want.
Just use {{ $data }} in the view
for a specific key,
{{ $data['user_id'] }}

Getting value from multidimensional array by key in laravel 5.4 blade

I met some difficulties when I was trying to get value from an array in my php blade.
It has rather clear structure (printed with dd function)
{{dd($attr)}}
array:4 [▼
"id" => "215"
"type" => "select"
"name" => "Status"
"value" => array:2 [▼
"pred" => array:3 [▼
0 => "Employed"
1 => "On vacation"
2 => "Dismissed"
]
"sel_val" => "0"
]
]
And when I want to get a value by key 'sel_val' or 'pred'
print_r($attr['value']['pred']);
it gives me Illegal string offset 'pred'
And it works nice in Controller. What should i do?
It gives that error because pred is also an array. you'll have to do $attr['value']['pred'][0] to get Employed, $attr['value']['pred'][1] to get On vacation, $attr['value']['pred'][2] to get Dismissed and $attr['value']['sel_val'] to get the value of sel_val which is 0 in this case. Hope this helps.
working fine when we send array in compact function in the controller
$record = array('id' => '215', 'type' => 'select', 'value' => array('pred' => array('0'=> 'Employed', '1' => 'On vacation', '2' => 'Dismissed'),'sel_val' => '0'));
return view('home', compact('record'));

How do I update multiple records from one post that returns a collection?

I have an AngularJS form that uses ng-repeat and ng-form to populate a list of users that can be marked as here or not.
I am now trying to use AJAX to submit the updated field to Laravel.
My form request is trying to POST a collection and update one column for multiple records. Nothing seems to be happening, no errors.
I suspect there is something wrong with my method.
public function setRoster(Request $request, $id) {
$players[] = $request;
foreach ($players as $player) {
Player::where('playerId', $player->playerId)
->update(array('gamesPlayed' => $id));
}
}
Any ideas? Thanks!
Here is the JSON from the POST
Request {#39
#json: ParameterBag {#31
#parameters: array:1 [
"players" => array:22 [
0 => array:15 [
"playerId" => 1
"teamId" => "6"
"number" => "2"
"position" => "unknown"
"gamesPlayed" => ""
"tempNumbers" => ""
"firstName" => "Tom"
"lastName" => "Travis"
"dob" => "1968-10-01"
"email" => "tom#hotmail.com"
"mobile" => ""
"photo" => "headshot.jpg"
"created_at" => "-0001-11-30 00:00:00"
"updated_at" => "-0001-11-30 00:00:00"
"onIce" => true
]
and so on...
So based on feedback, I have tried this;
foreach ($request as $player) {
Player::where('playerId', $player['playerId'])->update('gamesPlayed', '=', $id);
}
Which is now returning this error;
Cannot use object of type Symfony\Component\HttpFoundation\ParameterBag as array

Resources