Fetch data from same field name in two different tables and detect which filed name we mean

Viewed 117

I have assigned search method for my application and i have made relationship between two tables "users " table and "posts" table both of them have same field name "created_at" and when i want to fetch data that when this post has been created it will bring the date in users table created_at field not in posts table created_at field. All i want is how to tell the system make difference between which table field name i mean .

This date comes from created_at field in users table This date comes from created_at field in users table

I wand to come date in this created_at field in posts table I wand to come date in this created_at field in posts table

ListingController.php

public function search(Request $request){

     $posts = Post::with(['comments','category','creator'])
                 ->join('users', 'posts.created_by', '=', 'users.id')
                 ->where('slug', 'LIKE', '%'.$request->search. '%')
                 ->orWhere('users.name', 'LIKE', '%'.$request->search. '%')
                 ->where('status',1)->orderBy('posts.id','DESC')->paginate(5); 

         return view('front.listing',compact('posts'));

 }

listing.blade.php


<div class="article_date">
               by: <a href="{{ url('/author') }}/{{ $post->creator->id }}">{{ $post->creator->name }} </a> , {{$post->created_at->diffForHumans()}}
            </div>


1 Answers

You are calling your relationship improperly. You should not use a join there. Use constrained eager loading instead

There will be no conflict in the created_at date since there will be no join. While still keeping your search query inside the closure of the relationship.

        $posts = Post::with(['comments', 'category'])
            ->with(['creator' => function ($query) use ($request) {
                $query->where('name', 'LIKE', '%' . $request->search . '%');
            }])
            ->where('slug', 'LIKE', '%' . $request->search . '%')
            ->where('status', 1)
            ->orderBy('id', 'DESC')
            ->paginate(5);
Related