Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to test Eloquent Observers in Laravel 5.8?

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 BookObserver@updated

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.

like image 263
boka18 Avatar asked Dec 02 '25 23:12

boka18


1 Answers

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.

like image 173
mrhn Avatar answered Dec 04 '25 20:12

mrhn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!