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/
Related
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,
...
]);
}
I am making a custom login in Laravel 7. Register is done correctly but login is not working properly. What can i do for login using custom table user_master.
My database table is user_masters.
User_master model:
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User_master extends Model implements Authenticatable
{
//
use HasApiTokens, Notifiable;
protected $fillable = [
'user_full_name', 'user_email', 'user_password','user_otp_code','user_phone'
];
protected $hidden = [
'user_password'
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
This my controller. what have I done wrong here?
<?php
// namespace App\Http\Controllers;
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use App\User_master;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Http\Request;
class UserMasterController extends Controller
{
//
public $successStatus = 200;
/**
* login api
*
* #return \Illuminate\Http\Response
*/
public function login(){
if(Auth::attempt(['user_full_name' => request('user_full_name')])){
$user = Auth::user_master();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success], $this-> successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
/**
* Register api
*
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'user_full_name' => 'required',
'user_email' => 'required|email',
'user_password' => 'required',
'c_password' => 'required|same:user_password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$input['user_password'] = bcrypt($input['user_password']);
$user = user_master::create($input);
$success['token'] = $user->createToken('MyApp')-> accessToken;
$success['user_full_name'] = $user->user_full_name;
return response()->json(['success'=>$success], $this-> successStatus);
}
}
You need to set your authentication driver properly to work with your custom user Model.
Make these configuration in config/auth.php file ,in providers section:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User_master::class, // <---- Your custom user model
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
Notice:
You must implement Illuminate\Contracts\Auth\Authenticatable interface.
Illuminate\Foundation\Auth\User is a class, you cannot implement it.
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
I'am using Laravel 5.8 with pusher to make an broadcast , after i submit the form im getting this 404 not found i have been searching the google for the answer but no luck.
PostPublished.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class PostPublished implements ShouldBroadcast {
use Dispatchable, InteractsWithSockets, SerializesModels;
public $data;
public function __construct($data) {
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn() {
return new Channel('my-channel');
}
public function broadcastAs()
{
return 'Post-Published';
}
}
AdminAnnounceController
public function store(Request $request)
{
$data = request()->validate([
'department' => ['required', 'string', 'max:255'],
'title' => ['required', 'string', 'max:255'],
'content' => ['required', 'string', 'max:255'],
'status' => ['required'],
]);
$data = Announcement::create([
'department' => $data['department'],
'title' => $data['title'],
'content' => $data['content'],
'status' => $data['status'],
]);
event(new PostPublished($data));
return redirect('admin_announce')->with('success', 'the Annonucement has been send');
}
I am using the Laravel multi-auth for multiple users.
I have frontend controller for the public access where no login is required. I want to check there if the user is logged in. If so I want to hide Login nav and show Home/Dashboard nav link which on click should redirect users to his dashboard.
How can I check this in front-end controller/view? Any help is appreciated.
Thanks in advance.
I have following guards:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'university' => [
'driver' => 'session',
'provider' => 'universities',
],
'school' => [
'driver' => 'session',
'provider' => 'schools',
],
'student' => [
'driver' => 'session',
'provider' => 'students',
],
],
Model:
<?php
namespace Modules\Student\Http\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Student extends Authenticatable
{
use Notifiable;
protected $guard = 'student';
protected $fillable = ['first_name', 'last_name', 'email', 'password', 'remember_token'];
public function applications()
{
return $this->hasMany("Modules\Student\Http\Models\Application", 'student_id');
}
public function languages()
{
return $this->hasMany("Modules\Student\Http\Models\StudentLanguage", 'student_id');
}
public function certificates()
{
return $this->hasMany("Modules\Student\Http\Models\StudentCertificate", 'student_id');
}
public function educations()
{
return $this->hasMany("Modules\Student\Http\Models\StudentEducation", 'student_id');
}
}
Controller:
<?php
namespace Modules\Student\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Modules\Admin\Http\Models\Country;
use Modules\Student\Http\Models\Student;
use Modules\Student\Http\Models\Application;
use Modules\Student\Http\Models\StudentCertificate;
use Modules\Student\Http\Models\StudentLanguage;
use Modules\Student\Http\Models\StudentDocument;
use Modules\Student\Http\Models\StudentEducation;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
class StudentController extends Controller
{
protected $redirectTo = '/student';
public function __construct()
{
$this->middleware('auth:student');
}
public function index()
{
return view('student::dashboard');
}
public function profileForm()
{
$countries = Country::get(['id', 'country_name'])->toArray();
$student = Student::with('languages')
->with('certificates')
->with('educations')
->with('educations.country')
->with('ducuments')
->find(Auth::User()->id);
$student->countries = $countries;
$student->docsGroup = $student->ducuments->groupBy('doc_type');
return view('student::student_profile')
->withStudent($student);
}
public function deleteEducation($id)
{
$language = StudentEducation::find($id);
if($language->delete()){
return 'success';
}
}
public function addCertificate(Request $request)
{
$this->validate($request, [
'certificate_name' => 'required',
'certificate_score' => 'required',
]);
$certificate = new StudentCertificate();
$certificate->student_id = Auth::id();
$certificate->certificate_name = $request->certificate_name;
$certificate->score = $request->certificate_score;
if($certificate->save()){
Session::flash('success', 'New certificate added successfully!');
return redirect()->route('student.profile');
};
Session::flash('success', 'Some error occured while addeding certificate!');
return redirect()->back()
->withInput()->with('tab', ['basic_info']);;
}
}
And this is my controller where I want to check if any student/admin.. logged in or not:
<?php
namespace Modules\Student\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Modules\Admin\Http\Models\Degree;
use Modules\Admin\Http\Models\ProgramCategory;
use Modules\University\Http\Models\Program;
use Modules\University\Http\Models\Scholarship;
use Modules\University\Http\Models\University;
use Modules\Admin\Http\Models\Country;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
class FrontendController extends Controller
{
// public function __construct()
// {
// $this->middleware('auth:student');
// }
public static function GetSearchAttributes()
{
$country_ids = University::where([
['status', '=', 'active'],
['id', '>', '0']
])
->get(['country_id'])
->pluck('country_id')
->toArray();
$countries = Country::orderBy('country_name', 'asc')
->whereIn('id', $country_ids)
->get(['id', 'country_name'])
->toArray();
$categories = ProgramCategory::orderBy('category_name', 'ASC')
->with('ProgramsCount')
->where([
['status', '=', 'active'],
['parent_id', '=', null]
])
->get(['category_name', 'id'])
->toArray();
$degrees = Degree::orderBy('degree_name', 'asc')
->where('status', '=', 'active')
->get(['degree_name', 'id'])
->toArray();
$searchAttr['countries'] = $countries;
$searchAttr['categories'] = $categories;
$searchAttr['degrees'] = $degrees;
$searchAttr = (object) $searchAttr;
return $searchAttr;
}
/**
* Display a listing of the resource.
* #return Response
*/
public function index()
{
$logos = University::orderBy('id', 'ASC')
->where([
['status', '=', 'active']
])
->limit(8)
->get();
return view('student::index')->withLogos($logos);
}
Use check()
#if (Auth::guard('student')->check())
///show link for student
#elseif(Auth::guard('admin')->check())
//show link for admin
#else
///show login
#endif
Do this for other guards too. See this for better understanding.