I am doing feature testing for my Laravel application. I am trying to update an authenticated user data. I am using actingAs to authenticate my user in my test code and then trying to post with some data to update that user data. But I am getting "Call to a member function update() on null" error.
This problem only happening on test case. original application working fine.
public function an_authenticated_account_user_with_valid_role_can_change_2fa_option()
{
$this->withoutExceptionHandling();
//preventing middlewares
$this->withoutMiddleware(\App\Application\Middleware\VerifyCsrfToken::class);
$attributes = [
'two_step' => 'no'
];
$response = $this->actingAs($this->validRoleUser, 'account')
->post('/account/security/change-2fa', $attributes);
$response->assertStatus(200);
$response->assertSee('Please select an option');
}
I am getting this error message during test above code:
Call to a member function update() on null
Related
I am trying to access Authenticated User information inside the Stripe-Webhook-Url function. But when webhook url hits, the Auth inside that function doesn't return anything!
Here is the route and action I am working with:
route
Route::post('stripe-webhook', [StripeController::class, 'stripe_webhook']);
action
public function stripe_webhook(Request $request)
{
$response = $request->all();
$user_id = Auth::id(); // It returns Nothing.....
}
In the above function, The Auth returns nothing. Even session doesn't work inside this function.
I am trying to debug this issue but nothing worked out. Kindly help me to sort out this problem.
Thanks!
I've created a custom request in my project, but somehow it is not working. I'm facing two errors. I'm trying to show a message on view if validation fails through Ajax.
1) 422 Unprocessable Entity error
and
2) Undefined variable: teacherrequest
validation rules which i set in Request folder,
TeacherRequest.php:
public function rules()
{
return [
'Name' => 'required|regex:/^[\pL\s\-]+$/u',
'FName' => 'required|regex:/^[\pL\s\-]+$/u',
];
}
Controller:
public function update(TeacherRequest $request, $id)
{
if ($teacherrequest->fails()) {
return response()->json([
'msg' => 'Please Enter Correct Data',
]);
}
}
AJAX:
success: function (data) {
if(data.msg){
alert("please validate data");
}
}
Update:
if i remove if condition, i am getting 422 error, how to show that on view?
First, public function update(TeacherRequest $request) so in the function you need to use $request not $teacherrequest.
And second You need to have public function authorize() returning true.
You define TeacherRequest as $request TeacherRequest $request
but in next line use it as
if ($teacherrequest->fails()){ // this is wrong
correct one should be define like this
TeacherRequest $teacherrequest
or if you didn't change the dependency injection, just change the validator like this
if ($request->fails()){
summary: why error happened already specifically explained which is undefined teacherrequest variable, therefore 2 solutions above can solve it
If you type hint your request class as a parameter in your controller's action method (like you are doing in the example above) Laravel will automatically run your validation rules and return a 422 Unprocessable Entity if validation fails. You don't need to manually check if validation fails like you're doing above; in your controller's update method you can just implement the logic you want to run when validation passes.
Also on your front end you will need to use the error ajax callback to display the error message because a 422 status code is not considered successful.
See the documentation on creating form requests.
So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic.
I am new to PHPUnit and TDD. I just upgrade my project from Laravel 5.4 to 5.5 with phpunit 6.5.5 installed . In the learning process, I wrote this test:
/** #test */
public function it_assigns_an_employee_to_a_group() {
$group = factory(Group::class)->create();
$employee = factory(Employee::class)->create();
$this->post(route('employee.manage.group', $employee), [
'groups' => [$group->id]
]);
$this->assertEquals(1, $employee->groups);
}
And I have a defined route in the web.php file that look like this
Route::post('{employee}/manage/groups', 'ManageEmployeeController#group')
->name('employee.manage.group');
I have not yet created the ManageEmployeeController and when I run the test, instead of get an error telling me that the Controller does not exist, I get this error
Failed asserting that null matches expected 1.
How can I solve this issue please?
The exception was automatically handle by Laravel, so I disabled it using
$this->withoutExceptionHandling();
The test method now look like this:
/** #test */
public function it_assigns_an_employee_to_a_group() {
//Disable exception handling
$this->withoutExceptionHandling();
$group = factory(Group::class)->create();
$employee = factory(Employee::class)->create();
$this->post(route('employee.manage.group', $employee), [
'groups' => [$group->id]
]);
$this->assertEquals(1, $employee->groups);
}
You may not have create the method in the Controller but that doesn t mean your test will stop.
The test runs.It makes a call to your endpoint. It returns 404 status because no method in controller found.
And then you make an assertion which will fail since your post request
wasn't successful and no groups were created for your employee.
Just add a status assertion $response->assertStatus(code) or
$response->assetSuccessful()
Hello stackoverflow geeks, I'm in my final stages of the laravel learning curve all thanks to you guys.
However, i need to generate a warning message like "You cannot delete a role assigned to a user" every time a user tries to delete a role assigned to a user.
instead it loads a page with an sql error. how to i do it?
And how do i avoid a password that has been already been stored from being hashed again. eg:- $2y$10$p8JwI5P4yE2UFo2.vHP99.0dP2jU7ll/9w73IzUa9/yegKOSTHJWq is always hashed every time i edit a user's information.
Thanks you all who've made learning laravel easy for me by answering in time
code
public function destroy(Request $request,$id)
{
// delete
// $role = Role::find($id);
//$role->delete();
$role = Role::find ($id);
if ($role->users() !=null) {
return redirect()->back()->withInput(['warning' => 'Not allowed']);
}
$role->delete();
// redirect
Session::flash('message', 'Record successfully deleted!');
Session::flash('alert-type', 'success');
return Redirect::to('role');
}
This highly depends on how you want to handle the errors. You can either catch the sql exception and display your custom error OR what is probably better for you is to handle the incoming request, validate it and return an error if validation fails.
Here are the validation docs : https://laravel.com/docs/5.3/validation
You have multiple options on how to validate a request. Simple example to validate a title is unique in the table posts and is maximum 255 chars long:
$this->validate($request, [
'title' => 'required|unique:posts|max:255'
]);
If you cannot find a rule that is helping you simply define your own validation rule https://laravel.com/docs/5.3/validation#custom-validation-rules
Ofcourse you can also do the validation manually. In your request or in your controller (depends on your setup) just check for it
// assuming you want to delete an entry
public function delete(Request $request, $id)
{
$role = App\Role::findOrFail($id);
if ($role->users() != null) {
return redirect()->back()->withInput(['message' => 'Not allowed']);
// now you can output $message
}
$role->delete();
return ...
}
I'm trying to attach the currently logged in user to this request, so that I can save it in the database. Can someone point me in the right direction, please?
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$leadStatus = $this->leadStatusRepository->create($input);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
So, I have come up with the following using array_merge, but there must be a better way, surely?
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$userDetails = array('created_by' => Auth::user()->id, 'modified_by' => Auth::user()->id);
$merged_array = array_merge($input, $userDetails);
$leadStatus = $this->leadStatusRepository->create($merged_array);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
So you can use Auth Facade to get information of currently logged user.
For Laravel 5 - 5.1
\Auth::user() \\It will give you nice json of current authenticated user
For Laravel 5.2 to latest
\Auth::guard('guard_name')->user() \\Result is same
In laravel 5.2, there is new feature called Multi-Authentication which can help you to use multiple tables for multiple authentication out of the box that is why the guard('guard_name') function is use to get authenticated user.
This is the best approach to handle these type of scenario instead of attaching or joining.
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$userDetails = \Auth::user(); //Or \Auth::guard('guard_name')->user()
$leadStatus = $this->leadStatusRepository->create($input);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
Hope this helps.