MongoDB GridFS Get ID of a file - php

I am using MongoDB GridFS to store user avatars. I am using Laravel 4.2.
I am writing a function to clean up the DB of any unused avatars; an avatar is unused if it's id is not associated with any user (User model). Given the ID of an avatar I can remove the file from the DB. However I am having trouble extracting ID's of an avatar so I can compare it with those in the User model.
The data looks like this:
$avatars = DB::collection('user_avatars.files')->get();
return Response::json( $avatars[0] );
//result:
{"_id":{"$id":"542797096a8d09ac318b456b"},"extension":"jpg","usage":0,"popularity":[],"filename":"image.jpg","uploadDate":{"sec":1411880713,"usec":671000},"length":248388,"chunkSize":262144,"md5":"2c724361015c7e438d30359dd9c724a0"}
Now if I write:
return Response::json( $avatars[0]['_id'] );
//result is:
{"$id":"542797096a8d09ac318b456b"}
How would I grab 542797096a8d09ac318b456b? Anything I have tried so far does not give the ID but throws an error:
$avatars[0]['_id']->$id;
$avatars[0]['_id']['$id'];
$avatars[0]['_id']->$$id;
$avatars[0]['_id']->{$id};

I tried this and it works great:
avatars[0]['_id']->{'$id'};
Here is the complete function:
public function doPurgeDB()
{
$removed = array();
$avatars = DB::collection('user_avatars.files')->get();
foreach( $avatars as $avatar )
{
$avatar_id = $avatar['_id']->{'$id'}; //<<<<=========
$user = User::where('avatar_id', '=', $avatar_id);
if( !$user->count() )
{
$removed[] = $avatar;
$this->removeAvatar( $avatar_id );
}
}
return Response::json( $removed );
}
public function removeAvatar( $id )
{
$grid = DB::getGridFS('user_avatars');
return $grid->delete( new MongoId( $id ) );
}

Cast it to string: (string)$avatars[0]['_id'];

Related

How to check duplicate title and not save to database in laravel

i have a problem that when i get data from other api and want if same title wont save to api. Each time getting data from the api is 20 and want to save it to the database without duplicate. Please help me. Thank you very much!!!
public function getTitle($title){
$title = $this->posts->where('title', $title)->get();
return $title;
}
public function getApi(Request $request){
$url = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=87384f1c2fe94e11a76b2f6ff11b337f";
$data = Http::get($url);
$item = json_decode($data->body());
$i = collect($item->articles);
$limit = $i->take(20); // take limited 5 items
$decode = json_decode($limit);
foreach($decode as $post){
$ite = (array)$post;
$hi = $this->getTitle($ite['title']);
dd($ite['title'], $hi);
if($ite['title']==$hi){
dd('not save');
}
else{
dd('save');
}
//dd($hi, $ite['title']);
// create post
$dataPost = [
'title'=>$ite['title'],
'description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']
];
//dd($dataPost);
//$this->posts->create($dataPost);
}
return redirect()->route('posts.index');
}
You can use first or create for saving data in database if title name is new. using firstOrNew you dont have to use any other conditions
for example:-
$this->posts->firstOrCreate(
['title' => $ite['title']],
['description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']]);
firstOrNew:-
It tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new Model after applying any attributes passed in the second parameter
From docs
If any records exist that match your query's constraints, you may use
the exists and doesntExist methods
if($this->posts->where('title', $title)->doesntExist())
{
// save
} else {
// not save
}

Laravel 8 not finding "tag" from package "\Conner\Tagging\Taggable;"

The code works perfectly when I want to create a new tag from scratch, but when $skillsQuery->count() > 0 and enters in the if statement. It prints...
Method Illuminate\Database\Eloquent\Collection::tag does not exist.
How can I update tags using this package?
Controller
<?php
public function storeSkills(Request $request)
{
$id = auth()->user()->id;
$skillsQuery = Skill::where('created_by', $id)->get();
// If skill exists
if ($skillsQuery->count() > 0) {
$input = $request->all();
$tags = explode(", ", $input['name']);
// $skill = Skill::create($input);
$skillsQuery->tag($tags);
$skillsQuery->created_by = $id;
if ($skillsQuery->save()) {
return redirect()->route('profile')->with('success', 'Skills updated successfully');
} else {
return redirect()->route('profile')->with('error', 'Error updated your Skills!');
}
} else {
$input = $request->all();
$tags = explode(", ", $input['name']);
$skill = Skill::create($input);
$skill->tag($tags);
$skill->created_by = $id;
if ($skill->save())
return redirect()->route('profile')->with('success', 'Skills stored successfully');
else {
return redirect()->route('profile')->with('error', 'Error storing your Skills!');
}
}
}
The result of calling ->get() on a Illuminate\Database\Query is that you will receive an instance of a Illuminate\Database\Collection, which does not contain a ->tag() method. Even if it was a query (by removing ->get()) this still would not work, as you can't call a relationship method off of a collection.
If instead you loop over the skillsQuery then you will receive an instance of a Model object which then allows you to access functions and/or relationships off of it:
$skillsQuery->each(function ($skill) use ($tags) {
$skill->tag($tags); // or perhaps ->retag($tags); here
});

