I know there is question about this but there is not solution that helps me. So, i have table 'About' in database and model About.php. I want retrieve only one column from db such as title, and use this codes:
$abouts = About::orderBy('created_at', 'desc');
return view('about')->with('abouts', $abouts);
and in view:
{{$abouts->title}}
and how solve this problem. i don't want to use foreach loop. is it possible? how?
try Pluck()
The pluck method retrieves all of the values for a given key:
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
in controller:
$titles = About::orderBy('created_at', 'desc')->pluck('title')->all();
return view('about')->with('titles');
in blade use:
{{$titles[0]}}
ref: https://laravel.com/docs/9.x/collections#method-pluck
Related
I want to insert multiple rows in a table, where the data collection I am inserting has a unique number. For example : I am inserting 2 row for a user_id number 1. My codes from controller is : I want to keep DB::table() instead of laravel eloquent
foreach($post_data['user_id'] as $key => $no){
$set_base = DB::table('package_user')
->Insert([
'base_id' => $post_data['base_id'],
'base_title' => $post_data['base_title'],
'user_id' => $no,
'package_id' => $post_data['package_id'],
'plan_id' => $post_data['plan_id'],
'currency' => $post_data['currency'],
'payable_plan_amount' => $post_data['total_amount'],
'created_at' => Carbon::now()
]);
}
Please refer How to insert multiple rows from a single query using eloquent/fluent there is a solution for both eloquent and querybuilder
$data = [
['user_id'=>'Coder 1', 'subject_id'=> 4096],
['user_id'=>'Coder 2', 'subject_id'=> 2048],
];
Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach
You can also use fill() method if the model instance already created with the pre-defined populated datas.
<code>
$modelObj = new Model();
$modelCollection = collect($request->input())->all();
$modelObj->fill($modelCollection);
$modelObj->save();
</code>
I have the following array:
$elements = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
I need to filter by approximation, but just using the collection data, something like:
$elements->where('name', 'LIKE', 'De%')->values()->all();
Actually i can filter the data, but with a normal filter (where), this does not work for me because it find the exact coincidences. So, if i use a normal filter i have to say the exactly value to match:
$elements->where('name', 'Desk');
How i can made a query to the array data using something like a "Where LIKE" clausule?
You can use filter function in collection and in closure use preg_match php function to check if it exist in name parameter like this:
$name='de';
$elements->filter(function ($item) use($name){
return preg_match("/$name/",$item['name']);
});
I'm learning Laravel and have created a public endpoint where I want to output only certain information of some comments if a user is not authenticated from a GET request.
I have managed to filter out the comments based on whether or not they are approved. I now want to filter out the data that is returned. I have attached a screenshot of what is currently returned.
Ideally, I only want to return the id, name and the body in the json. How can I go about this? I tried the pluck() method which did not give the desired results. Any pointers would be greatly appreciated
public function index(Request $request)
{
if (Auth::guard('api')->check()) {
return Comment::all();
} else {
$comments = Comment::where('approved', 1)->get();
return $comments->pluck('id','name','body');
}
}
To select the particular columns, you can pass columns name to get as
$comments = Comment::where('approved', 1) -> get(['id','name','body']);
You can use a transformer to map the incoming data to a sensible output based on the auth state. The following example comes from the Fractal lib:
<?php
use Acme\Model\Book;
use League\Fractal;
$books = Book::all();
$resource = new Fractal\Resource\Collection($books, function(Book $book) {
return [
'id' => (int) $book->id,
'title' => $book->title,
'year' => $book->yr,
'author' => [
'name' => $book->author_name,
'email' => $book->author_email,
],
'links' => [
[
'rel' => 'self',
'uri' => '/books/'.$book->id,
]
]
];
});
Ideally, you would create 2 classes that extend from Transformer and pass the correct one to the output.
If you want to pass the result as json respose
$comments = Comment::where('approved', 1)->pluck('id','name','body')->toArray();
return Response::json($comments);
If you want to pass the result as to blade
$comments = Comment::where('approved', 1)->pluck('id','name','body')->toArray();
return view('your_blade_name')->with('comments',$comments);
I've got something like this
$query = Customer::find()
->select(['customer.name', 'surname', 'cityName' => 'cities.name', 'streetName' => 'streets.name'])
->joinWith(['city', 'street'])
->where(['group_id' => $id]);
When i do
return $query->all();
it returns only columns from customer table, but when i do something like this
$raw = $query->createCommand()->getRawSql();
return \Yii::$app->user_db->createCommand($raw)->queryAll();
it returns me all 4 columns. Why orm fails?
I'm using custom db connection (user), dynamicly connected after authorization. Anyway ActiveRecord->getDb() has been customized too and it works well till now.
it returns only columns from customer table, but when i do something like this.
Yes, that's right. Because Yii2 AR(Active Record) is ORM pattern. And it's try to return all result off query like object.
So, I will not tell the theory, I'd better suggest a solution variant:
$query = Customer::find()
->joinWith(['city', 'street'])
->where(['group_id' => $id])
->asArray()
->all();
return $query;
It's from Yii2 docs(performance tuning).
The result will be like:
[
all data selected from "customer",
['city' => all data selected from city joinWith],
['street' => all data selected from street joinWith]
]
I think, this is exactly what you need.
But, if you need objects. You can try marge objects to only one array.
$customer = Customer::find()
->joinWith(['city', 'street'])
->where(['group_id' => $id])
->all();
return [
'customer' => $customer,
'city' => $customer->city,
'street' => $customer->street,
];
you are using
->select(['customer.name', 'surname', 'cityName' => 'cities.name', 'streetName' => 'streets.name'])
so you will get selected columns only.
use,
$query = Customer::find()
->joinWith(['city', 'street'])
->where(['group_id' => $id])
->all();
this will give you all the columns
i am getting data from database which in need to group so i am converting database result set in to array and then passing it to laravel collect helper but i gives me error
Call to undefined function collect()
Code
$user_profile=collect(UserProfileItem::where('type', "age_group")->get()->toArray())->groupBy("age_group");
please help me about what i am doing wrong i want to use laravel collections method groupby to group my database result array by "age_group"
like below data group by account_id
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
You dont need to add collect function as you are already getting a collection. So you need to do it as :
$user_profile = UserProfileItem::where('type', "age_group")->get()->groupBy("age_group");
you need to first get the groups and loop through them and add data in those to the collection
$groups = UserProfileItem::groupBy("age_group")->get();
$collection = collect();
foreach($groups as $group){
$data = UserProfileItem::where('type', $group->type)->get();
$collection->put($group->type , $data);
}
return $collection;
i think for previous version of laravel creating your own group is the only solution
public function getGroupedUser($group="age_group"){
$users = $this->users->keyBy('id')->toArray();
$user_profile=UserProfileItem::where('type', "age_group")->get()->groupBy("age_group");
foreach ($user_profile as $row){
$urow[$row['data']][]=$row;
}
echo "<pre>";
print_r($user_profile);die;
}