Laravel 5.2 PHPUnit attach() doesn't move file - laravel

I have this method to store new user
public function register(CreateUserRequest $request){
$file = $request->file('idcard');
$fileName = rand(0, 99999).$file->getClientOriginalName();
if($request->hasFile('idcard') && $request->file('idcard')->isValid()){
$request->file('idcard')->move("images/idcard/", $fileName);
}
User::create([
'role_id' => 1,
'email' => $request->email,
'password' => $request->password,
'full_name' => $request->full_name,
'address' => $request->address,
'phone' => $request->phone,
'family_name' => $request->family_name,
'family_address' => $request->family_address,
'family_phone' => $request->family_phone,
'idcard' => $fileName,
'status' => 'unconfirmed',
'balance' => 0,
]);
Session::flash('success', 'Please check your email to activate your account.');
return redirect('/register');
}
And I have this unit test
public function testNewUserRegistration()
{
$this->visit('/register')
->type('This is full name', 'full_name')
->type('JL. Mulyorejo 226 D', 'address')
->type('085788884877', 'phone')
->type('Rizky Sugiarto', 'family_name')
->type('JL. Kandangan', 'family_address')
->type('085766669999', 'family_phone')
->attach('/var/www/html/autodealer/images/pics/banner_car.jpg', 'idcard')
->type('mail#yahoo.co.id', 'email')
->type('123456789', 'password')
->type('123456789', 'password_confirmation')
->press('Submit')
->seeInDatabase('users', ['email' => 'mail#yahoo.co.id', 'role_id' => 1, 'balance' => 0, 'status' => 'unconfirmed'])
->seePageIs('/register')
->see('Please check your email to activate your account.');
}
If I test my function via browser, it successfuly input database and move file.
But when I test via PHPUnit it pass the test, successfully input database but the image doesn't move.
Is there something wrong with my attach() or something else wrong?
Thanks, any help appreciated.

Related

Sending custom verification emails from a controller method

I have some data i am receiving from new users and extracting the email to send to the new user. This is how i am doing it
public function register_mechanic_post(Request $request)
{
$validatedData = $request->validate([
'email' => 'required|email|unique:users',
'password' => 'required',
'password_confirmation' => 'required'
], [
'email.required' => 'Email address is required',
'password.required' => 'Password field is required',
'password_confirmation.required' => 'Password confirmation field is required'
]);
$data = $request->all();
$name = $request->input('name');
$data['role'] = 'manager';
$email = $request->input('email');
User::create([
'email' => $request->input('email'),
'name' => $request->input('name'),
'role' => 'manager',
'password' => Hash::make($request->input('password')),
//'email_verified_at' => now()
]);
$user = User::where('email','=',$email)->first();
$user->sendEmailVerificationNotification();
return back()->with('success', 'Mechanic created successfully.');
}
I am getting this error
403 THIS ACTION IS UNAUTHORIZED
The docs say its because of signed urls https://laravel.com/docs/9.x/urls#signed-urls
I haven't modified the existing email verification code as shipped with laravel. How do i use the signed urls feature in my case?.
Not an answer, but your code could be significantly simpler, making it easier to manage in the future.
public function register_mechanic_post(Request $request)
{
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
'password_confirmation' => 'required'
], [
'email.required' => 'Email address is required',
'password.required' => 'Password field is required',
'password_confirmation.required' => 'Password confirmation field is required'
]);
$user = User::create([
'email' => $validatedData['email'],
'name' => $validatedData['name'],
'role' => 'manager',
'password' => Hash::make($validatedData['password']),
'email_verified_at' => now()
]);
$user->sendEmailVerificationNotification();
return back()->with('success', 'Mechanic created successfully.');
}
But why ask the user to verify their email when you are already setting the email_verified_at timestamp (indicating that verification has been performed)

Laravel Phpunit testing a request that take give output based on the request

I'm still new to laravel and I have a simple app and aSo I have a route that will store data based on the request in my controller.
public funtion store(Request $request, $id){
if ($request->has('work_experiences')) {
WorkExperience::create([
'user_id' => $user->id,
'position' => $request->work_experiences['position'],
'company' => $request->work_experiences['company'],
'start_date' => $request->work_experiences['start_date'],
'end_date' => $request->work_experiences['end_date'],
]);
}
if ($request->has('education')) {
Education::create([
'user_id' => $user->id,
'degree' => $request->education['degree'],
'university' => $request->education['university'],
'start_date' => $request->education['start_date'],
'end_date' => $request->education['end_date'],
]);
}
if ($request->has('job_interests')) {
JobInterest::create([
'user_id' => $user->id,
'job_position' => $request->job_interests['position'],
]);
}}
}
and in my test
public function test_authenticated_user_can_edit_education_profile()
{
$this->withoutExceptionHandling();
$user = User::factory()->create();
$this->actingAs($user);
$response = $this->post('/candidate' . '/' . $user->id, [
'user_id' => $user->id,
'position' => 'position',
'company' => 'company',
'start_date' => Carbon::now(),
'end_date' => Carbon::now(),
]);
$this->assertCount(1, WorkExperience::all());
}
when I run the test, the assertCount seems to fail because the response didn't work/insert the data to DB. where do I do wrong?
Well, the test is right.
It should fail because there is no work_experiences key in your request data.
The test request should look like:
$response = $this->post('/candidate' . '/' . $user->id, [
'work_experiences' => [
'user_id' => $user->id,
'position' => 'position',
'company' => 'company',
'start_date' => Carbon::now(),
'end_date' => Carbon::now(),
]
]);
So your data should go under a work_experiences key such that $request->has('work_experiences') returns true and executes the WorkExperience::create() statement.
Currently your endpoint only allows for a single "work experience" to be created. Seeing that you've named it work_experiences I assume you'd want to pass in an array/collection of "work experiences" - but that won't work with the current implementation; you'll have to loop over them instead - something like this:
if ($request->has('work_experiences')) {
foreach ($request->input('work_experiences') as $experience) {
WorkExperience::create([
'user_id' => $request->user()->id,
'position' => $experience['position'],
'company' => $experience['company'],
'start_date' => $experience['start_date'],
'end_date' => $experience['end_date'],
]);
}
}
And then your test should look something like this:
$response = $this->post('/candidate' . '/' . $user->id, [
'work_experiences' => [
[
'user_id' => $user->id,
'position' => 'position',
'company' => 'company',
'start_date' => Carbon::now(),
'end_date' => Carbon::now(),
],
// more "work experiences"
]
]);

