如何在Laravel中将数据从一个视图传递到另一个视图?

时间:2019-11-29 23:35:13

标签: php laravel

我对Laravel很陌生

我有两个观点

  • 阅读

Book View显示一本书

<section class="cont-readingone">
  <div class="container">
    <div class="row row-grid">
      <div class="col-md-6">
        <div class="row">
          <div class="col-md-6">
            <div class="cont-reading-image">
              <img src="{{ $book->image_url }}" alt="trending image" />
            </div>
          </div>
          <div class="col-md-6">
            <div class="out-box">
              <h2>{{ $book->name }}</h2>
              <h3>{{ $book->author->name }}</h3>
              <br>
              <a href="#" class="start-btn">Start Reading</a><br><br>
              <a href="#" class="buy-btn"><img src="\images\cart-buy.png" width="13px"/>&nbsp; Buy</a>
            </div>
          </div>
        </div>
      </div>

在我的控制器中,我能够使用

    public function show(Book $book) {

        $relatedBooks = Book::where('author_id', $book->author_id)
  ->where('id', '!=', $book->id)
  ->get();

    return view('book')->with('book', $book)->with('relatedBooks', $relatedBooks);
     }

在我的web.php

Route::get('/books/{book}', [BooksController::class, 'show'])->name('book');
  

我要实现的目标是,当我点击开始阅读   单书页,它将带我到另一个视图页(Read),但它带了我单击的书号。

Read View中,我有这段代码

    <script>
        "use strict";

        document.onreadystatechange = function () {
          if (document.readyState == "complete") {
            window.reader = ePubReader("{{ $book->epub_url }}", {
               restore: true
             });
          }
        };

    </script>
  

我的问题是我不知道如何获取我所著书的ID   单击并将其传递到Read View

如果有人可以向我解释逻辑,我会感到很高兴。

1 个答案:

答案 0 :(得分:0)

  

通过POST进行

//Book View
//change  <a href="#" class="start-btn">Start Reading</a> to
<form action="{{ route("your.route.to.read") }}" method="POST">
   @csrf
   <input name="book_id " value ={{$book->id}} hidden>
   <button type="submit">Start Reading</button>
</form>

//your Route will be
Route::get('/read',YourReadController@yourFunction)->name('your.route.to.read');

//your controller will be 
public function yourFunction(Request $request)
{
    //book id is in $$request->book_id
    //your operation here
    return view('read')->with('data',$dataYouWantToSend);
}
  

通过GET进行操作

//Book View
    //change  <a href="#" class="start-btn">Start Reading</a><br><br> to
<a href="{{route("your.route.to.read", $book->id)}}" class="start-btn">Start Reading</a>

//route for get will be 
Route::get('/read/{book_id}',YourReadController@yourFunction)->name('your.route.to.read');

//your countroller will be 
public function yourFunction($book_id)
{
   //book id is in $book_id
   //your operation here
   return view('read')->with('data',$dataYouWantToSend);
}