laravel undefined index error while retrieving notification data from database - php

I have created notification to store order submit event as
return [
'cart_id'=>$this->cart->id,
'text'=>'order is submitted'
];
when i retrieve notifications data from database as
#foreach (Auth::user()->unreadNotifications as $notification )
{{$notification->data['text'] }}
#endforeach
this gives error as undefined index text
but if i try to access text via
#foreach ($notification->data as $key => $data)
{{$data}}
#endforeach
it works
but why cant i can access data via $notification->data['text']

You should get the text attribute directly like :
#foreach (Auth::user()->unreadNotifications as $notification )
{{ $notification->text }}
//Or use
{{ $notification['text'] }}
#endforeach
Hope this helps.

Related

Laravel 5.6 - Grab message from Controller into view

I'm starting with Laravel and i need to show the output of a post request into the view. My controller file returns an array with a message, like this:
return redirect('/myroute')
->with('message', [
'type' => 'success',
'text' => 'It works'
]);
In my view file, i'm trying to grab the message text, but no success. See my code below
#if(Session::has('message'))
{{ $msg = Session::get('message') }}
<h4>{{ $msg->text }}</h4>
#endif
The point is: The condition works, if i changed the {{$msg->text}} to any text it works, but when i try to get the message text, it returns an error:
htmlspecialchars() expects parameter 1 to be string, array given
So, any help is apreciated. If more information is needed, just ask.
PS: i checked this question, but no success at all
EDITED:
PS2: Can't change controller structure
Try accessing the array as follows:
<h4>{{ $msg['text'] }}</h4>
or just pass an array with the items
->with([
'type' => 'success',
'text' => 'It works'
]);
//in the view
#if(session()->has('text'))
<h4> {{ session('text') }} </h4>
#endif
-- EDIT
iterate than over the session like so:
#foreach (Session::get('message') as $msg)
{{$msg['text']}}
#endforeach
you can read more about that here
Do this instead
return redirect('/myroute')->with('success','It worked');
Then on your view
{{session('success')}}

Getting info from json column in laravel 5.5

