Laravel一对多关系删除请求与guzzle

时间:2018-02-25 06:31:59

标签: php laravel api laravel-5 guzzle

我有两个表,书和作者,使用一对多的关系,作为父亲的作者和作为孩子的作者。我使用Guzzle向Book and Author提出客户请求。但是从客户端应用程序删除书籍表请求时出现问题,得到这样的错误

    GuzzleHttp \ Exception \ ServerException (500)
Server error: `DELETE http://localhost:8080/api/author/4` resulted in a `500 Internal Server Error` response: <!DOCTYPE html> <html> <head> <meta name="robots" content="noindex,nofollow" /> <style> (truncated...)

有时它的成功但父表(作者)也被删除了。 当我向邮递员提出请求时,一切正常。

我的代码,谢谢你。

图书管理员API

<

?php

namespace App\Http\Controllers;

use App\Book;
use Illuminate\Http\Request;
use DB;

/**
* 
*/
class BookController extends Controller

{
    public function allBook()
    {
        return response()->json(Book::all());
    }

    public function Book($id)
    {
        return response()->json(Book::find($id));
    }

    public function createBook(Request $request)
    {
        $book = Book::all();
        return Book::create($request->all());
    }

    public function updateBook($id, Request $request)
    {
        $book = Book::find($id);
        $book->update($request->all());

        return response()->json($book, 200);
    }

    public function deleteBook($id)
    {
        Book::find($id)->delete();
        return response('Book deleted', 200);
    }
}

图书迁移表

 <?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBooksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('genres');
            $table->text('synopsis');
            $table->integer('author_id')->unsigned();
            $table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {

    }
}

预订模型

  <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Book extends Model
    {
        protected $fillable =[
            'title','genres','synopsis','author_id'];

        public function author()
        {
            return $this->belongsTo(Author::class);
        }
    }

及其来自客户的请求的书籍控制器

     public function deleteBook($id)
   {
    $client = New GuzzleHttpClient();
       $apiRequest = $client->request('DELETE','http://localhost:8080/api/book/'. $id);

       return redirect()->route('book.index')->with('response', 'Delete book successfully');

   }

0 个答案:

没有答案