Laravel 5: how can I retrieve and display all post

2019-05-23 09:41发布

问题:

I have 3 tables

user:       id, username
subreddits: id, name, created_at
posts:      id, title, link, user_id, subreddit_id

The problem is, I am fetching the id of the subreddit / category manually while I need to be fetching it dynamically. How can I achieve that?

This is the show() method in SubredditController.php

public function show(Subreddit $subreddit)
    {

        $posts = Subreddit::findOrFail(3)->posts()->get();

        return view('subreddit/show')->with('subreddit', $subreddit)
                                    ->with('posts', $posts);
    }

And this is Subreddit Model

class Subreddit extends Model
{
    protected $fillable = [
        'name',
        'description'
    ];

    public function user() {
        return $this->belongsTo('App\User');
    }

    public function posts() {
        return $this->hasMany('App\Post');
    }
}

routes.php

Route::resource('subreddit', 'SubredditController');
Route::resource('posts', 'PostsController');

RouteServiceProvider.php

$router->model('articles', 'App\Article');
$router->model('subreddit', 'App\Subreddit');
$router->model('posts', 'App\Post');

回答1:

As you are using Route Model Binding, Laravel will automatically retrieve an object for the $id provided in the URI, which can then be injected into your method as an argument using dependency injection.

public function show(Subreddit $subreddit){ ... }

You can access the data as you would any object. E.g. To access the id of the record you can use $subreddit->id.

public function show(Subreddit $subreddit)
{
    $posts = Subreddit::findOrFail($subreddit->id)->posts()->get();

    return view('subreddit/show')->with('subreddit', $subreddit)
                                    ->with('posts', $posts);
}


回答2:

I'm fairly new with Laravel, but I think you need to define a route with parameters (sorry if I misunderstood your question).

http://laravel.com/docs/5.1/routing#route-parameters



回答3:

You need to pass the id using your route.

In your routes.php file, you can have this:

Route::get('subreddit/{id}', 'SubredditController@show');

And in SubredditController.php, pass the id to your method, like this:

public function show($id)
{
    $subreddit = Subreddit::findOrFail($id);
    $posts = $subreddit->posts()->get();

    return view('subreddit/show')->with('subreddit', $subreddit)
                                 ->with('posts', $posts);
}


回答4:

Why you are typing the model to the parameter of the function?

show(Subreddit $subreddit)

I saw it somewhere, but I cannot remember the need to use it.

are you using the column id autoincrement in the database?, if not, you have to especify it in the model adding the property incrementing and set it to false

public $incrementing = false;

and specify the actual primarykey

protected $primaryKey = 'code';

With the configuration that you posted, this code works for me:

routes.php

Route::resource('subreddit', 'SubredditController');

SubredditController.php

public function show($id)
{
    $subreddit = Subreddit::findOrFail($id);
    $subreddit->load('posts');
    return view("subreddit/show")->with("subreddit", $subreddit);
}

url

http://localhost:8888/test/public/subreddit/1

I'm loading the relation in the same object so send only one param to the view



回答5:

I think what you want here is route model binding

If you are using laravel 5, jeff way happens to have a very good tutorial for it here

here is also the documentation for route model binding.

Good news is Route model Binding is also flexible, even binding a complex data subset from your model to the route. which i think will fit your need.



回答6:

Fetch category with all posts

$categories = Subreddit::with('posts') -> where('id',$id) -> first(); 
if (categories){
  $data['results'] = categories;
}else{
  $data['results'] = null;
}

return view('myview') -> with($data);

The variable $results will be accessible in your view. In your view

if (!is_null($results){
  foreach($results as $result){
    // do something.
  }
} 

Hooe this help.