Laravel 4 How to pick random language string? - php

I am using Laravel 4 and I am creating an authentication app. I am stuck in a very small feature I want to implement but for me it's needed. When the user logs in I want to display a random array of "greetings" like "Howdly, username" or "Hey there, username" etc. from my language file. Is there any way I could do that?
I tried something like that:
{{ array_rand(trans('en.greetings') }}
But it displays the variable given for each string instead (for example hey_there which should be "Hey there")
My array:
"greetings" => array(
"howdly" => "Howdly",
"hello" => "Hello",
"hello_there" => "Hello there",
"hey" => "Hey",
"arr" => "Arr"
),

You could just shuffle the array each time and print the first index
//I am creating an array here, but you could assign whatever
$greetings = array(
"howdly" => "Howdly",
"hello" => "Hello",
"hello_there" => "Hello there",
"hey" => "Hey",
"arr" => "Arr"
);
shuffle($greetings);
echo reset($greetings); //will print the first value, you can return it or assgn it to a variable etc

I had the similar use case where I had to give random string back to the user. I'm using Laravel 5, and this is how I solved it. Your language file could look like this:
return[
"greeting_1"=>"myString 1",
"greeting_2"=>"myString 2",
"greeting_3"=>"myString 3",
];
I added a custom helper to my application and wrote a helper method to choose a response in random. My method looks like this:
function getRandomPrompt($key,$params=array()){
$key=explode(".",$key);
if(count($key)!= 2)
throw new Exception("Invalid language key format");
$file=$key[0];
$msgKey=$key[1];
//Get all the keys of the file
$keys_from_file=Lang::get($file);
//Filter all the prompts with this key
foreach ($keys_from_file as $file_key=>$value){
$key_parts=explode("_",$file_key);
if(($key_parts[0])!==$msgKey)
unset($keys_from_file[$file_key]);
}
$selected_key=array_rand($keys_from_file);
if(count($keys_from_file)>=1)
return Lang::get($file.".".$selected_key,$params);
else
return($file.".".$msgKey);
}
This helper simply looks for all possible keys, and return one string in random. You can also pass a parameter array to it. Now, whenever you want a string, you can get it by calling:getRandomPrompt("filename.greeting")

Was looking for something like this, but eventually I found another solution.
In your lang file:
return [
'String',
'Thong',
'Underwhere?',
];
Your blade solution:
{{ __('messages')[array_rand(__('messages'))] }}

Related

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");
// => ""

Laravel - pluck with specified keys

I have a line of code similar to the following:
Sport::pluck('id', 'name)
I am dealing with frontend JavaScript that expects a list in this format:
var list = [
{ text: 'Football', value: 1 },
{ text: 'Basketball', value: 2 },
{ text: 'Volleyball', value: 3 }
...
]
I am trying to figure out how I can somehow transform the id and name values that I pluck from my model to a format similar to the Javascript list.
If that's unclear, I am looking to end up with an associative array that contains two keys: text and value, where text represents the name field on my model, and where value represents the id of the model - I hope this makes sense.
How would I approach this?
I initially tried something like this (without checking the documentation)
Sport::pluck(["id" => "value", "name" => "text]);
But that isn't how you do it, which is quite clear now. I've also tried some map-related snippet, which I cannot seem to Ctrl-z to.
Any suggestions?
Another method is to use map->only():
Sport::all()->map->only('id', 'name');
The purpose of pluck is not what you intend to do,
Please have a look at below examples,
Sport::selectRaw("id as value, name as text")->pluck("text","value");
// ['1' => 'Football', '2'=>'BasketBall','3'=>'Volleyball',...]
Syntax
$plucked = $collection->pluck('name', 'product_id');
// ['prod-100' => 'Desk', 'prod-200' => 'Chair']
Please see the documentation.
Your output is possible using simple code.
Sport::selectRaw('id as value, name as text')->get();
You could use map.(https://laravel.com/docs/5.8/collections#method-map)
$mapped = Sport::all()->map(function($item, $index) {
return [
"id" => $item["id"],
"name" => $item["text"]
];
});
This is the easiest way. Actually Laravel offers a better way for it. You can use api resources to transform your data from eloquent for the frontend:
https://laravel.com/docs/5.8/eloquent-resources
Try with toArray function:
Sport::pluck('id', 'name)->toArray();
Then you can return your result with json_encode php function;

Best PHP Function To Output One Choice Out of Many

I'm importing a product list, and each item has a department number. Each number correlates with a department, i.e.
Handguns
Used Handguns
Used Long Guns
Tasers
Sporting Long Guns
There are 43 departments. Would I just do one long if statement like:
`<?php
if ($var = 1)
echo "Handguns";
else
if ($var = 2)
echo "Used Handguns";
etc.....
?>`
EDIT: I'm able to get an if statement like this to work:
function test($cat) {
if ($cat = 33)
echo "Clothing";
}
but using any array like this:
`$departments = [
33 => Clothing,
];
function getDepartment($id, $departments) {
echo $departments[$id];
}`
I've been unable to get that to work. I'm using wordpress and putting this in functions.php and calling the function from a plugin.
Should I just stick with a big if Statement?
2nd EDIT: Got it to work by including the array inside the function:
function getDepartment($id, $departments) {
$departments = [
"1" => "Handguns",
"2" => "Used Handguns",
"3" => "Used Long Guns",
"4" => "Tasers",
"5" => "Sporting Long Guns",
"6" => "SOTS ",
...
"41" => "Upper Receivers/Conv Kits",
"42" => "SBR Barrels and Uppers ",
"43" => "Upper/Conv Kits High Cap"
];
if (isset($departments[$id])) {
return $departments[$id];
}
return 'Uncategorized';
}
and inside wpallimport, the category call looked liked this: [getDepartment({column_4[1]})]
Create an array of the departments using their ID as their array key. Then you can access them using basic array variable syntax:
$departments = array(
1 => Handguns,
2 => Used Handguns,
3 => Used Long Guns,
4 => Tasers,
5 => Sporting Long Guns
);
$var = 2;
echo $departments[$var]; // prints "Used Handguns"
You can construct this array however you like. It can be hardcoded in a config file or more likely created from a SQL query.
Just make sure that the key exists in your array before you try to access it or else you get an undefined index error message. You probably would be wise to place this in a function so you can abstract this code and reduce duplicated code on each attempt to access this array.
function getDepartment($id, $departments) {
if (isset($departments[$id])) {
return $departments[$id];
}
return 'Invalid Department'; // or whatever you want if the value doesn't exist
}
echo getDepartment(2); // prints "Used Handguns"

Laravel: Add data to the Input::all()

I am grabbing the values from the parameters in the URL domain.com?para=value in the controller using
Input:all()
Is there a way to add more values to the Input:all() in the controller?
I have tried $_POST['para'] = "value and $_GET['para'] = "value" but no luck.
I've gone through the docs but cannot find anything.
Thanks
More Info
Here is what is returned
{
"param_1" => "value",
"param_2" => "value",
"param_3" => "value",
}
I would like to add another param into the Input:all()
{
"param_1" => "value",
"param_2" => "value",
"param_3" => "value",
"NEW_PARAM" => "NEW VALUE",
}
In laravel 5, you can use
Request::merge(['New Key' => 'New Value']);
or by using request() helper
request()->merge(['New Key' => 'New Value']);
You should never need to add anything to Input. You should assign Input like so...
$arr = Input::all();
And then add to $arr like so...
$arr['whatever'] = 'whatever';
If you need to get that value in another part of the stack, try to pass it through yourself.
Cheers.
Best way to add data into the input::all() in laravel.
Solution 1
add Request package at the top of the page.
use Request;
Then add following code into your controller.
Request::merge(['new_key' => 'new_value']);
Solution 2
You can assign all the Input::all(); to a variable and then you can add new data to the variable. Like below.
$all_input = Input::all();
$all_input['new_key'] = 'new_value';
Add an input value on the fly inside a request instance
public function store(Request $request){
$request->request->add(['new_key' => 'new_value']);
}
Remove data from an input value on the fly inside a request instance
public function store(Request $request){
$request->request->remove('key');
}

add value to JSON of title

I search a lot in stack and google try to find the answer which seems to be easy but I'm still stuck with it
I write a code to encode json with values I wanted from . and I would like to add a key / value to the JSON
the JSON is as following structure
{
- files: [
{
title: "works",
- tracks: [
{
title: "File",
format: "mp3"
}
]
},
-{
title: "season1",
tracks: [
{
title: "Button-1",
format: "wav"
},
-{
title: "Beep-9",
format: "wav"
}
]
}
]
}
I want to add to that a key and its value at the beginning to the json as properties under the title files , I mean that can be read by code as
json[files][new_key]
I tried to set that value like this
$json['new_key'] = "new_value";
but this causes adding numbers to the arrays in json , I don't why they numbered
this numbers affect my reading way of the json as JSONModel in my iOS app
so , I hope you can help me
thanks in advance
Assuming that the new value you want to add varies by file, you would need to loop through $json[files] and insert them per key/value pair.
<?php
for($i=0; $i<count($json); $i++)
$json[files][$i]["new_key"] = "value";
?>
I'm still not sure what you have exactly, but it seems you are trying to manipulate the json string.
If done correctly, that is probably the most efficient solution, but what you could also do is:
use json_decode to generate an array from your json string;
locate the correct section / sub-array where you want to add your data;
use array_unshift to prepend your new key - value pair;
use json_encode to generate a json string from your complete array.
The reason you're getting numbers appearing is because you're adding a key to an array (which functions more or less as a list in JS). So before you basically have the object "files" as a list of objects zero-indexed like any other JS array. When you add the key, JS simply adds your key to the end of your present keys (in your case 0 and 1).
It seems like you have a list of multimedia objects where each has a title and a list of tracks. The most straightforward way to solve your issue would be as follows:
$fileItem['title'] = 'works';
$fileItem['tracks'] = array(
array(
'title' => 'File',
'format' => 'mp3'
)
);
$json['files'][] = $fileItem;
$fileItem['title'] = 'season1';
$fileItem['tracks'] = array(
array(
'title' => 'Button-1',
'format' => 'wav'
),
array(
'title' => 'Beep-9',
'format' => 'wav'
)
);
$json['files'][] = $fileItem;
Then you JSON encode it and return it as you normally would. You can put the above in a loop as well. I lack enough context to recommend exactly how.

Categories