Testing 'factory' undefined - laravel

Hi im trying to implement a test_user_can_login_with_correct_credentials test and i cant figure out why there is a 'factory' undefined error.
I've searched online and people seem to be getting this because they haven't imported the user model but i have
here is the code
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;
class LoginTest extends TestCase
{
/**
* A basic feature test example.
*
* #return void
*/
public function test_user_can_view_a_login_form()
{
$response = $this->get('/login');
$response->assertSuccessful();
$response->assertViewIs('auth.login');
}
public function test_user_can_login_with_correct_credentials()
{
$user = factory(User::class)->create([ // Error with 'factory' on this line
'first_name' =>('John'),
'last_name' => ('Smith'),
'email' => ('john#example.com'),
'date_of_birth' => ('16/02/2001'),
'password' => Hash::make('test'),
'join_date' => Carbon::now()
]);
$response = $this->from('/login')->post('/login', [
'email' => $user->email,
'password' => 'test',
]);
$response->assertRedirect('/login');
$response->assertSessionHasErrors('email');
$this->assertTrue(session()->hasOldInput('email'));
$this->assertFalse(session()->hasOldInput('password'));
$this->assertGuest();
}
}
The exact error is 'Undefined function 'Tests\Feature\factory'.intelephense(1010)'
Any help would be appreciated im unsure of how to resolve this

Related

php artisan migarate:fresh -seed keep getting error

i keep getting this error whenever i tried to use php artisan migarate:fresh -seed. What should i do?
Error
Class "Database\Seeders\User" not found
at D:\database\seeders\UserTableSeeder.php:16
`enter code here` 12▕ * #return void
13▕ */
14▕ public function run()
15▕ {
➜ 16▕ User::factory()->create([
17▕ 'name' => 'Admin',
18▕ 'email' => 'admin#example.com',
19▕ 'password' => bcrypt('password'),
20▕ 'type' => User::ADMIN,
A namespace is failing, try this instead.
In your User.php model
Ensure the class has this trait included:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory; // <-- Add this
class User
{
use HasFactory; // <-- Add this
...
}
In your user seeder
public function run()
{
\App\Models\User::factory()->create([ // <-- Reference the user this way
'name' => 'Admin',
'email' => 'admin#example.com',
'password' => bcrypt('password'),
'type' => User::ADMIN,
...
]);
}

Laravel - How to make Cron Job work on my localhost Windows

I am consuming and external API using Guzzle. The I want to save into the database on my localhost before I eventually move it to the server.
Localhost:8888/myapp
It works on Postman and I could see the data when I used dd();
Console\Commands\UpdateCreateEmployee
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Employee;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
class UpdateCreateEmployee extends Command
{
protected $signature = 'command:UpdateCreateEmployee';
protected $description = 'Update or Create Employee Profile';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$userCompany = Auth::user()->company_id;
$client = new Client();
$res = $client->request('GET','https://api.apptest.net/staff', [
'query' => ['key' => 'wwwwwwdddd']
])->getBody();
$clientdatas = json_decode($res->getContents(), true);
foreach($clientdatas as $clientdata)
{
$employee = HrEmployee::updateOrCreate([
'employee_code' => $clientdata->staff_id,
],
[
'username' => strtok($request->email_company, '#'),
'first_name' => $clientdata->first_name,
'last_name' => $clientdata->flast_name,
'other_name' => $clientdata->middle_name,
'date_of_birth' => Carbon::parse($clientdata['date_of_birth'])->toDateString(),
'hr_status' => $clientdata->hr_status,
'address' => $clientdata->address,
'company_id' => 1,
'country_name' => $clientdata->country,
'email' => $clientdata->email,
]);
//user
$user = User::updateOrCreate([
'email' => $employee->email,
],
[
'username' => $employee->username,
'password' => bcrypt("123456"),
'first_name' => $employee->first_name,
'last_name' => $employee->last_name,
]);
$user->assignRole('Employee');
$employee->update(['user_id' => $user->id]);
}
}
}
kernel
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
'App\Console\Commands\UpdateCreateEmployee',
];
protected function schedule(Schedule $schedule)
{
$schedule->command('command:UpdateCreateEmployee')
->everyFifteenMinutes();
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
After fifteen minutes, I checked the database, there was nothing there.
How do I make it work on my localhost windows?
Thanks
The native way to use cron jobs under Windows environment is Task Scheduler.
Make a new task to run every minute:
Program script: path/to/your/php.exe
Add arguments: path/to/your/artisan schedule:run
More information can be found here: https://quantizd.com/how-to-use-laravel-task-scheduler-on-windows-10/

Undefined property: App\Http\Controllers\ProfessionalsController::$user

I want to add the user while adding a vendor, but it shows me error. I have created the object of class User. This is my code:
<?php
namespace App\Http\Controllers;
use Session;
use App\Vendors;
use App\User;
use App\Category;
use App\Location;
use Illuminate\Http\Request;
class VendorsController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|min:2|max:20',
'email' => 'required|email|unique:users,email'
]);
$data = array(
'name' => $request->name,
'email' => $request->email,
'role' => 'Vendor'
);
$this->user->fill($data);
$this->user->save();
$professional = Professional::create([
'user_id' => $this->user,
'contact_number' => $request->contact_number,
'address' => $request->address,
'about_us' => $request->about_us,
'category_id' => $request->category_id
]);
return redirect()->back();
}
}
But I am getting this error:
Undefined property: App\Http\Controllers\ProfessionalsController::$user
Any help will be appreciated.

Laravel resources when called in usersController gives me a different path and an error

I am a week old into laravel and am working on my first api.
Everything worked well till I decided to introduce resources. When I call the UserResource method I get an error that I can't understand. I have googled but haven't found an answer yet.
This is the error I get when I run on postman
Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined function App\Http\Controllers\Api\UserResource()
The Resource file is in app/Http/Resources/
Checkout the path returned
App\Http\Controllers\Api\UserResource
yet the one I add is
App\Http\Resources\UserResource;
Laravel Code:
app/Http/Controllers/Api/usersController.php
use App\User;
use App\Http\Resources\UserResource;
class UsersController extends Controller
{
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$email = $request->email;
$password = $request->password;
$user = User::where('email', $email)->where('password', $password)->first();
if($user) {
$success['token'] = $user->createToken('myapp')-> accessToken;
$success['user'] = UserResource($user);
return response()->json(['success' => $success], 200);
}
return response()->json(['error' => 'UnAuthorised'], 401);
}
}
app/Http/Resources/UserResource.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'other_names' => $this->other_names,
'email' => $this->email,
'phone_number' => $this->phone_number,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
You forgot the new operator trying to instantiate the UserResource class. Without the new operator, PHP will look for a function called UserResource in the current namespace, therefore you get that error.

Call to undefined method Illuminate\Http\JsonResponse::validate() in Laravel 5.3

I am implementing a registration form using JSON post request and laravel 5.3 with the below Controller settings
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
$data = $data['Register'];
$validator = Validator::make($data, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
if($validator->fails())
{
$errors = $validator->errors()->all()[0];
//dd($errors);
return response()->json(['errors'=>$errors]);
}
else
{
return $validator;
}
}
protected function create(array $data)
{
$data = $data['Register'];
//dd($data);
User::create([
//'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
return response()->json(['success' => $data['email']], 200);
}
}
But i want to track server errors in the event of multiple registration with the same email. I have handled this on the client side but in need to handle on the backend too.
The Problem is with the validator function it keep returning below error
FatalThrowableError in RegistersUsers.php line 31:
Call to undefined method Illuminate\Http\JsonResponse::validate()
I have checked inside the framework code and there is a validate method which seems to be unrecognized with the json response any ideas?

Resources