How can I use an array values outside a foreach loop in Laravel 5.4?
Here is the code :
public function index(Request $request)
{
$name = $request->input('keyword');
$category = $request->input('category');
$catkeywords = array(DB::table('keywords')->pluck($category));
foreach ($catkeywords as $catkeyword) {
$string = implode(',',$catkeyword);
}
echo $string;
}
I don't know why it doesn't work !
I just want the returned keywords from database to combine them with some text and to use for some API queries.
In other words, I want the list of keywords outside of the loop.
For using in an API query like this :
http://api-url/query?id=domain1.com,domain2.com,domain3.com
$catkeywords returns a json formatted list of keywords.
Now I want to combine these keywords with a user-inputted value and add a ".com" suffix,
then separate them using commas and use them on query url as a variable.
P.S : I'm using guzzlehttp for sending requests to the API. So it should be placed on :
'DomainList' => $domainlist
How can I do that ?
If you're using laravel, you should consider taking advantages of their collections:
https://laravel.com/docs/5.4/collections#method-implode
public function index(Request $request)
{
$name = $request->input('keyword');
$category = $request->input('category');
$catkeywords = DB::table('keywords')->implode($category, ',');
echo $catkeywords;
}
Laravel collections have a command for imploding the array, so there's no need to use pluck and loop through the array unless you plan on doing other operations on the data too.
EDIT: Based on updated question, it sounds like you're looking for something like this:
public function index(Request $request)
{
$name = $request->input('keyword');
$category = $request->input('category');
$catkeywords = DB::table('keywords')->pluck($category); //You don't need to wrap this in an array()
$keywords = []; //Create a holding array
foreach ($catkeywords as $catkeyword) {
$keywords[] = $catkeyword . '.com'; //Push the value to the array
}
echo implode(',', $keywords); //Then implode the edited values at the end
}
when you use pluck() method then it return array of given name
so you dont have need to use foreach loop
just use
$catkeywords = array(DB::table('keywords')->pluck($category));
echo implode(',',$catkeyword);
You try do that
public function index(Request $request)
{
$name = $request->input('keyword');
$string = '';
$category = $request->input('category');
$catkeywords = array(DB::table('keywords')->pluck($category));
foreach ($catkeywords as $catkeyword) {
$string .= implode(',',$catkeyword);
}
echo $string;
}
Related
Hello There I need Help To Update on Vehicle Wies on Specific Dates.I'm Attaching Form image and Here is my Controller code.
public function add_vehicle_expense(Request $request)
{
$veh = array('veh_reg_num' => $request->veh_reg_num);
foreach ($veh as $data) {
print_r($request->date[$data]);
dd();
$veh = Sale_report::where('date',$request->date[$data])->where('veh_reg_num', $request->veh_reg_num[$data])->update(['diesel_qty'=> $request->qty[$data], 'diesel_rate'=> $request->rate[$data], 'diesel_amount'=> $request->total_amount[$data], 'other_expense'=> $request->other_exp[$data]]);
}
if ($veh) {
return redirect()->back()->with('Data Store Successfully');
}
//$veh = Sale_report::where('date',$request->date)->where('veh_reg_num', $request->veh_reg_num)->update(['diesel_qty'=> $request->qty, 'diesel_rate'=> $request->rate, 'diesel_amount'=> $request->total_amount, 'other_expense'=> $request->other_exp]);
/* foreach ($request->date as $reg_num => $key ) {
$s = Sale_report::where('date',$request->date[$reg_num])->where('veh_reg_num',$request->veh_reg_num[$reg_num])->first();
$s->diesel_qty = $request->qty[$reg_num];
$s->diesel_rate = $request->rate[$reg_num];
$s->diesel_amount = $request->total_amount[$reg_num];
$s->other_expense = $request->other_exp[$reg_num];
$s->update();
} */
}
I have try to Update Data by matching Each Vehicle Number with Date Some times it Show ErrorException Attempt to read property on int,ErrorException Undefined array key "data"
I have Found The Solution of this Problem.
I've use implode(',' , $request->veh_reg_num) Then I use $datas = explode() function then I use foreach() With exploded Vairable as foreach($datas as $data => $value){
match the each row that with $data array then I Update the values to data base }
I am building an API with laravel, so I am trying to pass Laravel's Eloquent functions as string and execute them in the controller, actually I am sending a JSON object but I am converting it to a string in backend, here is what I tried to do
API URL with parameters:
http://www.example.com/api/articles?parameters={"orderByDesc":"'created_at'", "limit":"2"}
Controller side:
$json = json_decode(request('parameters'), TRUE);
$query = '';
foreach ($json as $function => $value){
$query .= $function.'('.$value.')->';
}
$query = $query.'get();';
return $query;
Output:
orderByDesc('created_at')->limit(2)->get();
Now how can I execute this string as code on the model, example:
$articles = Article::orderByDesc('created_at')->limit(2)->get();
I couldn't concatenate like this: Article::.$query
And I can't use PHP's eval()
The idea is to use Laravel's Eloquent functions inside a JSON object and pass them in one URL parameter.
Thanks
Maybe you should try this.
$json = json_decode(request('parameters'), true);
$query = Article::query();
foreach($json as $function => $value){
$query->{$function}($value);
}
$query = $query->get();
return $query;
You can run function on object with ->{$func_name} syntax
Edit: You can pass multiple arguments too. But you can check if whether value is array or not:
foreach($json as $function => $value){
if(is_array($value)) {
$query->{$function}(...$value);
} else {
$query->{$function}($value);
}
}
In this case you can have: {"orderByDesc":"'created_at'", "limit":"2", "where": ["column_name", "LIKE", "%SOME_STRING"]} and it will generate query equivalent to: ->where('column_name', 'LIKE', '%SOME_STRING')
I have a database table named 'services'. With the function below I get all the records from that table. This function is located in my ServicesController.php.
public function index() {
$roadmap = Roadmap::all();
return view('services', compact('roadmap'));
}
Now in my view I also do the following:
<?php
foreach($roadmap as $roadmap_item) {
$new = array();
$splitted = explode("|", $roadmap_item->steps);
foreach($splitted as $split) {
$new = explode(":", $split);
}
}
?>
Lets say I get the string 'step1:hello|step2:bye' back from '$roadmap-item->steps'. I split them in substrings with explode etc. This is working by the way.
But is there a way I can manipulate the string in the Controller so my view will be nice and clean without many php code and still remain the variable $roadmap with all the database records.
Kind regards,
Dylan
I think you can do very similar things in your controller. Do foreach in your controller first then make a changes in every item in your collection and pass the new collection.
For example:
$roadmaps = Roadmap::all();
foreach($roadmaps as $roadmap){
$roadmap->something = " the changes you want to do as string " . $roadmap->something;
$roadmap->save();
}
return view('services', compact('roadmaps'));
or
$roadmaps = Roadmap::all();
$new = new Collection();
foreach($roadmaps as $roadmap){
$new[] = array('roadmap' => $roadmap, 'something' => $roadmap->string . " etcetc ")
$new->save();
}
return view('services', compact('new'));
I want to pass data from laravel controller to view. the problem i am having is that the data being passed is coming from a database table and its being stored in a variable using nested foreach loop but the variable is being overritten with each loop.
Here is the Code.
public function generateContract(Request $request){
foreach($request->ids as $id){
$contract = explode(",", $id);
$this->techId[] = $contract[0];
$this->meetingId[] = $contract[1];
$this->contractId[] = $contract[2];
}
$names = contract::whereIn('technician_id', $this->techId)->whereIn('meeting_id', $this->meetingId )->get();
foreach($names as $name){
$names_arr[] = $name->firstName;
}
$unique_names = array_unique($names_arr);
foreach($unique_names as $unique_name){
$functions[] = Contract::where('firstName', $unique_name)->whereIn('meeting_id', $this->meetingId)->whereIn('id', $this->contractId)->get();
}
return view('contract.generated_contract', compact('unique_names', 'functions'));
}
My question is how can i pass the $functions variable to view without it being overwritten. I have tried using array but the array is also being overritten with each loop.
I'm learning Yii Framework . I'm working with a framework first time, i need some advices.
I have a getSocials() function on my Controller .
private function getSocials($id)
{
$socials=Socials::model()->find("socials_user=$id");
foreach ($socials as $social)
{
$type = $social["socials_type"];
$allSocial .= "<li>$type</li>";
}
return $allSocial;
}
(it's private because i'm calling it from another function only).
I'll explain it line by line,
$socials=Socials::model()->find("socials_user=$id");
Getting datas from database which socials_user collumn equals to $id, via Socials model.
foreach ($socials as $social)
$socials returning as an array because there are a few lines which socials_user collumn equals to $id on database .
$allSocial .= "<li>$type</li>";
On foreach loop, adding <li>...</li> to end of string, so $allSocial will be <li>...</li><li>...</li>...
BUt i'm getting Undefined variable: allSocial error . When i remove dot from front of equal symbol (=), it's working. But this time on foreach loop, it's overwriting always and finally $allSocial containing only last <li>...</li>
Are there any logical mistake ?
$allSocial is not defined anywhere, you cant attach a string to an undefined variable. Try it like this:
private function getSocials($id)
{
$socials=Socials::model()->find("socials_user=$id");
$allSocial = '';
foreach ($socials as $social)
{
$type = $social["socials_type"];
$allSocial .= "<li>$type</li>";
}
return $allSocial;
}
You need to define $allSocial before you try to concatenate anything to it. You may also want to consider returning an array instead so you can easily access the different strings.
private function getSocials($id) {
$socials=Socials::model()->find("socials_user=$id");
$allSocial = array();
foreach ($socials as $social)
{
$type = $social["socials_type"];
$str = "<li>$type</li>";
array_push($allSocial, $str);
}
return $allSocial;
}
find function will return only one record which is not an array so foreach will never execute
replace the code with following to get it working right :
private function getSocials($id)
{
$socials=Socials::model()->findAll('socials_user=:socials_user',
array(':socials_user'=>1));
$allSocial = '';
foreach ($socials as $social)
{
$type = $social["socials_type"];
$allSocial .= "<li>$type</li>";
}
return $allSocial;
}