-2

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

Tahir D
  • 1
  • 3
  • 2
    you can't point to two methods for a single route like this..you have to add a parameter to the route to distinguish which values to return and add a condition in the controller method to return values based on route parameter. – zahid hasan emon Jan 03 '21 at 15:12
  • 2
    I recommend you read through the [Laravel documentation](https://laravel.com/docs/8.x/routing) and some [tutorials](https://laracasts.com/series/laravel-6-from-scratch) as your code suggests you need to review the basics. – Peppermintology Jan 03 '21 at 15:19

1 Answers1

0

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]);
    }
Tahir D
  • 1
  • 3