Laravel 7: Showing error while passing multiple variable in str_replace - arrays

I'm facing error while passing multiple variable in str_replace function.
Error: Argument 1 passed to Xenon\LaravelBDSms\SMS::shoot() must be of the type string, null given, called in
Message Body:
Hello #name#,
Total Amount Purchased : #total#
Previous Due: #previous_due#
Deposit: #deposit#
Total Due: #total_due#
Controller:
$id = 1;
$sms_settings = SmsSetting::findOrFail($id);
if($sms_settings->order_create == 1){
$name = $request->name;
$previous_due = $customer->due;
$deposit = $request->deposit;
$total = $request->total;
$total_due = $request->total_due;
$msgs = $sms_settings->order_create_sms;
$msg = str_replace(array('#name#', '#total#','#previous_due#','#deposit#','#total_due#'), array($name,$previous_due, $deposit, $total, $total_due), $msgs);
$send= SMS::shoot($request->mobile, $msg);
}
Shoot Function:
public function shoot(string $number, string $text)
{
$this->sender->setMobile($number);
$this->sender->setMessage($text);
return $this->sender->send();
}
Here I'm using a Laravel Package for sending SMS to mobile number. How can I pass multiple variable in str_replace?

$request->mobile is null, confirm if you are passing the same in the request. Thats why the error.
Also use $request->validated('mobile'), that is safer.
str_replace seems to be fine. Take a look at Example, but Look at examples again, it might break if characters are overlapping with other arguments

I think the variable $msgs = $sms_settings->order_create_sms; contain empty that's why str_replace couldn't replace the data that you given so
$msg = str_replace(array('#name#', '#total#','#previous_due#','#deposit#','#total_due#'), array($name,$previous_due, $deposit, $total, $total_due), $msgs); , will return null.
I recommend checking $msgs again.

$msgs = $sms_settings->order_create_sms;
Make sure $msgs is not null place is_null($msgs) condition before feeding to str_replace
check more about str_replace: https://www.php.net/manual/en/function.str-replace.php

Related

unexpected result in a query in laravel

I’m a beginner in Laravel but have a problem at first. I wrote this query and I’m waiting for Sonya Bins as result but unexpectedly I see ["Sonya Bins"]. what’s the problem?
Route::get('products', function () {
$articles=DB::table('users')->where('id','2')->get()->pluck('name');
return view('products',compact('articles'));
});
pluck will return array if you want to get only single value then use value
// will return array
$articles=DB::table('users')->where('id','2')->get()->pluck('name');
//will return string
$articles=DB::table('users')->where('id','2')->value('name');
// output Sonya Bins
here is an example from the documentation:
if you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
Read more about it here
Hope it helps.
Thanks
pluck() used to return a String before Laravel 5.1, but now it returns an array.
The alternative for that behavior now is value()
Try this:
Route::get('products', function () {
$articles=DB::table('users')->where('id','2')->get()->value('name');
return view('products',compact('articles'));
});
I think it's easier to use the Model + find function + value function.
Route::get('products', function () {
$articles = User::find(2)->value('name');
return view('products',compact('articles'));
});
pluck will return the collection.
I think id is your primary key.
You can just get the first record, and call its attribute's name:
DB::table('users')->where('id','2')->first()->name;
or
DB::table('users')->find(2)->name;
First thing is that you used invalid name for what you pass to view - you don't pass articles but user name.
Second thing is that you use get method to get results instead of first (or find) - you probably expect there is only single user with id = 2.
So to sum up you should use:
$userName = DB::table('users')->find(2)->name;
return view('products',compact('userName'));
Of course above code is for case when you are 100% sure there is user with id = 2 in database. If it might happen there won't be such user, you should use construction like this:
$userName = optional(DB::table('users')->find(2))->name;
($userName will be null if there is no such record)
or
$userName = optional(DB::table('users')->find(2))->name ?? 'No user';
in case you want to use custom string.

Return Stringbuilder when using variable name to create string builder