Getting distinct rows from paginated result set in Laravel

I have created the following for a product catelog/lister:
public function index($type_id = null) {
$filters = $sort = array();
if (isset($type_id)) {
$filters['type'] = $type_id;
} else {
$filters['type'] = Input::get('type');
}
$filters['search'] = Input::get('search');
$filters['brand'] = Input::get('brand');
$sort['sort'] = Input::get('sort');
$sort['sortdir'] = Input::get('dir');
$productsPaginated = $this->fetchProducts($filters, $sort);
return View::make('products.products', array(
'productsList' => $productsPaginated
)
);
}
public function fetchProducts($filters, $sorts, $perpage = 2) {
print_r($filters);
$Product = Product::query();
if (!empty($filters['search']))
$Product->where('name', 'LIKE', '%' . $filters['search'] . '%');
if (isset($filters['type']))
$Product->where('type_id', $filters['type']);
if (isset($filters['brand']))
$Product->where('brand_id', $filters['brand']);
if (isset($sorts['sort']))
$Product->orderBy($sorts['sort'], $sorts['sortdir']);
$Product = $Product->paginate($perpage);
return $Product;
}
Which works well so far.
I am now trying to create some filters so a user can further filter the results.
How can I access and determine distinct rows based on a column in:
$productsPaginated = $this->fetchProducts($filters, $sort);
?
The groupBy method not only exists on the query builder but also on the collection class. (which will be returned when calling paginate)
Take a look at the source on github
So add an argument to your function and use groupBy
public function fetchProducts($filters, $sorts, $perpage = 2, $groupBy = null) {
// code omitted for brevity
$Product = $Product->paginate($perpage);
if($groupBy){
$Product = $Product->groupBy($groupBy);
}
return $Product;
}
Update
Then there's the lists function that works on collections as well as on query builders...
$Product->lists('column-name');
Update 2
I was curious so I did some testing and a found something very weird and I have no idea if its a bug or a feature I don't understand
When calling groupBy the collection returned has actually only one item (index "") and this item contains an array of the "original" items. So to make lists work. I found this workaround
$Product = $Product->groupBy($groupBy);
$Product = new Collection($Product[""]); // \Illuminate\Support\Collection
$Product = $Product->lists('column-name');

Using docrtrine in Symfony2

I'm working on a php project but I have a problem with the database , I use this code to get data from the database :
public function getSeenAction(Request $request , $notificationId)
{
$sessionId = $request->headers->get('SessionID');
if( $sessionId == null )
{
//return new Response("Unauthorized",401);
}
$notificationRepo = $this->getDoctrine()->getRepository('MegasoftEntangleBundle:Notification');
$notification = $notificationRepo->findOneById($notificationId);
if($notification == null)
{
return new Response("Notification not found" ,404);
}
$seen = $notification->getSeen();
$response = new JsonResponse();
$response->setdata(array('seen'=>$seen));
$response->setStatusCode(200);
return $response;
}
I tried the same code with other tables and it worked , but whenever I retrive data from the Notification table it always give null , although the table contains the data.
$notificationRepo = $this->getDoctrine()->getRepository('MegasoftEntangleBundle:Notification');
$notification = $notificationRepo->findAll();
var_dump(notification);
Is this code returns you something ? Probably the code of your NotificationRepository.php is not good, can you put it on ?
Try using find instead of findOneById if you just want to find record by Id.
On the other hand if you want to use findOneBy the passed argument for criteria should be an array.
$result = $notificationRepo->find($notificationId);
Or
$result = $notificationRepo->findOneBy(array('id' => $notificationId));
Or
make sure you have a proper code for findOneById in your NotificationRepository.php file
Then you can check
if (!empty($result)) { ... }

Getting the rowid after adding an item with CI cart?

On the codeigniter website it says the the insert() method will return a $rowid of the latest inserted product. However How exactly do I grab it?
$data = array();
$insert = $this->cart->insert($data);
I tried $insert['rowid'] and $insert->rowid but neither seem to work.
Thank you!
introducing: insert_id()
like this
$id = $this->db->insert_id();
return $id;
in your model, lets call it friend_model
function insertRow()
{
// Prepare data, normally you would pass this in
$data = array(
'first' => 'john',
'last' => 'smith'
);
// insert data
$this->db->insert( 'friends', $data );
// confirm insert
if ( $this->db->affected_rows() == '1' )
// return new ID
{ $id = $this->db->insert_id();
return $id; }
// else did not insert, return false
else {return FALSE;}
}
in your controller, check if you got an id back from model
if(! $id = $this->friend_model->insertRow() )
// it no work
{ // some error method
}
else
{ // success !
}

Categories