Having Laravel 8 routing and controller issue

135 Views Asked by At

Having Laravel 8 routing and controller issue

I'm bit new to laravel8 and got hang of it and I'm building a news portal as a project and learn at same time.

On the main index page I like to display some data such posts and categories and so on, where the data comes different tables in the db and from same controllers but different methods to the same route. So I’m bit stuck here, the problem I’m having is that it’s not working This is my code

Here are the routs

// main Index Page
Route::get('/','App\Http\Controllers\Home_pageController@categories);
// Index Latest Posts
Route::get('/','App\Http\Controllers\Home_pageController@homePageLatestPosts');

Methods in the Controllers This is the method for displaying the latest posts in a sidebar

// Display latest limit by 10 the posts on home page
    public function homePageLatestPosts(){
        // $all_posts = Blogs::all();
        $latest_posts = DB::table('blogs')->join('users', 'users.id', '=', 'blogs.added_by')->select('users.*','blogs.*')->orderBy('blogs.created_at', 'desc')->paginate(5);
        // dd($latest_posts);
        return view('welcome' , ['latest_posts'=>$latest_posts]);
    }


// Show Categories
    public function categories(){
        $categories = DB::table('categories')->orderBy('category_name', 'desc')->get();
        // dd($categories);
        return view('welcome',['cats'=>$categories]);
    }

I would like to know what the problem is and if there is a solution and if its the right approach that I', taking

I have googled around for a solution but not being able to solve it

thanks in advance

1

There are 1 best solutions below

0
Tahir D On

thanks for the responses.

i got a way around by fetching the data from DB in one method and passed them to the view for display.

use App\Models\Blog;
use App\Models\User;
use App\Models\Categories;
    public function welcome(){
        // Latest Posts
        $latest_posts = DB::table('blogs')->join('users', 'users.id', '=', 'blogs.added_by')->select('users.*','blogs.*')->orderBy('blogs.created_at', 'desc')->paginate(10);
        // Home Page Categories
        $categories = DB::table('categories')->orderBy('category_name', 'desc')->get();
        // Return
        return view('welcome' , [ 'categories'=>$categories,'latest_posts'=>$latest_posts]);
    }