Blade foreach cast output to an object - php

I am trying to figure out how I can give my data output in the blade file, the Laravel look;
like $data->name
But I can't get the output to be casted as an object. I think I have to make an array of the data before I can loop it proper in a foreach but this doesn't feel like the right way.
I am relatively new to Laravel and I want to do this the nice way, can someone point me in the right direction? Thanks in advance
Controller:
$data = collect($this->api->organization->index())->toArray();
return View::make('pages.organization.index', array('data' => $data[0]));
View:
#foreach($data as ((object)$organization))
{{ $organization->name }}
#endforeach
I know this will not work, but I think it illustrates my question a little bit.
EDIT
What I didn't realize is that $data = collect($this->api->organization->index()); is returning an array with all the data arrays inside because I didn't name it in my return like this:
return (object)['all' => $data];
After adding all I could reference the code inside my view like I wanted to. I know this is not a very detailed answer, if you run into the same problem message me I'll edit the answer.

Object:
$data = collect($this->api->organization->index());
#foreach($data as $organization))
{{ $organization->name }}
#endforeach
Array:
$data = collect($this->api->organization->index())->toArray();
#foreach($data as $organization))
{{ $organization['name'] }}
#endforeach

Related

PHP variable is not assigned

I'm working on a laravel project.
now I want to access one of my column which is data
The data colmn contains an array of stuff like message, klant_address, reactionPlacer and more.
foreach(Auth::user()->unreadNotifications as $notfiy) {
{{ $notify->data['klant_address'] }} //This gives an error "variable is not assigned"
}
but if i store it first to a variable it does'nt gives an error like this
foreach(Auth::user()->unreadNotifications as $notfiy) {
$klantAddress = $notify->data['klant_address']
echo $klantAddress
}
Now comes the weirdest part of all
if i do
dd($notify->data['klant_address']) <-- this does gives me the signle string return
and
foreach(Auth::user()->unreadNotifications as $notfiy) {
{{ $notfiy->data['messages'] }} <--- This does output
}
does work.
I hope someone can help me or at least explain why this is happened. Because I'm so confused for it.
thanks in advance.
Error Page
Database Table
Looks more like JSON to me. (Look at the last image)
Try this:
{{ $notify->data->klant_address ?? '' }}
If that doesn't work, try {{ json_encode($notify->data)->klant_address ?? '' }}
(Thrown in ternaries to help with nulls etc.)

Empty array don't appear as empty in Laravel blade

Right now I'm trying to check when the view receives an empty array.
#if(! empty($array))
// Section content goes here...
#foreach($array as $value)
// All table data goes here...
#endforeach
#endif
The code as it is above seems to still run when the $array is empty and causes an exception.
When I try to dump the array with {{ dd($array) }} I get $array = [].
Sounds like you might be having a collection. You could simply do count($array) to check amount of records in the array. It would look something like this:
#if(count($array))
// Section content goes here...
#foreach($array as $value)
// All table data goes here...
#endforeach
#endif
The section should now be hidden. If you wish to only skip the foreach when there is nothing in the array you could do this:
// Section content goes here...
#forelse($array as $value)
// All table data goes here...
#empty
// Optional message if it's empty
#endforelse
Which would output the section content and check if the array has any values before it foreach it.
You can read more about loops within blade files in the Laravel documentation.
Is it possible your array is a collection?
Try using a #forelse, this will check if the array or collection is empty and display another block instead. For example:
#forelse($array as $value)
{{ $value }}
#empty
array is empty
#endforelse

Output value from table in view

