How to turn a collection into an array in laravel - laravel

I'm not sure if my title is correctly done, but what I'm trying to do is get all the notifications that a user didn't read.
I have 2 tables the first table is notifications and the second one is read_notifications.
Here is my code in User.php model
$read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->get();
$unread = Notification::whereNotIn('id', $read)->get();
Here I'm getting all the notification IDs in the read_notifications table and I want to put them in the $unread statement.
The error I get when I do this is
Object of class stdClass could not be converted to string

Notification::whereNotIn('id', $read)->get();
$read is an object and id should be a string (or integer). You should use an id field from your $read object like $read[$i]->id.
Also whereNotIn needs an array as a second argument, so you need to collect your IDs from $read to an array like [1,2,3].

Thanks for helping. I found what I needed, I needed to use the pluck method.
Here is the updated code
$read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->pluck('notification_id');
$unread = Notification::whereNotIn('id', $read)->get();

for whereNotIn to work $read should be an array.
$read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->get();
foreach($read as $re)
$ot[] = $re->notification_id;
$unread = Notification::whereNotIn('id', $ot)->get();
OR you can use pluck
$read = DB::table('read_notifications')->where('user_id', $this->id)->pluck('notification_id');
$unread = Notification::whereNotIn('id', $read)->get();

Related

how to get 2 table data into single variable array in laravel?

i have 2 tables User and subadmin consider user have 3 columns and subadmin has 2 column i want to get 3+2 (5 column) data into a single veriable array
the technique i want to use is that in user table i have id which is same in subadmin table with sub_admin_id(column) how i can use eloquent model to first link id with sub_admin_id and then into a single query get 5 column in single veriable array
here i am using to get data
$subadmindata = User::find($id)->get(); // [column1 ,column2 ,column3 ]
$subadmindata1 = SubAdmin::find($id)->get(); // [column1 ,column2 ]
output should be
$data = // [column1 ,column2 ,column3 , column4 ,column5 ]
note i dont want to use array merge or combine method i want to use eloquent model for my learning
you could use concat like this
$subadmindata = User::find($id)->get();
$subadmindata1 = SubAdmin::find($id)->get(); // it will return array of collections
$data = $subadmindata->concat($subadmindata1);
Notice when you use get after find it stop it's jobs so there is no need to find here
get() method will give you a collection not array, so you can merge two collection as follows.
$subadmindata = User::find($id)->get();
$subadmindata1 = SubAdmin::find($id)->get();
$data = $subadmindata->merge($subadmindata1);
You can't use find with get(Assuming that you need a one result not all of the users). Try this. But looks like you need build the relationships correctly first. Anyway, quick answer is below.
$userCols = User::select('column1','col2','col3')->find($id);
$subAdminCols = SubAdmin::select('col4','col5')->find($id);
$cols = array_merge($userCols->toArray(), $subAdminCols->toArray());
try this
in user model
public function subadmin(){
return $this->hasOne(SubAdmin::class,'sub_admin_id');
}
in controller
$sub_admins = User::find($id);
dd($sub_admins->subadmin->sub_admin_id)
you can use php ... operator to to push data
example like this
$subadmindata = User::find($id)->get()->toArray(); // [column1 ,column2 ,column3 ]
$subadmindata1 = SubAdmin::find($id)->get()->toArray(); // [column1 ,column2 ]
array_push($subadmindata, ...$subadmindata1);
return $subadmindata
ref link https://wiki.php.net/rfc/spread_operator_for_array

How to get string value using eloquent query

I am trying to execute a query using eloquent, however it returns me an array. What I want is to only get the string value of my query.
This is what I get
[{"name":"hey"}] [{"name":"sdasdasd"}]
Here's my eloquent query:
$categoryName = Category::select('name')->where('id', request('category'))->get();
$subCategory = Subcategory::select('name')->where('id', request('subCat'))->get();
as per the Laravel Docs
Retrieving A Single Row / Column From A Table
If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single stdClass object:
$user = DB::table('users')->where('name', 'John')->first();
echo $user->name;
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');
so in your example maybe you need to do something like the following :
$subCategory = Subcategory::select('name')->where('id', request('subCat'))-> first();
echo $subCategory->name;
There are so many ways to achive your goal.
Solutions
Use pluck().
$categoryName = Category::select('name')
->where('id', request('category'))
->pluck()
->first();
Use model properties.
$categoryName = Category::find(request('category'))
->name;
If you take only name then follow the below code.
$categoryName = Category::where('id', request('category'))->first()->name;
$subCategory = Subcategory::where('id', request('subCat'))->first()->name;
echo $categoryName;
echo $subCategory;
If you take all columns in a row follow the below code:
$categoryName = Category::where('id', request('category'))->first();
$subCategory = Subcategory::where('id', request('subCat'))->first();
echo $subCategory->name;
echo $categoryName->name;
I hope this i may help you.Try this.
You can get the answer using
$name = DB::table('Category')->where('id','=',request('category'))->pluck('name')->first();
echo $name;
$name = Category::select('name')->where('id', request('category'))->take(1)->orderBy('id','asc')->first()->name;
echo $name;
OR
echo Category::select('name')->where('id', request('category'))->take(1)->orderBy('id','asc')->first()->name;