I have json column where i save my orders data in it, code below is sample of that data:
[{"id":27,"name":"new product","price":7246,"quantity":"1","attributes":[],"conditions":[]}]
with code above if i have such loop in my edit page i'm able to get orders info:
#foreach($order->product_data as $data)
{{ $data['quantity'] }}
#endforeach
until here everything is good, but the problem when comes that my order has attributes "attributes":[], then i get this error:
Invalid argument supplied for foreach()
and my data in json column is like:
"[{\"id\":29,\"name\":\"effewf\",\"price\":24524,\"quantity\":\"1\",\"attributes\":[{\"attr\":{\"label\":\"Red\",\"price\":\"5000.00\"}},{\"attr\":{\"label\":\"22\\\"\",\"price\":\"900000.00\"}}],\"conditions\":[]}]"
as you see this order has 2 attributes. (can be more or less).
additional
this is how i get those data in order model:
protected $casts = [
'product_data' => 'array',
];
any idea why i get that error and how i can get my attributes data no matter if my order has attribute or not?
UPDATE
if i open edit page of order without attribute and dd the result will be like:
array:6 [▼
"id" => 27
"name" => "new product"
"price" => 7246
"quantity" => "1"
"attributes" => []
"conditions" => []
]
if load the same on order with attributes get the error above.
You should only allow to print data if exists and having the format we are expecting ,please add necessary conditions to your code like below which may prevent from getting the errors
Assuming the array you have in post is data you need to print.
#if($order->product_data) // check product_data value or not , also add key exists if needed
#if(is_array($order->product_data)) // check for product_data is array or not
#foreach($order->product_data as $data)
{{ $data['quantity'] // if array }}
{{ $data->quantity // if object }}
#if($data->attributes)
#foreach($data->attributes as $attribute) // loop through attributes
{{ $attribute->nameOfTheProperty // if object }}
#endforeach
#endif
#endforeach
#endif
#endif
But better to handle the data in controller if possible
update:
you need to convert your data into array, as your attribute property will be blank array if not having value otherwise it will be stdObject.
so your code should be : ($order->product_data should be an array if not then convert it to an array)
#if($order->product_data)
#if(is_array($order->product_data)) // assuming array
#foreach($order->product_data as $data)
{{ $data['quantity'] // if array }}
#if(count($data['attributes']) > 0) // **checked for blank array**
#foreach($data->attributes as $attribute) // loop through attributes
{{ $attribute['attr']['label'] }}
{{ $attribute['attr']['price'] }}
#endforeach
#endif
#endforeach
#endif
#endif
Tried with your sample data, and that executed without any error.
$json = "[{\"id\":29,\"name\":\"effewf\",\"price\":24524,\"quantity\":\"1\",\"attributes\":[{\"attr\":{\"label\":\"Red\",\"price\":\"5000.00\"}},{\"attr\":{\"label\":\"22\\\"\",\"price\":\"900000.00\"}}],\"conditions\":[]}]";
$jsonAsArray = json_decode($json, true);
foreach ($jsonAsArray as $data) {
echo $data['quantity'] . "\n";
if (! empty($data['attributes']) ) {
if (is_array($data['attributes'])) {
foreach ($data['attributes'] as $attribute) {
echo $attribute['attr']['label'] . ' ' . $attribute['attr']['price'] . "\n";
}
}
}
}
Outputs:
1
Red 5000.00
22" 900000.00
In your case, the product_data is not cast as an array.
You could try Defining An Accessor in your Order model, and remove the cast property of product_data
public function getProductDataAttribute($value)
{
return json_decode($value, TRUE);
}
Or Manually decode the json in your loop
#foreach (json_decode($order->product_data, TRUE) as $data)
{{ $data['quantity'] }}
#if (! empty($data['attributes']))
#foreach ($data['attributes'] as $attribute)
{{ $attribute['attr']['label'] }} {{ $attribute['attr']['price'] }}
#endforeach
#endif
#endforeach
This is how I did mine (category is a json column in the DB):
<div class="category">
<ul class="list-group">
#foreach ( json_decode( $code->category ) as $category)
<li class="list-group-item d-flex justify-content-between align-items-center">
<span class="badge badge-secondary badge-pill">{{$category}}</span>
</li>
#endforeach
</ul>
</div>
You just have to json_decode your json column to get an array and iterate over it. that's it, cheers.

How to use Youtube Class on View

I am using Youtube package
I added this on app.php
Alaouy\Youtube\YoutubeServiceProvider::class,
&
'Youtube' => Alaouy\Youtube\Facades\Youtube::class,
now i m trying in view like this
{{ Youtube::getVideoInfo('rie-hPVJ7Sw') }}
but getting error
"htmlspecialchars() expects parameter 1 to be string, object given
(View: C:\xampp\htdocs\guru\resources\views\admin\video\index.blade.php)"
how can I fix this?
i Tried
#foreach($videos as $video)
{{ var_dump(Youtube::getVideoInfo($video->videoid)) }}
#endforeach
its showing me everything
Here is Screenshot
As per the docs,
// Return an STD PHP object
$video = Youtube::getVideoInfo('rie-hPVJ7Sw');
so you could do,
{{ var_dump(Youtube::getVideoInfo('rie-hPVJ7Sw')) }}
to print out the object or assign it to a variable and access the respective object properties
EDIT
To show only the embed html you could use the following code
#foreach($videos as $video)
{!! Youtube::getVideoInfo($video->videoid)->player->embedHtml !!}
#endforeach

Get selected value in form, seletbox

I have a problem and I can't resolve it, please help me. So I have my form :
{{ Form::open(array('url'=>'/administration/student/addMarks','method' => 'post')) }}
#foreach($aObjectsInGroupe as $object)
{{ Form::hidden('id_object[]',$object->id) }}
{{ Form::label($object->name) }}
{{ Form::select('note[]', $aMarks, null, array('class'=>'form-control')) }}
<br />
#endforeach
{{ Form::hidden('id',$aOneStudent['id']) }}
{{ Form::submit('Add mark',array('class'=>'btn btn-primary')) }}
{{ Form::close() }}
In my StudentController I have a method for get the mark from student_id and object_id:
public function getMarkByStudentAndObject($nIdStudent, $nIdObject){
$aMark = \Mark::where('student_id', '=', $nIdStudent)
->and('object_id', $nIdObject)
->get()
->toArray();
}
$aMarsks it's a table :
$aMarks = array(
'0'=>'0',
'1'=>'1',
'2'=>'2',
'3'=>'3',
'4'=>'4',
'5'=>'5',
'6'=>'6',
'7'=>'7',
'8'=>'8',
'9'=>'9',
'10'=>'10',
);
It's possible to call the method getMarkByStudentAndObject in :
{{ Form::select('note[]', $aMarks, null, array('class'=>'form-control')) }}
to get the selected value?
Help me please. Thx in advance.
maybe you need to do this:
<select name="note[]" class="form-control">
#foreach($aMarks as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
You should also check your Eloquent query, instead of ->and use another ->where
Try the lists() function of the Query Builder
\Mark::where('student_id', '=', $nIdStudent)
->and('object_id', $nIdObject)
->lists('column_1', 'column_2');
You then get the values of column_1 as the keys of the array and column_2 as the values.
http://laravel.com/docs/4.2/queries#selects
You should be able to directly call this from the Form::select. A call to
Mark::getMarkByStudentAndObject($aOneStudent['id'], $object->id)->note
would give you the Mark object and then you would need to get the note column which stores the value in the Mark object. Resulting in a call like this:
{{
Form::select(
'note[]',
$aMarks,
Mark::getMarkByStudentAndObject(
$aOneStudent['id'],
$object->id
)->note, array('class'=>'form-control')
)
}}
At the moment I can't verify if this is working because I have no possibility to test it but it should work as Blade is just a wrapper for PHP calls.

laravel passing database array from controller to view

hello people here is my code below for controller
$siteinformation = DB::table('siteinformation')->where('Site',$myarr[0]['site'])->select()->get();
print_R($siteinformation); will display
Array ( [0] => stdClass Object ( [Site] => site1 [Nickname] => friend [ProgramID] => 1 [CreateDateTime] => 2014-06-03 18:05:39 ) )
I am trying to pass it to view
return Redirect::to('sbs_site')->with('siteinformation',$siteinformation);
In my view i have...
#if(Session::has('siteinformation'))
#foreach ($siteinformation as $key => $value)
{{ $value->Nickname }}
#endforeach
#endif
Iam gettng an error Undefined variable: siteinformation
my route file contains... Route::post('sbs_site', array('uses' => 'myController#sys_config'));
what could be the problem??
I think you don't need to redirect; probably you are doing it wrong, instead you should pass the data to the view directly using something like this:
$siteinformation = DB::table('siteinformation')
->where('Site',$myarr[0]['site'])
->get();
// View Name: "sbs_site.blade.php"
return View::make('sbs_site')->with('siteinformation', $siteinformation);
Then in the view:
#foreach ($siteinformation as $value)
{{ $value->Site }}
{{ $value->Nickname }}
#endforeach
But if your really need to use a redirect then you may do it like this:
// Route Is: "sbs_site"
return Redirect::to('sbs_site')->with('siteinformation', $siteinformation);
Then in your view:
#if(Session::has('siteinformation'))
#foreach (Session::get('siteinformation') as $value)
{{ $value->Site }}
{{ $value->Nickname}}
#endforeach
#endif
This worked for me...
in view
#if(Session::has('siteinformation'))
#foreach (Session::get('siteinformation')as $key => $value)
{{ $value->Nickname}}
#endforeach
#endif
In controller
return Redirect::to('sbs_site')->with('siteinformation',$siteinformation);
Your view file is not getting session set if(Session::has('siteinformation')), because you did not set session in your controller. You set in your controller 'siteinformation' as a normal variable. If you want to set session, instead of this.
Redirect::to('sbs_site')->with('siteinformation',$urserializedobj);
Do this
Session::put('siteinformation',$urserializedobj);
Redirect::to('sbs_site');
OR
Simply don't check session in your view instead of this
if(Session::has('siteinformation'))
Just do this
if (!empty($siteinformation)) :
I don't know why u are redirecting to pass it to the view
return View::make('yourview',array('siteinformation'=>$siteinformation));
This will do the trick if you can make the view directly from the controller
BUT
if u need to redirect than i suppose you can serialize your array or change it to json first because the with function passes the data as flash so only strings
$urserializedobj = $siteinformation.toJson();//if this doesn't work try serealizing
return Redirect::to('sbs_site')->with('siteinformation',$urserializedobj );
now in your view you can do this
#if(Session::has('siteinformation'))
$siteInformation = json_decode(Session::get('siteinformation'));
#foreach ($siteinformation as $key => $value)
{{ $value->Nickname }}
#endforeach
#endif

Categories