How to call a function on model Collection laravel - php

before i post this I've searched a lot for an answer but no result please forgive me my English not that good
i have Laravel app that contains :
User Model
public function Follow()
{
return $this->belongsToMany(Page::class,"follows","user_id","page_id");
}
Page Model
public function Posts()
{
return $this->hasMany(Post::class);
}
Post Model
public function Page()
{
return $this->belongsTo(Page::class);
}
In the homeController I've index method that should return the posts of the user's followed pages
$user->follow()->get();
this returned only the Pages collection, I couldn't get the Posts or access any
I need to access the posts and their properties, also if possible i need to count the post's likes.
thank you very much.

I have found an answer after trillion attempts
public function index()
{
$user = Auth::User();
$posts = [];
foreach ($user->follow as $key => $page)
{
foreach ($page->posts as $k => $post)
{
array_push($posts, $post);
}
}
//return $posts;
return view('home', compact('posts'));
}
I'm not able to access the likes count yet but i'll try the with('') method
I'll Update for any further Info

You're using the function follow() that returns a page!! Check your return statement
should be:
public function Follow()
{
return $this->belongsToMany(Follow::class,"follows","user_id","page_id");
}

Related

show comment data on post laravel

So yesterday I success to count comment from post, now I want to show comment in admin dashboard, so here is my code in controller
public function getComment()
{
$user = Auth::user();
$posts = $user->posts();
foreach ($posts as $key => $value) {
$posts[$key]->post_comments = PostComment::where('post_id', $value->id)->get();
}
return $posts;
}
and here is my web.php route code to get this comment
Route::get('/comment/post/{id}', 'DashboardController#getComment');
But it retrieve all comment even in different post, I only want to get comment from same post that I want. The weird one is when I click the button it retrieve random id not the id from the post, it look like this
http://127.0.0.1:8000/comment/post/%7Bid%7D
hope you guys can help me thanks
In Laravel we can use relationship to get related data. Here is the example to get user post comments:-
public function getComment()
{
$userId = Auth::user()->id;
$posts = Post::where('user_id', $userId)->with("post_comments")->get();
return $posts;
}
In Post model you need to add this
use App\Comment;
public function post_comments()
{
return $this->hasMany(Comment::class);
}
I hope this will help you to solve your problem with an easy way.
here is the code to retrieve all the comments of certain post by post->id
public function getComment($id) {
$comments = Comment::query()->where('post_id', $id)->get();
return $comments;
}
Make sure the Comment model class have table name
I edited my code and got this solutions, I add id on the get comment parameter
public function getComment($id)
{
$user = Auth::user();
$posts = $user->posts();
foreach ($posts as $key => $value) {
$posts[$key]->post_comments = PostComment::where('post_id', $id)->get();
}
return $posts;
}
public function getComment($id) {
$results = Post::with(['comments'])->where('post_id',$id);
$posts = $results->get();
}
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
public function comments() {
return $this->hasMany(Comment::class, 'post_id');
}
}

Laravel 5.2 trying to get user_id post

I am following a Laravel course on Udemy and while I followed everything the instructor did, for some weird reason I am not getting the expected result.
This is the Relationship One to One lesson and I added a function in User Model to check if it has any posts.
Then added the route to display post if user_id equals.
app\User.php
public function post() {
return $this->hasOne('App\Post');
}
app\Http\routes.php
Route::get('/user/{id}/post', function($id) {
return User::find($id)->post;
});
Below is the screenshot from the database showing that I have a post with user_id = 1 in the posts table. I also have a user with id=1 in the user's table.
MySQL data
Why do I get a blank page when visiting domain/user/1/post?
Sohel, i got a result from your function, but had to use
var_dump(User::with('post')->where('id',1)->first());
Then tried something else:
return User::with('post')->where('id',$id)->first();
And this is the result:
{"id":1,"name":"Nick","email":"nick#kriogen.name","created_at":"2018-03-15 09:49:51","updated_at":"2018-03-15 09:49:51","post":null}
Your one to one relationship should go as:
app\User.php
public function post() {
return $this->hasOne('App\Post');
}
app\Post.php
public function user() {
return $this->hasOne('App\User');
}
you can try doing this function in controller:
public function getPost {
$user= User::find($id);
return $user->post();
}
The issue was not with the functions, the issue was in the database.
Column deleted_at was not NULL and it was marking the post as being soft deleted, therefore not being displayed.
Since the "user_id" field is in the "posts" table, the relation in the App\User model need to be:
public function post() {
return $this->hasMany('App\Post');
}
then, call it without the parenthesis to get the result:
public function getPost {
$user= User::find($id);
return $user->post;
}
When you use the parenthesis, you get the builder and not the result. example:
public function getPost {
$user= User::find($id);
return $user->post()->get();
}
OR
public function getPost {
$user= User::find($id);
return $user->post()->where('name', 'like', '%hello%')->get();
}
I think you need ->hasMany() relation if you want to check if user has any posts because the user can has many posts... and the code would be:
public function posts() {
return $this->hasMany('App\Post');
}
The call:
User::find($id)->posts;

laravel dynamic scope not working

I try to get my categories base on their status and i have scope below in my category model:
public function scopeOfStatus($query, $status)
{
return $query->where('status_id', $status);
}
And my controller is like:
public function finder() {
$findercategories = Category::OfStatus('Active')->get();
return response()->json($findercategories);
}
My route is like:
Route::get('/finder','frontend\SearchController#finder');
But i get blank page as result. Any idea?
update
if i use $findercategories = Category::ofStatus(1)->get(); i get the result that i want but it's static not dynamic :\
Get the Id's from the statuses table with respect to the searched value and use the Id's to get the Category
public function scopeOfStatus($query, $status)
{
$statuses = Status::where('title', $status)->pluck('id'); // Or relevant column name
return $query->whereIn('status_id', $statuses);
}
and in your Controller you could do so
public function finder() {
$findercategories = Category::ofStatus('Active')->get();
return response()->json($findercategories);
}

Query with two laravel models and return result

I have two models, User and Post
User Model:
public function posts()
{
return $this->hasMany('App\Post');
}
Post Model:
public function user()
{
return $this->belongsTo('App\User');
}
In my controller I have a public function which has:
$users = User::orderBy('is_ban', 'desc')->paginate(10);
$posts = Post::orderBy('created_at', 'desc')->paginate(10);
Which is working as expected.
I also have one column in users table `is_ban' It's of boolean type.
I am looking for a query which will return the following:
Only get post which has been made by the user which has is_ban=false
perhaps i haven't understood you, but i hope it will help. You can add it to your Post model
public function getBannedUsersPosts()
{
return self::whereIn('user_id', User::where('is_ban', 0)->pluck('id'))->get();
}

Laravel models to return null relation?

I am writing a website for photo posts and I have these functions relating likes (they determine if the user is liking the specific post or not)
Post Model:
public function likes()
{
return $this->hasMany('Like');
}
public function isLiked()
{
return $this->likes()->where('user_id', Auth::user()->id);
}
Post Controller function for example:
public function postsByType($type)
{
if($this->user){
$posts = Post::with('isLiked')->where('type', '=', $type)->paginate(12);
} else {
$posts = Post::where('type', '=', $type)->paginate(12);
}
return $posts;
}
Is there any way to return null in MODEL function when user is not logged in, without running a query?
I want to avoid writing that if in post controller
I thought about the following solution but it's not working...
public function isFollowing()
{
return $this->setRelation('isFollowing', null);
}
getting this error:
Call to undefined method Illuminate\Database\Query \Builder::addEagerConstraints()
Since you probably always want to fetch the relation (except if there's no user logged in) I suggest you do something like this in your model:
(I also renamed the relationship to liked, you'll see later why)
public function newQuery(){
$query = parent::newQuery();
if(Auth::check()){
$query->with('liked');
}
return $query;
}
Now every time a query is run with the model with('isLiked') will be added if the user is logged in.
One problem remains though. If you access isLiked the query will be run anyways. And even for every post because it's not eager loaded. You can fix that by adding an attribute accessor:
public function getIsLikedAttribute(){
if(Auth::guest) return false;
return ! $this->liked->isEmpty();
}
So in your view you can just do this:
#if($post->isLiked)
Note: It would be nicer to move the things inside newQuery() to a global scope. Make sure to check out how to do that in the documentation if you're interested.
Here's an example with a scope. Create a class, let's call it LikedScope:
class LikedScope implements Illuminate\Database\Eloquent\ScopeInterface {
public function apply(Builder $builder, Model $model){
if(Auth::check()){
$builder->with('liked');
}
}
public function remove(Builder $builder, Model $model){
}
}
And then add it to your model:
public static function boot(){
parent::boot();
static::addGlobalScope(new LikedScope);
}

Categories