laravel controller compact doesn't work - php

In my Routes I have:
Route::get('/about','PagesController#about');
In PagesController:
public function about()
{
$people=['Taylor','Matt','Jeffrey'];
return view('pages.about',compact($people));
}
if I use
return view('pages.about',['people'=> $people]);
It runs ok.
The controller isn't passing the array to view, why ?

Use
compact('people')
If you're a beginner checkout the laracasts video series to get a good understanding of the Laravel framework.

Remove $ sign inside compact function like compact('people'). This will solve your issue.
compact() is not a Laravel function. It is a PHP function. It creates an array containing variables and their values.
For an example, assume you have following variables.
$name = 'Jon Snow';
$dad = 'Rhaegar Targaryen';
$mom = 'Lyanna Stark';
If you put those in a compact() as follows,
$thePrinceThatWasPromised = compact(['name', 'dad', 'mom']);
You'll get following array assigned to $thePrinceThatWasPromised.
[
'name' => 'Jon Snow',
'dad' => 'Rhaegar Targaryen',
'mom' => 'Lyanna Stark'
]
For more information go to php manual

Related

Laravel ->put() issue - Mixed content (JSON vs. not JSON)

I'm having an issue with using Laravels put() function, as I want put JSON content in this one single scenario.
$datatable->GroupsCollection = $datatable->GroupsCollection->put($job, '{"grade":'.$grade.'}' );
But when trying to create 'fake' JSON, the inserted value will be:
{\"grade\":'VALUE_OF_$GRADE'}
I've tried using str_replace() and stripslashes() to cut out the backwardslashes, but no bueno.
I've Googled around, and reading something about a cast was needed in the Model.
So I put in this:
protected $casts = [
'dvalue' => 'array',
];
This result in breaking existing functionality of the code.
public function getGroupsCollectionAttribute()
{
return collect($this->dvalue ? $this->dvalue['groups'] : null);
}
public function setGroupsCollectionAttribute($value)
{
$currentValue = $this->dvalue ?? new Collection();
$this->dvalue['groups'] = $currentValue->$value;
}
I 'fixed' the get, but I'm not sure how I should format the 'set' function with this new cast and setting it to an array.
Worth to notice is that we have mixed content in the DB-rows, so it's not always JSON.
Any easier way to go around this?
Ending up fixing it by simply creating an array like this:
$grade_json = array("grade" => $grade);
$datatable->GroupsCollection = $datatable->GroupsCollection->put($job, $grade_json);

Get Array Path as string by php

I have arrays like this
$InternetGatewayDevice['DeviceInfo'][0]['SoftwareVersion'][1]['_value']
and also like this
$InternetGatewayDevice['DeviceInfo'][1]['SoftwareVersion'][2]['_value']
actually, both of them return same value, which is the software version for the router, but because routers belong to different vendors, I have that problem, so
actually, I want to know the path that I have to go in, in order to get my value
so I want to have somethings like this
InternetGatewayDevice.DeviceInfo.0.SoftwareVersion.1._value
as a string
I mean I want a function where I can provide to it the array and the key ,so the function will return to me the path of the array that I have to follow in order to get the value like this
getpath($array,"SoftwareVersion")
whhich will return value like this
InternetGatewayDevice.DeviceInfo.0.SoftwareVersion
are there any way to do this in php ?or laravel package
or is there any way in PHP to get the value whatever the number key is?
I mean like this
$InternetGatewayDevice['DeviceInfo'][*]['SoftwareVersion'][*]
so what ever the key it will return the value
You could try to use he data_get helper function provided by Laravel.
public function getSoftwareVersion(array $data, int $deviceInfoIndex, int $softwareVersionIndex)
{
$index = "DeviceInfo.{$deviceInfoIndex}.SoftwareVersion.{$softwareVersionIndex}";
return data_get($data, $index);
}
Then it can be used like
$softwareVersion = getSoftwareVersion($internetGatewayDevice, 1, 0);
Laravel Docs - Helpers - Method data_get
you can use the get function from lodash php
https://github.com/lodash-php/lodash-php
Example:
<?php
use function _\get;
$sampleArray = ["key1" => ["key2" => ["key3" => "val1", "key4" => ""]]];
get($sampleArray, 'key1.key2.key3');
// => "val1"
get($sampleArray, 'key1.key2.key5', "default");
// => "default"
get($sampleArray, 'key1.key2.key4', "default");
// => ""

Convert multiple array into a string in laravel

$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->get(array('id'));
return $est_data;
result:
[{"id":43},{"id":71},{"id":41},{"id":39}]
This is my above laravel condition and result, i want the result to be like 43,71,41,39.
Can anyone please help me, how can be this done using php. i tried with implode() function, but getting error, please help...thank you
Laravel pluck method will select required fields only:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return $est_data;
As commented by #apokryfos for your laravel version (4.2) lists method should be used, so it is:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->lists('id');
return $est_data;
You can use the laravel array_flatten() array helper:
The array_flatten function flattens a multi-dimensional array into a
single level array:
$array = array('name' => 'Joe', 'languages' => array('PHP', 'Ruby'));
$array = array_flatten($array);
// array('Joe', 'PHP', 'Ruby');
In your case:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return array_flatten($est_data);
$result = implode(',',$est_data[0]);
This will solve your problem. You should read about implode(convert to string) and explode (string to array). They are really useful php functions.
Reading your comment, your error is coming from the fact that you try to access $set_data and not $set_data[0] where you values are based on the output you provided us.
Use the php array_column function, specifying the id:
$est_data = Establishments::where('status',0)->where('city','=',$data['location'])->pluck('id');
return array_column("id", $est_data);

Passing dependency parameters to App::make() or App::makeWith() in Laravel

I have a class that uses a dependency. I need to be able to dynamically set parameters on the dependency from the controller:
$objDependency = new MyDependency();
$objDependency->setSomething($something);
$objDependency->setSomethingElse($somethingElse);
$objMyClass = new MyClass($objDependency);
How do I achieve this through the Service Container in Laravel? This is what I've tried but this seems wrong to me. In my AppServiceProvider:
$this->app->bind('MyClass', function($app,$parameters){
$objDependency = new MyDependency();
$objDependency->setSomething($parameters['something']);
$objDependency->setSomethingElse($parameters['somethingElse']);
return new MyClass($objDependency);
}
And then in the controller i'd use this like:
$objMyClass = App:make('MyClass', [
'something' => $something,
'somethingElse' => $somethingElse
]);
Is this correct? Is there a better way I can do this?
Thanks
You can see detailed documentation here: https://laravel.com/docs/5.6/container#the-make-method
It's done like this:
$api = $this->app->makeWith('HelpSpot\API', ['id' => 1]);
Or use the app() helper
$api = app()->makeWith(HelpSpot\API::class, ['id' => 1]);
It is essential to set the array key as the argument variable name, otherwise it will be ignored. So if your code is expecting a variable called $modelData, the array key needs to be 'modelData'.
$api = app()->makeWith(HelpSpot\API::class, ['modelData' => $modelData]);
Note: if you're using it for mocking, makeWith does not return Mockery instance.
You can also do it this way:
$this->app->make(SomeClass::class, ["foo" => 'bar']);

Laravel isset with array value

I am having an issue - well because the value I am trying to pull from the DB does not exist yet.
Is there away that I check if its isset?
Is there any better way that I can get my value from the db to save on double code?
Controller:
$siteSocialFacebook = socialSettings::where('socialName','=','facebook')->get();
$siteFacebook = $siteSocialFacebook[0]['socialLink'];
Blade:
value="{{ old('facebook', #$siteFacebook)}}"
If you will only ever expect one result, use first() instead of get() and skip the array. You can pass it into the Blade template like this:
return view('blade', [
'siteFacebook' => $siteSocialFacebook['socialLink'] ?: null,
]);
This will prevent any issues with undefined parameters.
Edit: I just realized you're treating models as arrays. You can do this too:
return view('blade', [
'siteFacebook' => $siteSocialFacebook->socialLink,
]);
That handles it for you.

Categories