mutiple emails controller is not working how do i solve?

i have a problem this controller is not working how can i do? should send mutiple emails how do i solve?
I don't know how to handle it
function submit(Request $request) {
$this->validate($request, [
'email' => 'required|email',
'file' => 'mimes:pdf,doc,docx'
]);
$data = array(
'name' => $request->name,
'cognome' => $request->cognome,
'luogo' => $request->luogo,
'date' => $request->date,
'telefono' => $request->telefono,
'email' => $request->email,
'citta' => $request->citta,
'provincia' => $request->provincia,
'studio' => $request->studio,
'lingua' => $request->lingua,
'livello' => $request->livello,
'lingua2' => $request->lingua2,
'livello2' => $request->livello2,
'file' => $request->file,
'agree' => $request->agree
);
Mail::send('mail', $data, function($message) use ($request,$data){
$message->to('luis#gmail.com', 'luis')->subject('Send mail ' . $request->name);
$message->from($request->email, $request->name);
if($request->hasFile('file')){
$message->attach($request->file('file')->getRealPath(), array(
'as' => $request->file('file')->getClientOriginalName(),
'mime' => $request->file('file')->getMimeType())
);
}
});
Session::flash('success', 'Mail spedita con sucesso');
}
I wish I could solve the problem
any advice? on how to do it?

Login when successfully updated the data of the user in Laravel

RegisterController.php
I added here an update function so that when the user wants to login with Facebook, he/she will be redirected to a form and then fill the fields so that their information will be stored in the Database.
protected function create(array $data)
{
if ($data['userEmail']) {
return User::where('email', $data['userEmail'])
->update([
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
} else {
return User::create([
'full_name' => $data['full_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
}
}
The error when the IF statement returns true is this
"Type error: Argument 1 passed to
Illuminate\Auth\SessionGuard::login() must implement interface
Illuminate\Contracts\Auth\Authenticatable, integer given, called in
C:\xampp\htdocs\esoftwaredeals\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php
on line 35".
However, if it returns false, there will be no error and a new user is created and will automatically redirect to the "/my-account" page which is where I wanted to redirect when the user successfully updated their information.
You need to return User instance from the create() method:
protected function create(array $data)
{
if ($data['userEmail']) {
$user = User::where('email', $data['userEmail'])->first();
$user->update([
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
} else {
$user = User::create([
'full_name' => $data['full_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'phone_number' => $data['phone_number'],
'address' => $data['address'],
'country' => $data['country'],
'city' => $data['city'],
'zip_code' => $data['zip_code'],
'state' => $data['state'],
'is_online' => true,
]);
}
return $user;
}
Also, you should use the updateOrCreate() method to keep the code maintainable. For example:
protected function create(array $data)
{
$data['password'] = bcrypt($data['password']);
return User::updateOrCreate(
array_only($data, ['email', 'full_name']),
array_except($data, ['email', 'full_name'])
);
}
An update query returns the number of rows that where affected by the update query.So when the update user is successful it will return 1.
The create method returns the saved model instance. So this is causing the issue in your code.
You can use find and save method provided by eloquent and return the user object in if statement and it will work.
$user = User::where('email', $email)->first();
$user->firstname = $firstname;
$user->lastname = $lastname;
$user->save();
return $user;
Try like this and it should work.
$user = User::find($usuario->ID);
$user->rol_id = 1;
$user->save();
}
}
}
return view('dashboard.index')->with(compact('cantReferidosDirectos', 'cantReferidosIndirectos', 'cantReferidosActivos', 'fechaProxActivacion', 'new_member',
'cantventas', 'cantventasmont', 'fullname', 'rangos', 'cantAllUsers', 'rankingComisiones', 'rankingVentas', 'permiso','noticias', 'contTicket', 'moneda',
'nombreRol'
));
}
/**
* Permite actualizar las informacion de los usuarios
*
* #access public
* #return view
*/
public function ActualizarTodo()
{
$comisiones = new ComisionesController;
$comisiones->ObtenerUsuarios();
$todousers = $this->generarArregloUsuario(Auth::user()->ID);
foreach ($todousers as $user ) {
if ($user['rol'] != 0) {
$activacion = new ActivacionController;
$activacion->activarUsuarios($user['ID']);
}
}
Arguments
"compact(): Undefined variable: fechaProxActivacion"
Como soluciono este error

update function is not working

I am trying to update my database for a user by this code , but it is not working . there is no change by the way!
public function update( Request $request)
{
$request->user()->tasks()->where('id', '=', $request->id)->update([
'name' => $request->title,
'body' => $request->body,
]);
return redirect('/request');
}
Try code and update database:
App\User::find($request->id)->tasks()->update([
'name' => $request->title,
'body' => $request->body
]);
return redirect('/request');
If you already know the id of the task, make it easy on yourself.
Task::find($request->id)->update([
'name' => $request->title,
'body' => $request->body
]);

Resources