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 [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.
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.
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms