Replace string by values from collection in Laravel - laravel

I am beginner ini Laravel. I have this code:
$value = "Szanowni Państwo,
Status został zmieniony.
<br/><br/>
Osoba odp.: {osoba_odpowiedzialna}<br/>";
$collection = collect(
(object) [
'osoba_odpowiedzialna' => $responsiblePerson,
'rodzaj' => data_get($term, 'termType.name'),
'klient' => data_get($term, 'client.name'),
'sprawa' => data_get($term, 'caseInstance.internal_signature'),
'status' => data_get($term, 'termStatus.name'),
'adres' => route('calendar.index')
]
);
in result $collection I have:
https://ibb.co/Kz18CJ1
I need replace my $value - values from $collection by key: osoba_odpowiedzialna, klient, rodzaj etc.
How can I make it?

Your question is not very clear, sorry, but I think what you want is this:
$replacedText = preg_replace('/{osoba_odpowiedzialna}/',
$collection['osoba_odpowiedzialna'], $value);
//this will yield (last line below)
//Osoba odp.: Łukasz Moderator
After your comments:
$collection->map(function($item, $key) use (&$value){ //$collection->each(.. should also be fine
$value = preg_replace('/{'.$key.'}/', $item, $value);
});

Related

Laravel 7 : Why I am Getting Only First Array? I want to Fetch All Category ID data

I am getting a issue while fetching array data in Laravel 7 here is my code
https://i.stack.imgur.com/IZbg6.png
and the result is : https://i.stack.imgur.com/ByKaV.png
It is fetching only one array data. I don't know where i am missing.
If anybody know the error, please help me to solve this issue.
Below is my code ======================================
$cat_id = $category->id;
$location = null;
$sites = \DB::select( 'SELECT id FROM sites WHERE category_id = ?', [ $category->id ]);
$all = [ ];
foreach( $sites as $s ) {
$all[ ] = $s->id;
}
$sites = $all;
$all_cat_id = implode(',', array_map('intval', $sites));
// echo "<pre>";
// print($all_cat_id);
// die();
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->where('id', [$all_cat_id])->paginate(10);
return view('browse-category', [ 'activeNav' => 'home',
'reviews' => $reviews,
'sites' => $sites,
'category' => $category,
'all_categories' => $all_categories,
'location' => $location
]);
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->whereIn('id', [$all_cat_id])->paginate(10);
You need to use whereIn() instead of where()
whereIn() checks column against array.

Laravel : array_push not working in collection->each() iterator

