Getting data out of array column in laravel 5.5 - php

I save my order data to notifications table as my notification using laravel Notification and I have problem with returning my data.
here is my notification method: App\Notifications\OrderSubmited.php
public function toArray($notifiable)
{
return [
'order_id' => $this->order->id,
'title' => $this->order->title,
'buyer' => $this->order->user_id,
'status' => $this->order->orderstatus_id,
];
}
My method to get data:
View::composer('admin.dashboard', function ($view) {
$notifications = DB::table('notifications')->orderby('id', 'desc')
->latest()
->take(5)
->get();
$notifs = $notifications;
$view->with('notifs', $notifs);
});
here is my blade code:
#foreach($notifs as $notif)
{{dd($notif)}}
#foreach($notif->data as $data)
{{$data['order_id']}} <br>
#endforeach
#endforeach
this is my {{dd($notif)}} output:
{#721 ▼
+"id": "46546547464415474884"
+"type": "App\Notifications\OrderSubmited"
+"notifiable_id": 2
+"notifiable_type": "App\Order"
+"data": "{"order_id":2,"title":"tsdfg", "user_id":"1", "orderstatus_id":"11"}"
+"read_at": null
+"created_at": "2018-01-18 00:00:00"
+"updated_at": "2018-01-18 00:00:00"
}
as you can see data i try to return are stored in data column.
If I remove my dd i will get this error:
Invalid argument supplied for foreach()
On this line:
#foreach($notif->data as $data)
Any idea?

Each notification is an object containing an array called data containing the values you return from your toArray method when creating the notification. You would normally iterate through your notifications and access their data like so:
#foreach ($notifications as $notification)
{{ $notification->data['order_id'] }}
#endforeach
Laravel converts the data property (which is stored in the database as JSON) into an array.
However because you are retrieving the notifications yourself from the database without making use of the built in methods you will need to convert that data to an array from JSON yourself, like so:
View::composer('admin.dashboard', function ($view) {
$notifications = DB::table('notifications')->orderby('id', 'desc')
->latest()
->take(5)
->get();
$view->with('notifications', $notifications);
});
Then from within your view:
#foreach ($notifications as $notification)
#php $data = json_decode($notification->data, true); #endphp
{{ $data['order_id'] }}
#endforeach
Regarding your follow up question, something like this:
View::composer('admin.dashboard', function ($view) {
$notifications = DB::table('notifications')->orderby('id', 'desc')
->latest()
->take(5)
->get()
->map(function ($item, $key) {
$item->data = json_decode($item->data);
$item->data->user = User::find($item->data->user_id);
return $item;
});
$view->with('notifications', $notifications);
});
Then from within your view:
#foreach ($notifications as $notification)
{{ $notification->data->user->name }}
#endforeach

Related

How to echo object name of an array in Laravel controller

how do I display an object name of an array that I fetched from the database in Laravel blade?
When I dump array in Laravel controller I get this "name" => "{"name":"Item 1"}". Now, how do extract Item 1 from array and display in a blade while looping using foreach.
Controller
$data = DB::table('items')
->select('name')
->where('id', $user->id)
->get();
$output = json_decode($data,true);
dd($output);
Results
"name" => "{"name":"Item 1"}
Kindly help.
You have to extract from each object separately.
Variant 1:
Controller:
$data = DB::table('items')->select('name')->where('id', $user->id)->get()
->map(function($item){
$item->name = json_decode($item->name, true);
return $item;
});
return view('some_view', ['data' => $data]);
View:
#foreach($data as $d)
<p>{{ is_array($d->name) ? $d->name['name'] : 'No Name' }}</p> {{-- Just Checking if Json is correctly decoded --}}
#endforeach
Variant 2:
Controller:
$data = DB::table('items')->select('name')->where('id', $user->id)->get();
View:
#foreach($data as $d)
#php($name = json_decode($d->name, true))
<p>{{ is_array($name) ? $name['name'] : 'No Name' }}</p> {{-- Just Checking if Json is correctly decoded --}}
#endforeach
Controller:
$dataes = DB::table('items')
->select('name')
->where('id', $user->id)
->get();
return view('viewName',compact('dataes'));
View:
#foreach($dataes as $data)
{{ $data->name }}
#endforeach

How to implement DataTable with parameter 'id' in Laravel (DataTables)?

