简体   繁体   中英

Passing data from blade to route

I'm trying to list articles from database then show details of the article when the user clicks on it. How can I pass the article id or name to the route/controller to display the details? I tried butting the id in the href but I don't know how to handle it from routes!

this is the articles list:

@foreach ($articles as $article)
    <div class="panel-body">
        <a href="#">{{$article->name}}</a>
    </div>
@endforeach

where do I go from here?

If you want to use route() you can pass parameters in second argument

@foreach ($articles as $article)
     <div class="panel-body">
          <a href="{{ route('article.show', [$article->id]) }}">{{ $article->name }}</a>
                             ^^^ or whatever is the name of your route
     </div>
@endforeach

Naturally this assumes you have your route defined in app\\Http\\routes.php . For example

Route::get('/articles/{id}', ['as' => 'article.show', 'uses' => 'ArticleController@show']);

Alternatively you can use url()

@foreach ($articles as $article)
     <div class="panel-body">
          <a href="{{ url('/articles', [$article->id] }}">{{ $article->name }}</a>
     </div>
@endforeach

Your View file for listing all the articles:

@foreach ($articles as $article)
    <div class="panel-body">
        <a href="/article/{{ $article->id }}">{{$article->name}}</a>
    </div>
@endforeach

routes.php

Route::get('/article/{id}', 'ArticlesController@show');

ArticlesController.php

/**
 * Show the article of the given id.
 *
 * @param int $id The id of the article
 * @return \Illuminate\View\View
 */
public function show($id)
{
    $article = Article::findOrFail($id);

    return view('articles.show', compact('article'));
}

show.blade.php

<h3>{{ $article->name }}</h3>

<p>{{ $article->body }}</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM