Not able to pass a variable in laravel - php

In the controller below, if I return $friendPosts (which has the post ids), the ids are shown in the view without problems.
But when I try to return the $sharedPosts (which has the whole row), nothing shows up in the view.
Controller
public function getProfile($email)
{
$myFriends = Auth::user()->friends()->lists('id');
$friendShares = Share::where('user_id',$myFriends)->get();
$friendPosts = $friendShares->lists('post_id');
$sharedPosts = Post::where('id', $friendPosts)->get();
return view('profile.index')
->with ('friendShares', $sharedPosts);
}
View
#foreach ($friendShares as $friendShares)
<p> {{$friendShares}}</p>
#endforeach

$myFriends = Auth::user()->friends()->lists('id');
$friendShares = Share::where('user_id',$myFriends)->get();
$friendPosts = $friendShares->lists('post_id');
$sharedPosts = Post::where('id', $friendPosts)->get();
should be
$myFriends = Auth::user()->friends()->lists('id');
$friendShares = Share::whereIn('user_id',$myFriends)->get();
$friendPosts = $friendShares->lists('post_id');
$sharedPosts = Post::whereIn('id', $friendPosts)->get();
You are working with more ids, not just one, so you have to use whereIn() which looks trough an array of values.
Next time it would be useful if you tell us what you actually wanted/tried to do with your code.

Related

Reusing a Yii2 query

Am trying to reuse a query but it fails.
In my method I have:
public function getPacked($from, $to){
$initquery = RealTimeTblTrucks::find()
->leftJoin('tbl_truck_history','tbl_truck_history.truck_id=tbl_trucks.id')
->where(["between","tbl_truck_history.created_at",$from,$to])
->andWhere(["tbl_truck_history.status"=>20]);
$data = [];
$data[SELF] =$initquery
->andWhere(["tbl_trucks.truck_category"=>28])
->count();
$data[NORMAL] = $initquery->andWhere(["tbl_trucks.truck_category"=>27])
->count();
$data[BULKER] = $initquery->andWhere(['in', 'tbl_trucks.truck_category', [26,34]])
->count();
return $data;
}
Now the first ($data[SELF]) returns the correct information but the next ones NORMAL and BULKER didn't return the correct information.
When I check on the raw query I can see that the last two are affected by the first one such that the new query at $data[NORMAL] contains a check for truck_category = 20 which should only be executed on the first array item (SELF).
How to refactor this to make it work?
Advantage of clone over creation a new object, is that, all properties will be copied into the new object instead of resetting them. This is quite useful when you use query builder.
public function getPacked($from, $to) {
$initquery = RealTimeTblTrucks::find()
->leftJoin('tbl_truck_history','tbl_truck_history.truck_id=tbl_trucks.id')
->where(["between","tbl_truck_history.created_at",$from,$to])
->andWhere(["tbl_truck_history.status"=>20]);
$data = [];
$querySelf = clone $initquery;
$data[SELF] = $querySelf
->andWhere(["tbl_trucks.truck_category"=>28])
->count();
$queryNormal = clone $initquery;
$data[NORMAL] = $queryNormal->andWhere(["tbl_trucks.truck_category"=>27])
->count();
$queryBulker = clone $initquery;
$data[BULKER] = $queryBulker->andWhere(['in', 'tbl_trucks.truck_category', [26,34]])
->count();
return $data;
}
Refer Yii2 clone detail

Merging two query result based on condition

I have two query results.I need to merge the query result based on a condition.
$portfolio = DB::table('architects_portfolio')->get();
$img=DB::table('architects_portfolio_images')
->distinct()->get(['architects_images_id']);
and my condition to merge is
architects_portfolio.id = architects_portfolio_images.architects_images_id
I have my first table 'architects_portfolio' which contain portfolio and second table 'architects_portfolio_images' which contain images of portfolio.I need to get only one image for now.But I get all images of portfolio now by using below code.But I need only one
$architect = User::find($user_id)->architect;
$portfolio = ArchitectsPortfolio::join('architects_portfolio_images as images', 'architects_portfolio.id', '=', 'images.architects_images_id')
->where('architects_portfolio.architects_id', $architect->id)
->select('architects_portfolio.id', 'architects_portfolio.architects_id', 'architects_portfolio.name', 'architects_portfolio.description', 'images.filename','images.architects_images_id')
->distinct()->get(['images.architects_images_id']);
My tables
architects_potfolio
architects_portfolio_images
You should try this:
$rsltArchitectDetails = DB::table('architects_portfolio')
->select('architects_portfolio_images.architects_images_id')
->join('architects_portfolio_images', 'architects_portfolio.id' , '=', 'architects_portfolio_images.architects_images_id')
->distinct()
->get();
$querys = DB::table('architects_portfolio');
$querys->select('architects_portfolio_images.architects_images_id');
$querys->join('architects_portfolio','architects_portfolio.id','=','architects_portfolio_images.architects_images_id')->distinct()->get();
The best way is to use relationships, then you could just load portfolios with related images:
$portfolios = ArhitectPortfolio::with('images')->get();
To make it work, you just need to define the images relationship in the ArhitectPortfolio model:
public function images()
{
return $this->hasMany(ArchitectPortfolioImage::class, 'architects_images_id');
}
Instead of merging we can make use of following code
$data = Architect::where("user_id", $user_id)->first();
$architect = User::find($user_id)->architect;
$portfolio = ArchitectsPortfolio::where('architects_portfolio.architects_id', $architect->id)->paginate(6);
foreach ($portfolio as $r) {
$image = ArchitectsPortfolioImages::where('architects_images_id', $r->id)->first();
if ($image) {
$r->filename = $image->filename;
}
}

Only last row getting displayed in view in Codeigniter

I'm trying to fetch certain values from and then pass it to another model in the same control.
However I'm only able to display the last row in the view.
I have shared my code below and I'm not sure where I'm going wrong.
Controller:
public function test($id){
$mapping_details = $this->queue_model->get_mapping_details($id);
foreach ($mapping_details as $value) {
$data['agent_details'] = array($this->agent_model->get_agent_details($value['user_id']));
}
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Model:
public function get_agent_details($id) {
$query = "select * from user_table where id = ".$id." and company_id = ".$this->session->userdata('user_comp_id');
$res = $this->db->query($query);
return $res->result_array();
}
Welcome to StackOverflow. The problem is the iteration in your controller. You are iterating through the $mapping_details results and per every iteration you are re-assigning the value to $data['agent_details'] , thus losing the last stored information. What you need to do is push to an array, like this:
foreach ($mapping_details as $value) {
$data['agent_details'][] = $this->agent_model->get_agent_details($value['user_id']);
}
However, wouldn't it be best if you created a query that uses JOIN to get the related information from the database? This will be a more efficient way of creating your query, and will stop you from iterating and calling that get_agent_details() over and over again. Think of speed. To do this, you would create a model method that looks something like this (this is just an example):
public function get_mapping_details_with_users($id){
$this->db->select('*');
$this->db->from('mapping_details_table as m');
$this->db->join('user_table as u', 'u.id=m.user_id');
$this->db->where('m.id', $id);
$this->db->where('u.company_id', $this->session->userdata('user_comp_id'));
return $this->db->get()->result();
}
Then your controller will only need to get that model result and send it to the view:
public function test($id){
$data['details_w_users'] = $this->queue_model->get_mapping_details_with_users($id);
$this->load->view('app/admin_console/agent_queue_mapping_view', $data);
}
Hope this helps. :)

laravel pagination on post

hi :) im parsing my database in a table with pagination !!
this is my controller
$theme = Theme::all();
$questions = questionList::paginate(10);
$the = "";
return View::make('home.home')
->with('user',Auth::user())
->with('theme', $theme)
->with('the' , $the)
->with('questions',$questions);
and my view i have {{ $questions->links(); }} under my table and it's working fine !!
the thing is that i have a list of themes to sort data in the table so when i click on divertisement i get divertisement data.
the problem is that when i paginate it return to the get request and give me all the data !! what is the problem thx :)
To add a filter/sort you also need to add that in a where clause in your query and also you need to append the query string in your pagination links. For example:
public function showPosts()
{
$questions = app('questionList');
if($filter = Input::get('filter')) {
$questions = $questions->where('theme', $filter);
}
$questions = $questions->paginate(10);
if(isset($filter)) {
$questions->appends('filter', $filter);
}
return View::make(...)->with(...);
}
In your view you need to create links to this method (Probably using a route name or url) with filter query string. So, for example:
Divertisement
SomethingElse

Laravel 4 whereIn and many to many

I have a tag system, where you can add tags to photos and users.
I have a function where the users are able to add their favorite tags, and select images based on those tags
But my problem i am a really big beginner with php and laravel and i do not know how to pass the values to the whereIn function
Model
public function tag()
{
return $this->belongsToMany('Tag', 'users_tag');
}
Controller
// get the logged in user
$user = $this->user->find(Auth::user()->id);
// get tags relation
$userTags = $user->tag->toArray();
// select photos based on user tags
$photos = Photo::whereHas('tag', function($q) use ($userTags)
{
$q->whereIn('id', $userTags);
})->paginate(13);
$trendyTags = $this->tag->trendyTags();
$this->layout->title = trans('tag.favorite');
$this->layout->content = View::make('main::favoritetags')
->with('user', $user)
->with('photos', $photos)
->with('trendyTags', $trendyTags);
When i pass i get an error
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
than i tried to use array_flatten() to clean my array
// get the logged in user
$user = $this->user->find(Auth::user()->id);
// get tags relation
$userTags =array_flatten($user->tag->toArray());
// select photos based on user tags
$photos = Photo::whereHas('tag', function($q) use ($userTags)
{
$q->whereIn('id', $userTags);
})->paginate(13);
$trendyTags = $this->tag->trendyTags();
$this->layout->title = trans('tag.favorite');
$this->layout->content = View::make('main::favoritetags')
->with('user', $user)
->with('photos', $photos)
->with('trendyTags', $trendyTags);
This way it works but not returning the correct tags.
Could please someone could lend me a hand on this?
Sure thing and I'll make a couple recommendations.
To get the user model, you simply have to use $user = Auth::user().
To use whereIn(), it's expecting a 1 dimensional array of user id's. The toArray() function is going to return an array of associative arrays containing all the users and their properties, so it's not going to work quite right. To get what you need, you should use lists('id').
And one last thing that has really helped me is when you are setting up a relation that's going to return a collection of objects (hasMany, belongsToMany()), make the relation name plurual, so in this case you would modify your tag() function to tags().
So with all that in mind, this should work for you.
// get the logged in user
$user = Auth::user();
// get tags relation
$userTags = $user->tags()->lists('id');
// select photos based on user tags
$photos = Photo::whereHas('tags', function($q) use ($userTags)
{
$q->whereIn('id', $userTags);
})->paginate(13);
$trendyTags = $this->tags->trendyTags();
$this->layout->title = trans('tag.favorite');
$this->layout->content = View::make('main::favoritetags')
->with('user', $user)
->with('photos', $photos)
->with('trendyTags', $trendyTags);
And I'd suggest to modify your relation to... though not hugely important.
public function tags()
{
return $this->belongsToMany('Tag', 'users_tag');
}

Categories