Two column values in same table Laravel 5.4 merge into Array

I want to merge example_1 and example_2 values into array.
example_1 and example_2 are of type int.
User::select('example_1','example_2')->where('id',Auth::user()->id)->get();
// The result: [{"example_1":"1","example_2":"2"}]
example_1 and example_2 if has value 1 and 2 respectively.
I want to have an array : [1,2]
You can do one of this
$result = array_only(auth()->user()->toArray(), ['example_1','example_2']);
// Or
$result = User::where('id', auth()->id())->first(['example_1','example_2'])->toArray();
// Finally
$data = array_values($result);
All Eloquent queries return Collection objects. Those can be modified easier (through collections methods).
You can use first() to get the first object out of this collection.
Now you can access the variables of the Eloquent User model by calling them like you'd call public class properties.
Your final code would look like:
$user = User::select('example_1','example_2')
->where('id',Auth::user()->id)->get()->first();
$array = [ $user->example_1, $user->example_2 ];
// The result: [1,2]

Only one row is returned using where in with comma seperated value in Laravel raw query

I am developing a php project using Laravel 5.2. In my app I am retrieving records from database using manual query. But I am having a problem with retrieving records by using where in statement with csv.
Example how I am retrieving
$csv = "1,3,5";
$sql = "SELECT * FROM `items` WHERE `id` IN (?)";
$rows = DB::select($sql,[$csv]);
As you can see above I am retrieving three rows. But it returns only one row where id is 1. Why is that?
You can't do it like that. Each entry in your csv is a separate parameter, so for your code you would actually need IN (?, ?, ?), and then pass in the array of values. It would be pretty easy to write the code to do this (explode the string to an array, create another array of question marks the same size, put it all together).
However, you are using Laravel, so it would be easier to use the functionality Laravel provides to you.
Using the query builder, you can do this like:
$csv = "1,3,5";
// turn your csv into an array
$ids = explode(",", $csv);
// get the data
$rows = DB::table('items')->whereIn('id', $ids)->get();
// $rows will be an array of stdClass objects containing your results
dd($rows);
Or, if you have an Item model setup for your items table, you could do:
$items = Item::whereIn('id', $params)->get();
// $items will be a Collection of Item objects
dd($items);
Or, assuming id is the primary key of your items table:
// find can take a single id, or an array of ids
$items = Item::find($params);
// $items will be a Collection of Item objects
dd($items);
Edit
If you really want to do it the manual way, you could use a loop, but you don't need to. PHP provides some pretty convenient array methods.
$csv = "1,3,5";
// turn your csv into an array
$ids = explode(",", $csv);
// generate the number of parameters you need
$markers = array_fill(0, count($ids), '?');
// write your sql
$sql = "SELECT * FROM `items` WHERE `id` IN (".implode(',', $markers).")";
// get your data
$rows = DB::select($sql, $ids);

Get values from a doctrine collection with composite key

4 for on on my applications with Doctrine.
In there I'm using the following doctrine command to retrieve person object collection
//query
$people = $q->execute();
This return 20 objects. The primary key of the person object is a composite key with three attributes. Those are
id
department_id
name
I need to get person objects by searching in it as follows.
$id = 10;
$department_id = 1;
$name = "abc";
$people->get($id, $department_id, $name);
But this doesn't work and not give correct results. I tried with this and it gives null results which seems my collections primary key is not set.
$people->getKeyColumn();
I don't want to go through a foreach loop in collection and process it because when I deal with about 500 people, it slow down my application.
Can some one help me with this issue to get values from a doctrine collection.
Can you use something like this?
$people = Doctrine::getTable('Persons')
->createQuery()
->where('id = ? AND department_id = ? AND name = ?', array($id, $department_id, $name))
->execute();
It will get you a DoctrineCollection already filtered by the parameters provided.
'Persons' here is a Doctrine model name, not a table name from mySQL.
You can also use Doctrine's magic finders findBy*():
$people = Doctrine_Core::getTable('Persons')
->findByIdAndDepartmentIdAndName($id, $department_id, $name);

Resources