I need to create a collection from an array in Laravel and use -> to access my domain key, I've tried:
all()
first()
get()
What am I missing?
$domain = collect([
'domain' => 'test'
])->first();
I need to be able to use this syntax: $domain->domain which would then give me "test".
$domains = collect([(object)['domain' => 'test']]);
$domain = $domains->first();
// OR $domain = collect([(object)['domain' => 'test']])->first();
$domain->domain; // 'test'`
The (object)[...] syntax is called casting, and allows you to set certain variables as an explicit type, if possible. This code will create a Collection of a single Object, with a single property domain: 'Test', which you can access via -> syntax.
Note, if you're working with Models, you can use either -> or [] syntax:
$domains = Domain::get();
$domain = $domains->first();
$domain->domain; // 'test'
$domain['domain']; // 'test'
Related
In Laravel, I'm trying to create an array of some existing values I have that are built from values from a JSON object.
I have the 4 variables set and they dump properly but I'd like to add all 4 (username, perms, roles, access) to the array (IdentifierArray) with their own key/name so that when I add the array to the session and inspect it, I can see each value with it's key/name.
Code at this point:
$IdentifierArray = [];
$Username = $login->username;
$Perms = $login->permissions;
$Roles = $login->roles;
$Access = $login->access;
Session::put('Array of Values', $identifierArray);
So I'd like to add those object values to the array in the best way while having a key for each as well, like:
Array(
"username": $username value,
"perms":$perms value,
"Roles":$roles value,
"Access":$Access value
)
Another way of doing it, equal to #danboh:
$IdentifierArray = [
"username" => $login->username,
"permissions" => $login->permissions,
"roles" => $login->roles,
"access" => $login->access
];
Why not use a regular PHP array? Like:
$IdentifierArray["username"] = $login->username;
$IdentifierArray["permissions"] = $login->permissions;
$IdentifierArray["roles"] = $login->roles;
$IdentifierArray["access"] = $login->access;
You can use the array_only helper to make your life easy:
$identifierArray = array_only(
json_decode($login, true),
['username', 'permissions', 'roles', 'access']
);
Another option would be to use the only() Collection method:
collect(json_decode($login, true))
->only(['username', 'permissions', 'roles', 'access'])
->all();
I am using Laravel 5.5 and I am declaring my model object the following:
$product = new product();
$product->name = $coinArr[$key];
$product->symbol = $symbolArr[$key];
$product->current_price = $priceArr[$key];
///save image to public folder
$fileName = basename($imgArr[$key]);
Image::make($imgArr[$key])->save(public_path('images/' . $fileName));
$product->asset_logo = $fileName;
//$product->updateOrCreate();
App/Product::updateOrCreate($product);
If the product does not exist in the database I would like to create it else just update it.
I tried the following two ways to use the updateOrCreate method. However, I receive the following error for App/Product::updateOrCreate($product);:
Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::updateOrCreate(), 0 passed in C:\Users\admin\Desktop\Coding Projects\laravel_proj\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 1455 and at least 1 expected
And the following error for $product->updateOrCreate();:
Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::updateOrCreate()
Any suggestions how to use updateOrCreate with my model object?
I appreciate your replies!
When you use updateOrCreate, you need to choose which attributes are used to determine if the product exists already. The function takes 2 arrays:
product::updateOrCreate([
'name' => $coinArr[$key] //Laravel will check if this model exists by name
],[
'symbol' => $symbolArr[$key] //if exists, will update symbol. if doesnt exist, will create new with this name and symbol
]);
That's not how the updateOrCreate() method works. In the first parameter you put an array with search conditions. If you want to search existing route by name for example, the correct syntax will be:
Product::updateOrCreate(
[
'name' => $coinArr[$key]
],
[
'symbol' => $symbolArr[$key],
'current_price' => $symbolArr[$key],
'asset_logo' => $fileName
]
);
The second parameter is array for creating a new object.
https://laravel.com/docs/5.5/eloquent#other-creation-methods
I am absolutely new in PHP and moreover in Laravel framework (I don't know if Laravel provides some utility class for this kind of tasks). I came from Java.
So I have the following problem:
Into a class I perform a call to a REST web service, something like this:
$response = $client->get('http://localhost:8080/Extranet/login',
[
'auth' => [
'dummy#gmail.com',
'pswd'
]
]);
$dettagliLogin = json_decode($response->getBody());
\Log::info('response: '.(json_encode($dettagliLogin)));
$response->getBody() contains the returned JSON object, this is the output of the previous \Log::info():
{
"id":5,
"userName":"Dummy User",
"email":"dummy#gmail.com",
"enabled":true
}
So I have the following problems:
1) What exactly returns the json_decode() function? I really can't understand because PHP is not strongly typed and I have not a declared return type.
This is the method signature:
function json_decode($json, $assoc = false, $depth = 512, $options = 0)
and in the related doc it says #return mixed. What exactly means "mixed"?
2) Anyway the main problem is: I have to use the content of the previous returned JSON object and put these value into the related field of an array like this:
$attributes = array(
'id' => HERE THE id FIELD VALUE OF MY JSON OBJECT,
'username' => HERE THE email FIELD VALUE OF MY JSON OBJECT',
'name' => HERE THE userName FIELD VALUE OF MY JSON OBJECT,
);
So I think that I have to parse the value of the $response->getBody() or of the json_decode($response->getBody()) to obtain these values. But how exactly can I do it? What is the neater way to do it? Does the Laravel framework provide some utility to do it?
For better understanding, let's first describe - what's JSON?
It's a way of representing objects (arrays, objects, etc) in a string.
1) What exactly returns the json_decode() function? I really can't
understand because PHP is not strongly typed and I have not a declared
return type. This is the method signature:
function json_decode($json, $assoc = false, $depth = 512, $options =
0) and in the related doc it says #return mixed. What exatly means
mixed?
json_deocde converts the JSON string into the original "structure" it represent.
#return mixed means that the returned value of json_decode can be any type of variable. If the JSON represent an array - it would be an array type, if it represent an object - it would be an object type.
2) Anyway the main problem is: I have to use the content of the
previous returned JSON object and put these value into the related
field of an array like this:
$attributes = array(
'id' => HERE THE id FIELD VALUE OF MY JSON OBJECT,
'username' => HERE THE email FIELD VALUE OF MY JSON OBJECT',
'name' => HERE THE userName FIELD VALUE OF MY JSON OBJECT,
);
In order to make sure which type of variable your JSON represent, you can use var_dump(json_decode($json));. Anyway, it's a class object.
Therefore:
$object = json_decode($json);
$attributes = array(
'id' => $object->id,
'username' => $object->email,
'name' => $object->userName,
);
If you json string is an object (not an array) it will return an object (of type stdClass). Mixed means it can be multiple things, so if it was a json array, you'd get an array.
Best thing to do is use json_decode, and then var_dump (or var_export) to see what you actually get.
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']);
In my controller I am retrieving records from my institutions table with the following fields
$params = array(
'fields' => array(
'Institution.id',
'Institution.name',
'Institution.about',
'Institution.picture'),
);
$institutions = $this->Institution->find('all',$params);
How can I prefix each 'Institution.picture' field with the full URL address, 'Institution.picture' itself only holds the name of the file.
I would also like to perform html_entity_decode() on each 'Institution.about' value from the returned set.
I know how to do this only without the framework if I make custom queries from scratch, then I would iterate each row and apply PHP functions to the field of interest. But is there a place in CakePHP (find or paginator) that I can specify such PHP manipulation on each field value from the returned set?
NOTE: I don't like to do this in the View, as I want to output it as json directly
You can define a virtualField for model:
public $virtualFields = array('image_url' => "CONCAT('/img/', Institution.picture)");
$params = array(
'fields' => array(
'Institution.id',
'Institution.name',
'Institution.about',
'Institution.picture',
'Institution.image_url'),
);
$institutions = $this->Institution->find('all',$params);
Unfortunaly MySQL doesn't have a function to decode HTML entities. You may utilize an afterFind() callback instead of virtualField. This lets you to decode entities as well as add a prefix.
CakePHP is php
Just iterate over the array and prepare it however you want:
$institutions = $this->Institution->find('all',$params);
$prefix = '/img/'; // <- define this
foreach ($institutions as &$row) {
$row['Institution']['about'] = html_entity_decode($row['Institution']['about']);
$row['Institution']['picture'] = $prefix . $row['Institution']['picture'];
}
If this is always required it can be applied to all finds via an afterFind method in the institution class.
I think you should do it in the View. See this example.
Hash::map can be very useful here. By specifying path you can only modify slices of the set.