Ad

Is There A Way To Test Eloquent Observers In Laravel 5.8?

- 1 answer

This is the problem I'm having: My code is set in a way that whenever Model's X title gets updated, it should change Model Y's count.

So what I do is, i send request that will trigger the event described above, BUT whenever i check if the changes are made in the database, they are not.

I've tried dd() inside the X Observers updated function, and it gets properly fired.

Any ideas?

Edit: I'm testing with assertDatabaseHas()

Edit2: This is my code for the test

public function testBasicTest()
{
    $user = factory(User::class)->create();
    $book = Book::create([
        'user_id' => $user->id,
        'name' => 'test'
    ]);

    $response = $this->getJson('/api/books-update?book_id=' . $book->id);

    $response->assertStatus(200);

    dd($response->getContent(), DB::table('books')->where('name', '=', 'JAJCA')->get());
}

And this is my Controller:

public function testEndpoint(Request $request)
{
    $book_id = $request->get('book_id');
    $book = Book::find($book_id);
    $book->update([
        'name' => 2
    ]);

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

And this is the [email protected]

public function updated(Book $book)
{
    $book->name = 'JAJCA';
}

The last line from TestBasicTest for getContent prints out: name => JAJCA And for the DB::table('books')->where('name', '=', 'JAJCA')->get() returns empty array.

Ad

Answer

Updated triggers after it has been saved. If you want to change input through events you will also have to use Updating and Creating.

So either use Updating like so, the save will happen after this event, with updated it has already happened.

public function updating(Book $book)
{
    $book->name = 'JAJCA';
}

Models are references so you are updating the object but not saving it.

Ad
source: stackoverflow.com
Ad