I have grouped collection and I iterate it using each() function.Inside the each function I want to add element to some array.But it is not working.Any idea?
$dataSet1 = [];
$appointments = [
['department' => 'finance', 'product' => 'Chair'],
['department' => 'marketing', 'product' => 'Bookcase'],
['department' => 'finance', 'product' => 'Desk'],
];
$groupData = collect($appointments)->groupBy('department');
$groupData->each(function ($item, $key) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Laravel version : 8.35.1
You need to pass the array to the function with use:
$groupData->each(function ($item, $key) use (&$dataSet1) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Pass-by-reference (&) is needed as long as $dataSet1 is not an object instance.

Got error 'Trying to get property 'id' of non-object' even dd function return it right

I have to display data from post table based on user. But, I always get error
Trying to get property 'id' of non-object
even though dd($user) and dd($post) return it right. dd($user) return 1st row, dd($post)return 1st row. When commenting all the 'dd' function , I got 'Trying to get property 'id' of non-object' at $post = post::find($user->id);. However when I dd($post->article_title, $post->id),I do get the data
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM) {
$user = User::find($RMM->id);
$post = post::find($user->id);
$post_data = array('title' => $post->article_title,
'name' => $post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);
result of dd(post)
result of dd(user)
Be aware, when you dd() something it die at first iteration in foreach, error may occurs in another iterates, maybe id 1 is exists in user but 3 or 4 is not.
use something like this:
$RMM_details = Company::where('branch', 'RMM')->get();
$RMM_details->transform(function($RMM)use($user){
$user = User::find($RMM->id);
$post = post::find($user->id);
return [
'title' => $post->article_title,
'name' => $post->author,
'date' => date('Y-m-d', strtotime($post->date)),
];
});
It might be because
$post = post::find($user->id);
is returning null value at some stances.
Check if it is empty or not by using the function empty and try again.
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM) {
$user = User::find($RMM->id);
if(!empty($user->id){
$post = post::find($user->id);
}
$post_data = array('title' => $post->article_title,
'name' => $post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);

Use Array Data in CodeIgniter Model as SQL?

In my controller, I am passing data to the model using the following code:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
var_dump($data);
$this->Login_model->insert_entry($data);
In my model, what I want to do is use the gid value as part of an SQL statement, like so:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = $gid');
Obviously this doesn't work, so I'm just wondering how I get the gid from $data and use it in my SQL statement?
Tested using
$get_gid = $this->db->where('gid', $data['gid'])->get('users');
print_r($get_gid);
However output is:
CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id]
=> Resource id #33 [result_array] => Array ( ) [result_object] => Array ( ) [custom_result_object] => Array ( ) [current_row] => 0
[num_rows] => 0 [row_data] => )
Did you try gid = $data['gid']
I assume that yours model method looks like this:
insert_entry($data)
{
here active record or query...
}
If yes try to display query to see if $data['gid'] is visible there
You can try it by
$this->db->get_compiled_select();
Or after query runs
$this->db->last_query();
Try this way:
$data = array(
'gid' => $this->input->post('gid'),
'name' => $this->input->post('name'),
'pic' => $this->input->post('pic'),
'link' => $this->input->post('link')
);
$gid = $data['gid'];
$this->db->where('gid',$gid);
$this->db->from('users');
$query = $this->db->get();
if($query)
{
//you can return query or you can do other operations here like insert the array data
//$this->db->insert('yourtable',$data);
return $query;
}
else
{
return FALSE;
}
You can try:
$get_gid = $this->db->query('SELECT * FROM users WHERE gid = '.$data['gid'].');
You just Forget after query $query->result().

Codeigniter - Sending a query result_arry() to a View for form_dropdown

I am using form_dropdown() and have a a problem below:
The form code is:
echo form_dropdown($level,$level_options,'1');
It works when I use
$level_options = array(
'1' => 'Grade 6',
'2' => 'Grade 7'
);
but not when I send a $data['levels'] from controller to view
For reference, the model database retrieve code is:
public function getAllLevelNames() {
$query = $this->db->query("SELECT level_description from levels ORDER BY level_description");
return $query->result_array();
}
The Problem
The problem is I get a dropdown pick list with:
0
Grade 6
1
Grade 7
The indexes are greyed out.
How do I get rid of the indexes?
Thanks in advance!
P.S.
I seem to have the form working now with a data['levels'] sent to the view. Now, the following code in my view seems to return "null" to my controller. Any ideas why please?
$level = array(
'name' => 'level',
'id' => 'level',
'value' => '1',
'maxlength' => '50',
'size' => '50',
'style' => 'width:50%',
);
$level_options = $levels;
echo "<p>Level: ";
echo form_dropdown($level,$level_options,'1');
Thanks!
You'll need to loop through your results_array and create a new array which is formatted correctly.
$query = $this->db->query("SELECT level_description from levels ORDER BY level_description");
$for_dropdown = array();
foreach ($query->result_array() as $row) {
$for_dropdown[$row->level_description] = $row->level_description;
}
return $for_dropdown;
Also I'm not sure how your levels table is structured, but usually you'll have an ID of some sort, which will be the primary key. If you do have that, you can include it in your query and have something like this instead:
$query = $this->db->query("SELECT id, level_description from levels ORDER BY level_description");
... // other code
$for_dropdown[$row->id] = $row->level_description;

Resources