Elequent Relationships Error - laravel-5

I have created a posts table & comments table for posts comments.
I want to get my posts with their comments ...
In my Post Model :
public function comments()
{
return $this->hasMany('App\Comment');
}
In my Comment Model :
public function post()
{
return $this->belongsTo('App\Post');
}
And this is my Controller :
public function show($ID)
{
try {
$post = Post::findOrFail($ID);
$comments = Post::find($ID)->comments;
$randomPosts = Post::all()->random(3);
return view('show', compact('post','comments','randomPosts'));
} catch (ModelNotFoundException $e) {
$posts = Post::orderBy('ID', 'DESC')->paginate(5);
return view('welcome', compact('posts'));
}
}
But I get this error :
Undefined property: Illuminate\Database\Eloquent\Collection::$ID
What is my problem ?

You need to assign the $ID variable to your id that you want to retrieve the post
For example let's say that you want the post with id 1 and its comment.
First you can retrieve the comments for first article like this:
$comments = App\Post::find(1)->comments;
foreach ($comments as $comment) {
echo $comment
}
Of course you can retrieve the post represents one comment.
For example the post that has the first comment:
$comment = App\Comment::find(1);
echo $comment->post->title;

Related

Where can I put paginate()?

I am trying put paginate(10) to add a pagination later, but when I added it it gives me this error:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$product
Here is my controller where I want add the pagination(10):
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('your')->with('product', $user->product);
}
I did try this:
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id)->paginate(10);
return view('your')->with('product', $user->product);
}
How can I avoid the undefined property error?
Actually find function is used for getting only 1 result and you are applying pagination on that which is resulting into an error.
You might be wanting the products data to be paginated, For that do like this
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id)->product()->paginate(10);
return view('your')->with('product', $user);
}

Count the number of posts for logged in user in laravel

I want a number of posts that logged in user to have
I tried but I don't know how it will work
public function limitation()
{
$limit = 3;
$ads = User::WithCount('ads')->get();
}
Any help will appericiate
it works!!
$limit = 3;
$userId = auth()->user()->id;
$userPostCountId = User::where('id', $userId);
$posts=User::withCount('ads')->first(); //Suggest:- it will return post counts
along with user details
if ($userId>0) {
# code...
if(isset($posts->ads))
{
$count = sizeof($posts->ads);
if ($count>=$limit) {
return redirect()->route('ad.index');
}
}
If you have set up your user-posts relationship correctly like so:
class User {
public function posts(){
return $this->hasMany('App\Posts')
}
}
then you can get the users posts like so
$user = Auth::user();
$numPosts = $user->posts()->count();
Read more about relationships and how to query them here: https://laravel.com/docs/6.x/eloquent-relationships#one-to-many
Make sure you defined proper model naming
Also, you have to define a relationship between users and posts
User Model
public function posts()
{
return $this->hasMany(Posts::class);
}
In your controller
public function userPosts()
{
$userId = auth()->user()->id;
$userPostCount = User::where('id', $userId)->withCount('posts')->first(); //Suggest:- it will return post counts along with user details
//or auth()->user()->posts()->count() //it will return only post count
// or if you want to count with post also
// $userPosts = User::where('id', $userId)->with('posts')->withCount('posts')->first(); // it will return user posts and post counts along with user data
return $userPostCount; // or $userPosts
}
For more information please read: Laravel eloquent relationship
use skip and take functions
$limit = 3;
$ads = User::WithCount('ads')->skip(0)->take($limit)->get();

why i can't call name from table food?

public function orderlist(Request $request){
$id = $request->id;
$data['order'] = Order::where('shop_id',$id)->orderBy('id')->get();
foreach($data['order'] as $orders){
$orders->shop = Shop::where('id',$orders->shop_id)->first();
$orders->food = Food::where('id',$orders->food_id)->get();
}
return $orders->food->name;
return view ('administrator.users.list_order.index',$data);
}
If you set up proper Eloquent relationships, this code could be rewritten like so:
public function orderlist(Request $request, Shop $shop){
$orders = $shop->orders()->with(['food'])->get();
return view ('administrator.users.list_order.index',compact('orders'));
}
Check out the docs here: https://laravel.com/docs/5.7/eloquent-relationships

how to update file in laravel

I update two data one text data and two file data but it's not working this. How to update file?
My code is:
public function update(Request $request){
$news=new News();
$news->newstitle=$request->newstitle;
$url1=$this->imageExistStatus1($request);
$news->save();
return redirect()->back()->with('sms','insert successful');
}
public function imageExistStatus1($request){
$newsByid1=News::where('id',$request->newsid)->first();
$fimage1=$request->file('imageone');
if ($fimage1) {
unlink($newsByid1->imageone)
$thisName1= $fimage1->getClientOriginalName();
$uplodePath1='public/up/';
$fimage1->move($uplodePath1,$thisName1);
$url1=$uplodePath1.$thisName1;
}else{
$url1=$newsByid1->imageone;
}
return $url1;
}
First, change your code to the following
public function update(Request $request, $id)
{
$news = News::findOrFail($id);
$news->newstitle = $request->newstitle;
$fimage1 = $request->file('imageone');
if ($fimage1) {
unlink($news->imageone);
$news->imageone = $this->imageExistStatus1($request, $id);
}
$news->save();
return redirect()->back()->with('sms', 'insert successful');
}
public function imageExistStatus1($request)
{
$fimage1 = $request->file('imageone');
$thisName1 = $fimage1->getClientOriginalName();
$uplodePath1 = 'public/up/';
$fimage1->move($uplodePath1, $thisName1);
$url1 = $uplodePath1 . $thisName1;
return $url1;
}
I hope your problem is resolved
tip:
Thanks to "Oluwatobi Samuel Omisakin".
please use the route:
Route::patch('/news/{id}/update', 'NewsController#update')

Create Join Between Tables Laravel

I Have 2 tables : Posts - Comment
I Want to Make Relation Between These 2 Tables and Need to Update The Comment That Has "1" Post_ID :
Route:
Route::get('join', 'JoinController#Join');
Controller :
public function Join()
{
$Comment = Posts::find(1)->Comment;
$Comment->Title = "JOIN";
$Comment->save();
}
Posts Model :
public function Comment()
{
return $this->hasOne('App\Comment');
}
Comment Model :
public function Posts()
{
return $this->belongsTo('App\Posts');
}
but i recieve this error :
Trying to get property of non-object
Do this instead:
$comment = new Comment;
$comment->Title = 'JOIN';
#comment->post_id = 1;
$comment->save();
Or you can use create() method:
$Comment = Posts::find(1)->Comment()->create(['Title' => 'JOIN']);
If you'll use create() method, make sure Title is in the $fillable array.
$Comment = Posts::find(1)->Comment()->first();
$Comment->Title = "JOIN";
$Comment->save();

Resources