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

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.

Related

Get Raw SQL of Insert Statement

I am looking for a way to get the correct SQL queries for an INSERT statement. I'm having to export this data for use in another (non-laravel) system. The post at How to get the raw SQL for a Laravel delete/update/insert statement? got me part of the way there but my queries are still parameterized:
Post::all()->each(function($post)
{
$builder = DB::table('posts');
$insertStatement = $builder->getGrammar()->compileInsert($builder->select(['created_at', 'title']), [
'created_at' => $post->created_at,
'title' => $post->title
]);
Storage::disk('sql')->append('posts-latest.sql', $insertStatement);
dump($insertStatement);
}
this results in...
insert into `posts` (`created_at`, `title`) values (?, ?)
So I've managed to set the fields to be updated but how to swap out the parameters for real values?
You can do this:
Post::all()->each(function($post){
$builder = DB::table('posts');
$grammar = $builder->getGrammar();
$values = [
'created_at' => $post->created_at,
'title' => $post->title
];
$table = $grammar->wrapTable($builder->from);
if (!is_array(reset($values))) {
$values = [$values];
}
$columns = $grammar->columnize(array_keys(reset($values)));
$parameters = collect($values)->map(function ($record) use ($grammar) {
$record = array_map(function($rec){
$rec = str_replace("'", "''", $rec);
return "'$rec'";
},array_values($record));
return '('.implode(', ', $record).')';
})->implode(', ');
$insertStatement = "insert into $table ($columns) values $parameters";
// $insertStatement should contains everything you need for this post
});
I ended up discovering DB::pretend which will generate the query without running it. Then it's a case of substitution. It seems that there is no way to get the raw SQL without substitution due to the use of parameters.
Post::all()->each(function($post)
{
$builder = DB::table('posts');
$query = DB::pretend(function() use ($builder, $post)
{
return $builder->insert([
'created_at' => $post->created_at,
'title' => $post->title,
'content' => $post->content,
'featured_image_link' => $post->featured_image_link,
'slug' => $post->slug
]);
});
$bindings = [];
collect($query[0]['bindings'])->each(function($binding) use (&$bindings)
{
$binding = str_replace("'", "\\'", $binding);
$bindings[] = "'$binding'";
});
$insertStatement = Str::replaceArray('?', $bindings, $query[0]['query']);
Storage::disk('sql')->append('posts-latest.sql', $insertStatement.';');
});

Replace string by values from collection in 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);
});

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)),
);

Update multiple rows in Database Table

I want to update multiple rows. Here is my controller file:
$ids = [$request->get('com_id')];
$name = [$request->get('com_name')];
$stat = [$request->get('com_status')];
$now = Carbon::now();
$count = count($ids);
$thiss=$request->validate(
['com_name' => 'required',
'com_status' => 'required'
]);
// $i=0;
for ($i=0; $i <$count ; $i++) {
$companies = companies::find($ids[$i][0]);
companies::where('id',$ids[$i][0])
->update(['company_name' => $name[$i][0],
'status' => $stat[$i][0]
]);
but in my code, Just the 1st row is being updated. what can I do for updating multiple rows with array index number?
You are trying to access the id from a two dimensional array and you are initializing the $ids variable like $ids = [$request->get('com_id')];. Please first check that you have all the ids in the $ids array. if that is alright then any of the following code should work,
// #1
companies::where('id', $ids[$i][0])
->update([
'company_name' => $name[$i][0],
'status' => $stat[$i][0]
]);
// #2
$company = companies::find($ids[$i][0]);
$company->company_name = $name[$i][0];
$company->status = $stat[$i][0];
$company->save();
You should follow the doc to for updating, please look into the https://laravel.com/docs/5.6/eloquent#updates and you may find more details.

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