trying to return string builder in a loop. is this workable.. I am collecting a list with each(), then appending 'it' to "scriptBldr_" to create a different object name each time to hold the string. then I collect the object names in a list. And trying to return using a for loop for each object name. But it's failing.
List.each {
String builderstring = "scriptBldr_" + it.replaceAll (/"/, '')
StringBuilder $builderstring = StringBuilder.newInstance()
if (ValidUDA == "Region") {
$builderstring <<"""
XYZCode
"""
StringBuilders.add(builderstring)
}
}
for(item in StringBuilders)
{
return item
}
I guess the following code does what you intended to code:
def myList = ['Hello "World"', 'asb"r"sd']
def ValidUDA = "Region"
def builders = [:]
myList.each {
String builderstring = "scriptBldr_" + it.replaceAll (/"/, '')
builders[builderstring] = StringBuilder.newInstance()
if (ValidUDA == "Region") {
builders[builderstring] <<"""
XYZCode
"""
}
}
return builders
A return statement will immediatly return from the method and hence will exit the loop and only called once. So, I guess, what you wanted to achieve is to return a list of StrinngBuilders.
some hints:
it is unusual in Groovy to start a variable with $ and you can run into problems with such a naming
when asking a question on SO, try to come up with a working example. As you can see, you example was missing some definitions
Update: as you've stated in you comment that you tryed to create dynamic variable names, I've updated the code to use maps. The returned map now contains the StringBuilders together with their names.

Getting the number of rows considering a time frame

I want to get the number of rows of a certain table considering a time frame.
I'm using CakePHP 3.7.
Here you can see my code (from the controller class) :
public function nbOfDefense($dateIn, $dateOut){
if($dateIn!=null && $dateFin!=null){
$conditions = array('thesis.date_end BETWEEN ? and ?' => array($dateIn, $dateOut));
$query = $this->Thesis->find('all',
array('conditions'=>$conditions));
die(strval($query->count()));
return $query;
}else{
$query = $this->Thesis->find('all');
die(strval($query->count()));
return $query->count();
}
}
I'm testing my function through my browser using this URL :
http://localhost:8888/thesis/nbOfDefense/2003-02-01/2019-04-13
What I want my function to do, is to, get in parameters two dates :
If those two dates are not null, you get the number of rows that between the two dates considering a date stored in the table you're consulting.
If the dates are null, then you get the total number of rows of the table.
And return an int, which is the number of rows that are between those two dates.
I feel like the problem here is how I handle my condition, because counting the total number of rows works perfectly (the else part of the code).
The error I have right now with this code is the following :
Cannot convert value of type array to string
it's pointing to this line :
die(strval($query->count()));
I guess the count function returns an array (weird because it doesn't when I count all rows without conditions). I also tried this :
die(strval(sizeof($query->count())));
But I get the same error as before (cannot convert array to string)
I must be missing something but I don't know what...
Try:
use Cake\ORM\Query;
use Cake\Database\Expression\QueryExpression;
class MyController extend AppController
{
public function nbOfDefense($dateIn = null, $dateOut = null)
{
$query = $this->Thesis->find();
if ($dateIn && $dateOut) {
$query->where(function (QueryExpression $exp, Query $q) use ($dateIn, $dateOut) {
return $exp->between('date_end', $dateIn, $dateOut);
});
}
$count = $query->count();
$this->set(compact('query', 'count'));
}
// ..
}
and read:
https://book.cakephp.org/3.0/en/orm/query-builder.html
https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html

Symfony2.8 with sonataEcommerce2.1.1 single Product page "requires that you provide a value for the "$product" argument"

I am using sonata-ecommerce. When I try to open single product page then Controller error occure.
Here is detailed error.
"Application\Sonata\ProductBundle\Controller\ProductController::viewAction()" requires that you provide a value for the "$product" argument (because there is no default value or because there is a non optional argument after this one).
No need to change the extend.
Here is my Code:-
Copy viewAction from vendor/sonata-project/ecommerce/ProductBundle/controller/Basecontroller and place it in src/Application/Sonata/Controller/ProductController.
After copy assign $product = null in the ApplicationSonataProductBundle.
public function viewAction($product = null) {
//Add these lines.
$slug = $this->getRequest()->get('slug');
$productId = $this->getRequest()->get('productId');
$product = $this->get('sonata.product.set.manager')->findEnabledFromIdAndSlug($productId, $slug);
....
}

Use twitchAPI with cake

since a few hours i'm trying to implement the twitchAPI in my cake projet. a long time ago i made this little script in basic php.
$channelName = "gamespot";
$json_file = #file_get_contents("http://api.justin.tv/api/stream/list.json?channel={$channelName}", 0, null, null);
$json_array = json_decode($json_file, true);
#$json_array[0] && $json_array[0]['name'] == "live_user_{$channelName}";
#$title = $json_array[0]['channel']['status'];
#$game = $json_array[0]['meta_game'];
#$chanel_view = $json_array[0]['channel_count'];
#$totalchanelview = $json_array[0]['channel_view_count'];
but i don't know how to add this lines on my controller
For know i've just find this
public function twitch() {
$json = file_get_contents('http://api.justin.tv/api/stream/list.json?channel=manvsgame');
$twitch = json_decode($json);
$totalchanelview = $twitch[0]['channel_view_count'];
$this->set('twitch', 'totalchanelview');
}
but of course i've this error
Fatal error: Cannot use object of type stdClass as array in /Users/*/Desktop/Websites/**/app/Controller/UsersController.php on line 29
anyone can explain to me how i can use this API?
thanks in advance and have a nice day/night :)
okey first thanks to help me. i still have a little "logic problem"
my function is something like that:
public function twitch() {
$json = file_get_contents('http://api.justin.tv/api/stream/list.json?channel=gamespot');
$twitch = json_decode($json, true);
$this->set('json', $twitch);
}
but know, what can I write to my view to see my informations (like the title of my stream for exemple.
I test with
echo $twitch[0]['title']; (it's my line 1)
bit i've this error
Notice (8): Undefined variable: twitch [APP/View/Users/admin_dashboard.ctp, line 1]
$twitch = json_decode($json, true); // add true param
$twitch[0]['channel_view_count'];
adding true returns the data as an associated array instead

Resources