'Retrieving object data based on db table in Laravel

This been a moment I’m struggling trying to retrieve object data using laravel by only retrieve list based on a DB table colums (using Models).

My DB table are working is structured like that:

id | user_id | news_id | informations

I’m trying to retrieve only array from object where the object properties “ID” ($object->data->id) are the same as news_id from my DB table taking in consideration that current authentified user ID is associated with user_id.

I’ve been stuck with object are actually destroyed by my code and no longer able to fetch it in blade to show data using foreach

//Controller to maps news
…
…
Use App\Models\News;
…
…

class NewsController extends Controller
{


public function getNews() 
{
$id = 13; //Example: user_id 

//Fetching all news where user_id is 13;
$news_user = News::where('user_id', $id)->get();
        

$news_collect = collect($news_obj->data);
        
 
foreach ($news_user as $new_user) {
          
$news_filtered = $news_collect->whereIn('id', $new_user->news_id);

      $news = $news_filtered->all();
      
            }

       return $news;
    }

…
…
}

//Controller to show in blade
…
…

use App\Http\Controllers\NewsController;
….
…

class NewsViewsController extends Controller
{

public function __construct()
{
…
…
$this->new_list = new NewsController;
…
…

public function index() 
{
$news = this->new_list->getNews();

return view('admin.news.index')
             ->with(['news' => $news]);
}
…
…

That how i retrieve the data from object…

{

   "data": [

      {

         "id": 39,
         "title": "test",
         "content": "this is Test"
      },
      {

         "id": 54,
         "title": "test",
         "content": "this is Test"
      },
     {

         "id": 79,
         "title": "test",
         "content": "this is Test"
      }

… …

Using Laravel 8, is there a better way to show array from object if current user_id is 13 which will retrieve the object array with id 39 ans 79 so i can loop inside a html table;

Example of my current db table data;

id | user_id | news_id | informations
1 | 13 | 39 | blabla
2 | 17 | 54 | bla
3 | 13 | 79 | blabla

That been a while im struggling without success

Thanks



Solution 1:[1]

    class NewsController extends Controller

{

public function getNews()
{
    $id = 13; //Example: user_id

    $user = User::with(['news'])->where('id', $id)->first();


    return view('admin.news.index',['news'=>$user->news]);
}

}

add to User model inside

public function news(){
return $this->hasMany(News::class, 'user_id'); }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vusal Orujov