I am trying to pass the ID value from the blade file into ajax so it the data table will be routed and will call the ProductActivities function in ProductController.
Here's my snippet code for show() function in ProductController:
public function show($id)
{
$product = Product::find($id);
$data = Product::with(['user_modify'], 'id', $product->user_modified)
->where('product_id', '=', $id)->first();
$category = Category::select('category_name')
->where('category_id', '=', $data->product_type)
->pluck('category_name')
->first();
if($data->count() > 0){
return view('product.view', compact('data', 'category'));
}else{
Toastr::error('Product cannot be retrieved.', 'Error');
return view('product.index');
}
}
And here's the snippet code of JavaScript for the DataTable initialization in view.blade.php file:
#push('js')
<script>
$(function () {
$("#prod_log_tbl").DataTable({
responsive:true,
stateSave:false,
scrollY:true,
autoWidth: false,
ajax: {{ url('product/activities', [Request::segment(3)]) }},
order:[0, 'desc'],
searchable: false,
sortable:false,
fixedColumns: true
});
});
</script>
#endpush
line of code for route in web.php:
Route::get('product/activities/{id}', 'Master\ProductController#ProductActivities')->name('product/activities/{id}');
snippet code for the ProductActivities() function in ProductController:
public function ProductActivities($id)
{
$dataAct = Activity::all()->where('subject_id', '=', $id);
return Datatables::of($dataAct)->make(true);
}
And here's the result of my current progress:
In the screenshot of result the URL that ajax shows has additional values after the ID which I think causes of the DataTable error.
I don't know How I am getting this error? How can I implement the passing of ID from the view blade file through DataTable ajax into the ProductController?
P.S. I use Yajra/DataTable package for Laravel.
I think you do not need php echo in you Ajax url, route helper syntax is
{{ route('routeName', ['id' => 1]) }}
you need route name and parameter, another way is using url helper
{{ url('product/activities/', [Request::segment(3)]) }}
Beside this if you want to use model refer documentation, using first() will give you only one object, you need a collection, better considering get().

Sending data from Controller to View in Laravel 7

I want to send my data from controller to xedit.blade.php, but I get the same error:
Undefined variable: users
in controller:
public function index3()
{
$users=User::all();
return view('xedit')->with('users' => $users);
}
Routes:
Route::get('/index3','Admin\UsersController#index3');
and I want to use $users in blade.Maybe there is a Route problem?
in your index method
public funtion index()
{
$users=User::all();
return view('xedit', compact('users'));
}
in your view add $users
<table>
#foreach ($users as $item)
<tr>
<td>{{ $item->id }}</td>
<td>{{ $item->name }}</td>
</tr>
#endforeach
</table>
Your code logic is perfect, I guess you have to use proper naming with your routes because of Laravel Standard.
Route::get('/admin/show','Admin\UsersController#index')-name('admin.show');
public function index()
{
$users = User::all();
return view('xedit')->with('users' => $users);
}
In view, blade use a professional approach like below
#isset($users)
... loop ...
#endisset()
check record before sending to view by using dump and die function dd($users);
Want to comment but doesn't have 50 reputation
Replace ('users' => $users); this with (['users' => $users]); as you are using =>

laravel pagination : Call to a member function render() on array

In laravel controller I have following code:
public function getAdmins(){
//$users = $this->user->all();
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
$exceptSuperadmin = array();
foreach($users as $user){
if(!$user->isUser())
$staffs[] = $user;
}
$users = #$staffs;
return view('users::admins.list')->with('staffs',$users)->with('search',$search);
}
In Model I have:
public function findUsers($search)
{
return self::where('name','like','%'.$search['name'].'%')
->where('username','like','%'.$search['uname'].'%')
->where('role','like','%'.$search['role'].'%')
->paginate(5);
}
And In blade file I have:
#if($staffs)
#foreach($staffs as $staff)
<!-- Some code here to loop array -->
#endforeach
#else
No Staffs
#endif
{!! $staffs->render() !!} Error comes at this line
I am not geeting why this error comes....staffs is an array and render() a function to echo the pagination pages...but can't getting the error...Anybody to help.
By applying foreach the pager object and assign an array you lose the paging properties, so you will have an array rather than a pager object.
I recommend the following solution for your case:
Controller:
public function getAdmins(){
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
return view('users::admins.list')->with('users',$users)->with('search',$search);
}
Blade file:
#if($users)
#foreach($users as $user)
#if(!$user->isUser())
<!-- Some code here to loop array -->
#endif
#endforeach
#else
No Staffs
#endif
{!! $users->render() !!}
NO, render() doesn't work on an object per se, neither on the array you are creating out of the required object for the pagination to work (LengthAwarePaginator)
Since you have a collection, and you need one, you could use one of the methods provided to do your filtering, such as filter.
Something like (untested but should work):
$staff = $users->filter(function ($value, $key) {
return !$value->isUser();
});

How to get data from database displaying in a list laravel

Whenever I am using this code I keep getting the following error:
"Trying to get property of non-object"
Controller:
public function createBooking()
{
$products = DB::table('products')->orderBy('id', 'asc')->lists('id', 'name');
return View::make('users.addbooking', array('products' => $products));
}
Blade View:
{{ Form::select('products', $products , Input::all('products')) }}
Try this out, I'm running laravel 5 and it works fine for me.
Controller:
public function createBooking()
{
$products = DB::table('products')
->orderBy('id', 'asc')
->lists('name', 'id'); // checked some of my code I have these swapped value first then id
return View::make('users.addbooking', array('products' => $products));
}
Blade:
{{ Form::select('products', ['' => 'Select'] + $products, '', ['class' => 'myClass', 'id' => 'myId'] }}
If you're getting the Trying to get property of non-object error, try this at after your query in your controller to check your getting the right results for your query:
dd($products);

Categories