I've got a problem in Laravel. I have passed my whole table to my view like this from my controller:
$usersTable = DB::table('users')->get();
return view('users')->with('users', $usersTable);
In a foreach loop I can perfectly get each of the values like this in my view:
#foreach($users as $user => $value)
<div class="projectBox">
<br><span class="projectBoxName">{{ $value->name }}</span>
#php
echo Form::image('/images/edit.png', "",['class' => "editUserBtn", 'userId' => $value->id]);
#endphp
<br><span class="projectBoxSmallText projectBoxEmail">{{ $value->email }}</span>
<br><span class="projectBoxSmallText projectBoxId">ID: {{ $value->id }}</span>
<br><span class="projectBoxSmallText projectBoxProjects">Currently no projects</span>
</div>
#endforeach
But I also need to access these values outside my foreach loop, how can I do that?
echo Form::text('email', "$users->$value->email", array('placeholder' => "Email"));
Ain't working...
This gives my the whole object in this form
[{"id":"1","name":"Administrator","email":"admin#mail.com","password":"$2y$10$Re3Ahf.SwU5vj4UvtU5Dy.jxaZMsUNC2WhuJMwsNy9gu6TST4PuRG","remember_token":null}]
How to get only the email? I also tried using indexes, but those weren't working.
Thanks!
Edit:
Full situation:
I have a list of users with their extra information (mail, tel,...). In those user-boxes there is a button which says 'edit user' when I click that a modal opens giving the current mail and tel. So I can't say in my controller WHO's mailaddress to return because I only know that at the moment the user clicks a client-side button.
Images: http://imgur.com/a/krDrY
(Edit button is that small circle with three dots).
To access a collection without using loop, you should use collection methods:
$users = User::get();
$users->where('name', 'John Smith')->first()->email
This will not create any additional queries since you've already eager loaded data.
If you want to load just one user, use first() instead of get():
$users = User::first();
If you'll use get() and then [0] or first() like some guys recommend here, you'll load all users data into the memory for each request which will overload your server.
Also, using indexes to access data (like $users[4]['email']) is a bad practice. Avoid it if possible.
You need to add as first element by adding [0]
echo Form::text('email', $users[0]->email, array('placeholder' => "Email"));
I suggest use ->first() instead of ->get() to get single object. And remove loop and use anywhere you want.
You are using a collection of users to get the first user's email, you do
$users->first()->email;
Looks like it's coming in as JSON. Try json_decode($data) and $data->email to get that attribute.

Blade laravel variable value type?

I'm new to laravel
Just being curious,
Suppose I make an array in a view page
myView.blade.php
Suppose:
$array = [
1, 2, 3
];
in the same page, I want to loop it with "blade" foreach
suppose:
#foreach($array as $value)
<span id="{{$value}}">{{$value}}</span>
#endforeach
but, I get an error like this.
ErrorException in 1ed42d9dadecab7c54e086f573c4cbad6576e7c3.php line 63:
Trying to get property of non-object...
what's happened? what type of variable actually blade converts?
Any question will highly appreciated! :)
First of all, it's better if you just pass the data to your view files from controller.
But, if you still want to do that, and you are using Laravel 5.3, you can do it like this:
#php
$array = [
1, 2, 3
]
#endphp
and then loop it:
#foreach($array as $value)
<span id="{{$value}}">{{$value}}</span>
#endforeach
Make, sure that you declare the $array array before the loop.
Have a look at the Service Injection and View Composers on Larave's documentation aswell.
Actually, I don't know what do you want? But recommendly, you should init your array at controller, through it to view and foreach.
In controller,
return view('your view path', ['array' => $array]);
In blade
#foreach($array as $value)
<span id="{{$value}}">{{$value}}</span>
#endforeach
Hope it could help, thanks.

Laravel form sort of submitting in debug mode but doesn't work in normal mode

so I have a selection box that gives a dropdown menu to give messages a manager from the dropdown. It takes the input and then changes to a column in the database called manager for it's respective column. When I try to submit the selection menu it gives me the regular error for Laravel. But then when I put ?debug=1 at the end it submits but gives the row's manager column a value of just blank.
Here is what I have in the routes.php
Route::get('foo/{id}', 'fooController#bar');
Route::post('foo/{id}', 'fooController#bar');
This is the form.
{{ Form::open(array('url' => '/admin/foo' . $message->id)) }}
{{ Form::select('handler[]', array('unassigned', 'foo', 'bar'), null, array('style' => 'width: 127px')); }}
{{ Form::submit('Change manager') }}
{{ Form::close() }}
{{ $message->manager }}
and here is what is in the fooController
public function bar($id = null)
{
$message = Message::find($id);
$handler = Input::get('handler[]');
$message->manager = $handler;
$message->save();
return Redirect::action('AdminController#foo_bar');
}
I had a problem like this the other day, I have zero recollection of what I did. I really appreciate any help, thanks! The database is postgresql if that's any help
Try a dd(Input::all()) at the beginning of your controller and make sure you're seeing what you expect.
Also since you're sending an array perhaps you have to do Input::get('handler.0') -- see here right below the Input::only() and Input::except() code block.
It would seem as though because you are naming your select handler[], PHP is grabbing it as part of an array.
When setting up your message model, try this...
public function bar($id = null)
{
$message = Message::find($id);
$handler = Input::get('handler[]');
$message->manager = $handler[0];
$message->save();
return Redirect::action('AdminController#foo_bar');
}
Usually, you'd only use names in your forms post-fixed with [] when you are accepting multiple values like checkboxes/multi-selects etc... Otherwise, it's probably best to stick with not using it because it may cause confusion.
I managed to fix it in a almost frustratingly simple way by just changing the method to PUT.
like this
Form::open(array('url' => 'foo/bar', 'method' => 'put'))

Categories