Code Igniter 4 Restful API only default controller, routes not work - php

I try to create restful api using Code Igniter 4 on Apache2. If I open http://<my-ip:port>, it shows welcome message. Then I created Account.php controller to get account list from database.
<?php namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\AccountModel;
class Account extends ResourceController
{
use ResponseTrait;
public function index()
{
$model = new AccountModel();
$data = $model->findAll();
return $this->respond($data, 200);
}
public function show($id = null)
{
$model = new AccountModel();
$data = $model->getWhere(['account_id' => $id])->getResult();
if($data){
return $this->respond($data);
}else{
return $this->failNotFound('No Data Found with id '.$id);
}
}
}
AccountModel.php
<?php namespace App\Models;
use CodeIgniter\Model;
class AccountModel extends Model
{
protected $table = 'account';
protected $primaryKey = 'id';
protected $allowedFields = ['account_id','name'];
}
I set Cors and Filters.
and this is my routes
<?php
namespace Config;
$routes = Services::routes();
if (file_exists(SYSTEMPATH . 'Config/Routes.php')) {
require SYSTEMPATH . 'Config/Routes.php';
}
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);
//$routes->get('/','Home::index');
$routes->resource('account');
if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) {
require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
}
http://my-ip:port shows welcome message. But if I open http://<my-ip:port/account> using postman I got error
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
<hr>
<address>Apache/2.4.46 (Ubuntu) Server at <my-ip> Port 80</address>
</body></html>
and I set Account as a default controller $routes->setDefaultController('Account'); I got list of account if I open http://<my-ip:port>. Do I miss some set up? I want to get account list if I open http://<my-ip:port/account> and others.

Is it works if tried http://<my-ip:port/index.php/account? if yes, you have to config your apache to hide index.php from URL.
visit following link for more infos. => more infos

look at my code best way using restful ctl ci4
first routs
<?php
/*
* Core Auth routes file.
*/
$routes->group('api', ['namespace' => 'Modules\Auth\Controllers'], function ($routes) {
$routes->resource('group', ['filter' => 'authJwt']);
$routes->resource('permission', ['filter' => 'authJwt']);
$routes->resource('groupPermission', ['filter' => 'authJwt']);
$routes->resource('userPermission', ['filter' => 'authJwt']);
$routes->group('auth', function ($routes) {
$routes->post('signin-jwt', 'Auth::signInJwt', ['filter' => 'isSignIn']);
$routes->post('signin', 'Auth::signIn', ['filter' => 'isSignIn']);
$routes->get('signout', 'Auth::signOut', ['filter' => 'authJwt']);
$routes->get('is-signin', 'Auth::isSignIn',['filter' => 'authJwt']);
$routes->post('signup', 'Auth::signUp', ['filter' => 'isSignIn']);
$routes->post('forgot', 'Auth::forgot', ['filter' => 'isSignIn']);
$routes->post('reset-password-email', 'Auth::resetPasswordViaEmail', ['filter' => 'isSignIn']);
$routes->post('reset-password-sms', 'Auth::resetPasswordViaSms', ['filter' => 'isSignIn']);
$routes->post('activate-account-email', 'Auth::activateAccountViaEmail', ['filter' => 'isSignIn']);
$routes->post('send-activate-email', 'Auth::sendActivateCodeViaEmail', ['filter' => 'isSignIn']);
$routes->post('activate-account-sms', 'Auth::activateAccountViaSms', ['filter' => 'isSignIn']);
$routes->post('send-activate-sms', 'Auth::sendActivateCodeViaSms', ['filter' => 'isSignIn']);
});
});
sencond api ctl
<?php
namespace Modules\Shared\Controllers;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*
* #package CodeIgniter
*/
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use Modules\Auth\Config\Services;
use Myth\Auth\AuthTrait;
use Psr\Log\LoggerInterface;
use Modules\Shared\Interfaces\UrlAggregationInterface;
use Modules\Shared\Libraries\UrlAggregation;
class ApiController extends ResourceController
{
use AuthTrait;
protected $format = "";
public object $userObject;
public UrlAggregationInterface $urlAggregation;
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* #var array
*/
protected $helpers = [
'cookie',
'url',
'from',
'filesystem',
'text',
'shared'
];
/**
* Constructor.
*
* #param RequestInterface $request
* #param ResponseInterface $response
* #param LoggerInterface $logger
*/
/**
* #var string
* Holds the session instance
*/
protected $session;
public function __construct()
{
$this->userObject = (object)[];
}
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
$this->urlAggregation = new UrlAggregation($request);
$requestWithUser = Services::requestWithUser();
$this->userObject = $requestWithUser->getUser();
}
}
thrid ctl
<?php namespace Modules\Auth\Controllers;
use Modules\Auth\Config\Services;
use Modules\Auth\Entities\GroupEntity;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Shared\Controllers\ApiController;
class Group extends ApiController
{
/**
* index function
* #method : GET
*/
public function index()
{
$groupEntity = new GroupEntity();
$this->urlAggregation->dataMap($groupEntity->getDataMap());
$groupService = Services::groupService();
$findAllData = $groupService->index($this->urlAggregation);
return $this->respond([
'data' => $findAllData['data'],
'pager' => $findAllData['pager']
], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
/**
* show function
* #method : GET with params ID
*/
public function show($id = null)
{
$groupService = Services::groupService();
$findOneData = $groupService->show($id);
return $this->respond([
'data' => $findOneData['data'],
'pager' => $findOneData['pager']
], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
public function create()
{
$rules = [
'name' => 'required|min_length[3]|max_length[255]|is_unique[auth_groups.name]',
'description' => 'required|min_length[3]|max_length[255]',
];
if (!$this->validate($rules)) {
return $this->respond([
'error' => $this->validator->getErrors(),
], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
$groupEntity = new GroupEntity((array)$this->request->getVar());
$groupService = Services::groupService();
$groupService->create($groupEntity);
return $this->respond([
'data' => ''
], ResponseInterface::HTTP_CREATED, lang('Shared.api.save'));
}
/**
* update function
* #method : PUT or PATCH
*/
public function update($id = null)
{
//get request from Vue Js
//get request from Vue Js
$json = $this->request->getJSON();
if (!isset($id)) {
$id = $json->id;
}
$rules = [
'name' => 'if_exist|required|min_length[3]|max_length[255]',
'description' => 'required|min_length[3]|max_length[255]',
];
if (!$this->validate($rules)) {
return $this->respond([
'error' => $this->validator->getErrors(),
], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
$groupEntity = new GroupEntity((array)$this->request->getVar());
$groupService = Services::groupService();
$groupService->update($id, $groupEntity);
return $this->respond([
], ResponseInterface::HTTP_OK, lang('Shared.api.update'));
}
/**
* edit function
* #method : DELETE with params ID
*/
public function delete($id = null)
{
$groupService = Services::groupService();
$groupService->delete($id);
return $this->respond([
], ResponseInterface::HTTP_OK, lang('Shared.api.remove'));
}
}
entitiy
forth service
<?php namespace Modules\Auth\Config;
use CodeIgniter\HTTP\UserAgent;
use Config\App;
use Config\Services as AppServices;
use Config\Services as BaseService;
use Modules\Auth\Libraries\RequestWithUser;
use Modules\Auth\Services\AuthService;
use Modules\Auth\Services\GroupsPermissionService;
use Modules\Auth\Services\PermissionService;
use Modules\Auth\Services\RoleRouteService;
use Modules\Auth\Services\GroupService;
use Modules\Auth\Services\UsersPermissionService;
class Services extends BaseService
{
//--------------------------------------------------------------------
/**
* The Request class models an HTTP request.
*
* #param App|null $config
* #param boolean $getShared
*
* #return RequestWithUser
*/
public static function requestWithUser(App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('requestWithUser', $config);
}
$config = $config ?? config('App');;
return new RequestWithUser(
$config,
AppServices::uri(),
'php://input',
new UserAgent()
);
}
//--------------------------------------------------------------------
public static function roleRoute($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('roleRoute');
}
return new RoleRouteService();
}
//--------------------------------------------------------------------
public static function authService($getShared = false)
{
if (!$getShared) {
return new AuthService();
}
return static::getSharedInstance('authService');
}
//--------------------------------------------------------------------
public static function groupService($getShared = false)
{
if (!$getShared) {
return new GroupService();
}
return static::getSharedInstance('groupService');
}
//--------------------------------------------------------------------
public static function permissionService($getShared = false)
{
if (!$getShared) {
return new PermissionService();
}
return static::getSharedInstance('permissionService');
}
//--------------------------------------------------------------------
public static function groupsPermissionService($getShared = false)
{
if (!$getShared) {
return new GroupsPermissionService();
}
return static::getSharedInstance('groupsPermissionService');
}
//--------------------------------------------------------------------
public static function userPermissionService($getShared = false)
{
if (!$getShared) {
return new UsersPermissionService();
}
return static::getSharedInstance('usersPermissionService');
}
//--------------------------------------------------------------------
}
<?php namespace Modules\Auth\Entities;
use \CodeIgniter\Entity;
use CodeIgniter\I18n\Time;
class GroupEntity extends Entity
{
protected $id;
protected $name;
protected $description;
//check type of data
// protected $casts = ['
// is_flag' => 'boolean'];
protected $attributes = [
'id' => null,
'name' => null,
'description' => null,
];
protected $datamap = [
];
protected $dates = [];
protected $casts = [];
protected $permissions = [];
protected $roles = [];
}
model
<?php namespace Myth\Auth\Authorization;
use CodeIgniter\Model;
use Modules\Auth\Entities\GroupEntity;
use Modules\Shared\Models\Aggregation;
class GroupModel extends Aggregation
{
protected $table = 'auth_groups';
protected $primaryKey = 'id';
protected $returnType = GroupEntity::class;
protected $allowedFields = [
'name', 'description'
];
protected $useTimestamps = false;
protected $validationRules = [
'name' => 'required|max_length[255]|is_unique[auth_groups.name,name,{name}]',
'description' => 'max_length[255]',
];
protected $validationMessages = [];
protected $skipValidation = false;
//--------------------------------------------------------------------
// Users
//--------------------------------------------------------------------
/**
* Adds a single user to a single group.
*
* #param int $userId
* #param int $groupId
*
* #return bool
*/
public function addUserToGroup(int $userId, int $groupId)
{
cache()->delete("{$groupId}_users");
cache()->delete("{$userId}_groups");
cache()->delete("{$userId}_permissions");
$data = [
'user_id' => (int) $userId,
'group_id' => (int) $groupId
];
return (bool) $this->db->table('auth_groups_users')->insert($data);
}
/**
* Removes a single user from a single group.
*
* #param int $userId
* #param int|string $groupId
*
* #return bool
*/
public function removeUserFromGroup(int $userId, $groupId)
{
cache()->delete("{$groupId}_users");
cache()->delete("{$userId}_groups");
cache()->delete("{$userId}_permissions");
return $this->db->table('auth_groups_users')
->where([
'user_id' => $userId,
'group_id' => (int) $groupId
])->delete();
}
/**
* Removes a single user from all groups.
*
* #param int $userId
*
* #return bool
*/
public function removeUserFromAllGroups(int $userId)
{
cache()->delete("{$userId}_groups");
cache()->delete("{$userId}_permissions");
return $this->db->table('auth_groups_users')
->where('user_id', (int)$userId)
->delete();
}
/**
* Returns an array of all groups that a user is a member of.
*
* #param int $userId
*
* #return array
*/
public function getGroupsForUser(int $userId)
{
if (null === $found = cache("{$userId}_groups"))
{
$found = $this->builder()
->select('auth_groups_users.*, auth_groups.name, auth_groups.description')
->join('auth_groups_users', 'auth_groups_users.group_id = auth_groups.id', 'left')
->where('user_id', $userId)
->get()->getResultArray();
cache()->save("{$userId}_groups", $found, 300);
}
return $found;
}
/**
* Returns an array of all users that are members of a group.
*
* #param int $groupId
*
* #return array
*/
public function getUsersForGroup(int $groupId)
{
if (null === $found = cache("{$groupId}_users"))
{
$found = $this->builder()
->select('auth_groups_users.*, users.*')
->join('auth_groups_users', 'auth_groups_users.group_id = auth_groups.id', 'left')
->join('users', 'auth_groups_users.user_id = users.id', 'left')
->where('auth_groups.id', $groupId)
->get()->getResultArray();
cache()->save("{$groupId}_users", $found, 300);
}
return $found;
}
//--------------------------------------------------------------------
// Permissions
//--------------------------------------------------------------------
/**
* Gets all permissions for a group in a way that can be
* easily used to check against:
*
* [
* id => name,
* id => name
* ]
*
* #param int $groupId
*
* #return array
*/
public function getPermissionsForGroup(int $groupId): array
{
$permissionModel = model(PermissionModel::class);
$fromGroup = $permissionModel
->select('auth_permissions.*')
->join('auth_groups_permissions', 'auth_groups_permissions.permission_id = auth_permissions.id', 'inner')
->where('group_id', $groupId)
->findAll();
$found = [];
foreach ($fromGroup as $permission)
{
$found[$permission['id']] = $permission;
}
return $found;
}
/**
* Add a single permission to a single group, by IDs.
*
* #param int $permissionId
* #param int $groupId
*
* #return mixed
*/
public function addPermissionToGroup(int $permissionId, int $groupId)
{
$data = [
'permission_id' => (int)$permissionId,
'group_id' => (int)$groupId
];
return $this->db->table('auth_groups_permissions')->insert($data);
}
//--------------------------------------------------------------------
/**
* Removes a single permission from a single group.
*
* #param int $permissionId
* #param int $groupId
*
* #return mixed
*/
public function removePermissionFromGroup(int $permissionId, int $groupId)
{
return $this->db->table('auth_groups_permissions')
->where([
'permission_id' => $permissionId,
'group_id' => $groupId
])->delete();
}
//--------------------------------------------------------------------
/**
* Removes a single permission from all groups.
*
* #param int $permissionId
*
* #return mixed
*/
public function removePermissionFromAllGroups(int $permissionId)
{
return $this->db->table('auth_groups_permissions')
->where('permission_id', $permissionId)
->delete();
}
}

Related

The route I made suddenly added the "um"

I am making a resource controller. Here's my code.
api.php:
Route::group([ 'prefix' => 'admin', 'namespace' => 'Admin'], function () {
Route::resource('penyedia', 'PenyediaController');
});
Following is the contents of the controller PenyediaController.php:
<?php
namespace App\Http\Controllers\Admin;
use App\Exceptions\InvalidRouteException;
use App\Http\Requests\ValidatePenyedia;
use App\Http\Requests\ValidateList;
use App\Models\Penyedia;
use App\Http\Controllers\Controller;
class PenyediaController extends Controller
{
/**
* Penyedia model.
*
* #var Penyedia
*/
private $penyedia;
/**
* PenyediaController constructor.
*
* #param Penyedia $penyedia
*/
public function __construct(Penyedia $penyedia)
{
$this->penyedia = $penyedia;
}
/**
* Display a listing of the Penyedia.
*
* #param ValidateList $request
* #return \Illuminate\Http\Response
*/
public function index(ValidateList $request)
{
$validated = $request->validated();
$filter = array_key_exists('filter', $validated) ? $validated['filter'] : [];
$keyword = array_key_exists('keyword', $validated) ? $validated['keyword'] : null;
$datatable = array_key_exists('per_page', $validated) ?
$this->penyedia->datatable($filter, $keyword)->paginate($validated['per_page'])
:
$this->penyedia->datatable($filter, $keyword)->get();
return response()->json([
'error' => false,
'data' => $datatable
]);
}
/**
* Show the form for creating a new Penyedia.
*
* #return void
* #throws InvalidRouteException
*/
public function create()
{
throw new InvalidRouteException();
}
/**
* Store a newly created Penyedia in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ValidatePenyedia $request)
{
$validated = $request->validated();
$this->penyedia = $this->penyedia->create($this->penyedia->prepareData($validated));
return response()->json([
'error' => false,
'data' => $this->penyedia->output()
]);
}
/**
* Display the specified Penyedia.
*
* #param int $id
* #return void
* #throws InvalidRouteException
*/
public function show(Penyedia $penyedia)
{
//dd('z');
dd($penyedia->nama);
throw new InvalidRouteException();
}
/**
* Show the form for editing the specified Penyedia.
*
* #param int $id
* #return void
* #throws InvalidRouteException
*/
public function edit($id)
{
throw new InvalidRouteException();
}
/**
* Update the specified Penyedia in storage.
*
* #param ValidatePenyedia $request
* #param Penyedia $penyedia
* #return \Illuminate\Http\Response
*/
public function update(Penyedia $penyedia)
{
dd($penyedia->id);
//dd("z");
$validated = $request->validated();
//dd("hehe");
dd($penyedia);
$penyedia->update($this->penyedia->prepareData($validated));
dd($this->penyedia->prepareData($validated));
return response()->json([
'error' => false,
'data' => $penyedia->output()
]);
}
/**
* Remove the specified Penyedia from storage.
*
* #param Penyedia $penyedia
* #return \Illuminate\Http\Response
* #throws \Exception
*/
public function destroy(Penyedia $penyedia)
{
$penyedia->delete();
return response()->json([
'error' => false,
'data' => $penyedia->output()
]);
}
}
This is the contents of Penyedia.php:
<?php
namespace App\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Penyedia extends Model
{
use SoftDeletes;
protected $table = 'penyedia';
protected $fillable = [
'nama', 'penanggung_jawab', 'deskripsi', 'category', 'user_id', 'kontak'
];
protected $dates = ['deleted_at'];
/**
* Relation to User.
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function scopeDatatable($query, $filters = [], $keyword = null){
// dd("sampesini");
foreach ($filters as $filter) {
$query->orderBy($filter['field'], $filter ['order']);
}
if ($keyword) {
$query->where('nama', 'LIKE', '%' . $keyword . '%')
->orWhere('deskripsi', 'LIKE', '%' . $keyword . '%')
->orWhere('penanggung_jawab', 'LIKE', '%' . $keyword . '%')
->orWhere('kontak', 'LIKE', '%' . $keyword . '%');
}
//return $query->select('id', 'nama');
return $query->with(['user:id,name'])->select('id', 'nama', 'penanggung_jawab', 'deskripsi', 'category', 'user_id', 'kontak');
}
public function prepareData($data)
{
return [
'nama' => $data['nama'] ? $data['nama'] : '',
'penanggung_jawab' => isset($data['penanggung_jawab']) ? $data['penanggung_jawab'] : '',
'deskripsi' => isset($data['deskripsi']) ? $data['deskripsi'] : '',
'category' => isset($data['category']) ? $data['category'] : '',
'user_id' => isset($data['user_id']) ? $data['user_id'] : '',
'kontak' => isset($data['kontak']) ? $data['kontak'] : '',
];
}
public function output()
{
return $this->with(['user:id,name'])->select('id', 'nama', 'penanggung_jawab', 'deskripsi', 'category', 'user_id', 'kontak')->first();
}
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Relation to Beasiswa.
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function beasiswa()
{
return $this->hasMany(Beasiswa::class);
}
}
Then when I open cmd then I type php artisan route: list
suddenly there was an addition of 'um' to the router's parameters. How can it be like that ? Here's the screenshot:
https://i.imgur.com/kZLUiGm.png
I found solution, I just edit my route like this :
Route::resource('penyedia', 'PenyediaController', [
'parameters' => ['penyedia' => 'penyedia']
]);
And my parameter is back to 'penyedia'

laravel controller new method global variable

I want to make an instance of my model in my controller and use it every where i need
I use this code:
public $test = new Access();
but the is this error that i cant figure it out why i kept getting this error:
expression is not allowed as field default value
and this is my controller code down here:
<?php
namespace App\Http\Controllers;
use App\Models\Access;
use Illuminate\Http\Request;
classAccessController extends Controller{
private $table = 'accesses';
public $test = new Access();
/**
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index()
{
$table = $this->table;
$accesses = (new Access())->index($table);
return view('index', compact('accesses'));
}
/**
* #param Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(Request $request)
{
$access = new Access();
$request->validate([
'can_select' => 'required|boolean',
'can_delete' => 'required|boolean',
'can_edit' => 'required|boolean',
'can_insert' => 'required|boolean',
'role_id' => 'required|integer|max:2',
'module_id' => 'required|integer|max:3',
]);
$access->can_select = $request->get('can_select');
$access->can_delete = $request->get('can_delete');
$access->can_edit = $request->get('can_edit');
$access->can_insert = $request->get('can_insert');
$access->role_id = $request->get('role_id');
$access->module_id = $request->get('module_id');
$attributes = array('can_select', 'can_delete', 'can_edit', 'can_insert', 'role_id', 'module_id');
$options = array($access->can_select, $access->can_delete, $access->can_edit, $access->can_insert, $access->role_id, $access->module_id);
$table = $this->table;
(new Access())->store($table, $attributes, $options);
return redirect('accesses')->with('success', 'Information has been inserted');
}
/**
* #param $id
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function edit($id)
{
$access = Access::find($id);
return view('update', compact('access', 'id'));
}
/**
* #param Request $request
* #param $id
* #return \Illuminate\Http\RedirectResponse
*/
public function update(Request $request, $id)
{
$access = Access::find($id);
$request->validate([
'can_select' => 'required|boolean',
'can_delete' => 'required|boolean',
'can_edit' => 'required|boolean',
'can_insert' => 'required|boolean',
'role_id' => 'required|integer|max:2',
'module_id' => 'required|integer|max:3',
]);
$access->can_select = $request->get('can_select');
$access->can_delete = $request->get('can_delete');
$access->can_edit = $request->get('can_edit');
$access->can_insert = $request->get('can_insert');
$access->role_id = $request->get('role_id');
$access->module_id = $request->get('module_id');
$attributes = array('can_select', 'can_delete', 'can_edit', 'can_insert', 'role_id', 'module_id');
$options = array($access->can_select, $access->can_delete, $access->can_edit, $access->can_insert, $access->role_id, $access->module_id);
$object = $access;
$table = $this->table;
(new Access())->updates($table, $object, $attributes, $options);
return redirect('accesses')->with('success', 'Information has been updated successfully!!');
}
/**
* #param $id
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy($id)
{
$access = Access::find($id);
$object = $access;
$table = $this->table;
(new Access())->erase($table, $object);
return redirect('accesses')->with('success', 'Information has been deleted');
}
}
i first thought it is the security problem but in my idea it is irrelevent in my idea
I don't understand your use case but.. you can use the contructor of the class to do so:
class ACoolController extends Controller {
protected $access;
/**
* ACoolController constructor.
*
*/
public function __construct()
{
$this->access = new Access();
}
public function aCoolFunction()
{
// do something with your variable
$this->access->someMethodOfYourModel();
}
}
Of-course you can't in PHP you cannot call a method to instantiate a class member even if it is a static method either initialize it in the constructor
class AccessController extends Controller{
public $test ;
public function __construct()
{
$this->test= new Access();
}
}
Or much better use the dependency injection pattern ( Container ) in Laravel to avoid creating multiple instances of the Access Model see the docs : https://laravel.com/docs/5.7/container

Laravel 5.2 Error In Custom Authentication

I am getting error while making custom authentication for my laravel 5.2 however this code works fine on my laravel 5.1 My config/auth.php file
'providers' => [
'users' => [
'driver' => 'custom',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
My CustomUserProvider.php (Auth/CustomUserProvider) file
<?php namespace App\Auth;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
class CustomUserProvider implements UserProvider {
protected $model;
public function __construct(UserContract $model)
{
$this->model = $model;
}
public function retrieveById($identifier)
{
}
public function retrieveByToken($identifier, $token)
{
}
public function updateRememberToken(UserContract $user, $token)
{
}
public function retrieveByCredentials(array $credentials)
{
}
public function validateCredentials(UserContract $user, array $credentials)
{
}
}
My CustomAuthProvider.php file
<?php namespace App\Providers;
use App\User;
use Auth;
use App\Auth\CustomUserProvider;
use Illuminate\Support\ServiceProvider;
class CustomAuthProvider extends ServiceProvider {
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
$this->app['auth']->extend('custom',function()
{
return new CustomUserProvider();
});
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}
Now this works fine in laravel 5.1 in 5.2 i am getting error like
InvalidArgumentException in CreatesUserProviders.php line 40:
Authentication user provider [custom] is not defined.
The only point is to use
$this->app['auth']->provider(...
instead of
$this->app['auth']->extend(...
The last one is used in 5.1, the first one should be used in 5.2.
app/Models/User.php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable {
protected $connection='conn';
protected $table='users-custom';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'login', 'passwd'
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'passwd',
];
public function getAuthPassword(){
//your passwor field name
return $this->passwd;
}
public $timestamps = false;
}
create app/Auth/CustomUserProvider.php
namespace App\Auth;
use Illuminate\Support\Str;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Contracts\Auth\UserProvider;
/**
* Description of CustomUserProvider
*
*/
class CustomUserProvider implements UserProvider {
/**
* The hasher implementation.
*
* #var \Illuminate\Contracts\Hashing\Hasher
*/
protected $hasher;
/**
* The Eloquent user model.
*
* #var string
*/
protected $model;
/**
* Create a new database user provider.
*
* #param \Illuminate\Contracts\Hashing\Hasher $hasher
* #param string $model class name of model
* #return void
*/
public function __construct($model) {
$this->model = $model;
}
/**
* Retrieve a user by their unique identifier.
*
* #param mixed $identifier
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveById($identifier) {
return $this->createModel()->newQuery()->find($identifier);
}
/**
* Retrieve a user by their unique identifier and "remember me" token.
*
* #param mixed $identifier
* #param string $token
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByToken($identifier, $token) {
$model = $this->createModel();
return $model->newQuery()
->where($model->getAuthIdentifierName(), $identifier)
->where($model->getRememberTokenName(), $token)
->first();
}
/**
* Update the "remember me" token for the given user in storage.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param string $token
* #return void
*/
public function updateRememberToken(UserContract $user, $token) {
$user->setRememberToken($token);
$user->save();
}
/**
* Retrieve a user by the given credentials.
*
* #param array $credentials
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials) {
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if (!Str::contains($key, 'password')) {
$query->where($key, $value);
}
}
return $query->first();
}
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
* #return bool
*/
public function validateCredentials(UserContract $user, array $credentials) {
//your method auth
$plain = $credentials['password'];
return md5($plain)==md5($user->getAuthPassword());
}
/**
* Create a new instance of the model.
*
* #return \Illuminate\Database\Eloquent\Model
*/
public function createModel() {
$class = '\\' . ltrim($this->model, '\\');
return new $class;
}
/**
* Gets the hasher implementation.
*
* #return \Illuminate\Contracts\Hashing\Hasher
*/
public function getHasher() {
return $this->hasher;
}
/**
* Sets the hasher implementation.
*
* #param \Illuminate\Contracts\Hashing\Hasher $hasher
* #return $this
*/
public function setHasher(HasherContract $hasher) {
$this->hasher = $hasher;
return $this;
}
/**
* Gets the name of the Eloquent user model.
*
* #return string
*/
public function getModel() {
return $this->model;
}
/**
* Sets the name of the Eloquent user model.
*
* #param string $model
* #return $this
*/
public function setModel($model) {
$this->model = $model;
return $this;
}
}
in config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users_office',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'users_office' => [
'driver' => 'customUser',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
in \vendor\laravel\framework\src\Illuminate\AuthCreatesUserProviders.php
public function createUserProvider($provider)
{
$config = $this->app['config']['auth.providers.'.$provider];
if (isset($this->customProviderCreators[$config['driver']])) {
return call_user_func(
$this->customProviderCreators[$config['driver']], $this->app, $config
);
}
switch ($config['driver']) {
case 'database':
return $this->createDatabaseProvider($config);
case 'eloquent':
return $this->createEloquentProvider($config);
case 'customUser':
return $this->createCustomUserProvider($config);
default:
throw new InvalidArgumentException("Authentication user provider [{$config['driver']}] is not defined.");
}
}
protected function createCustomUserProvider($config){
return new \App\Auth\CustomUserProvider($config['model']);
}
add App\Providers\CustomUserAuthProvider.php
namespace App\Providers;
use Auth;
use App\Models\User;
use App\Auth\CustomUserProvider;
use Illuminate\Support\ServiceProvider;
/**
* Description of CustomAuthProvider
*
*/
class CustomUserAuthProvider extends ServiceProvider {
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
Auth::extend('customUser', function($app) {
// Return an instance of Illuminate\Contracts\Auth\UserProvider...
return new CustomUserProvider(new User);
});
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}
Try by replacing the boot function as below:
public function boot()
{
Auth::provider('custom', function($app, array $config) {
// Return an instance of Illuminate\Contracts\Auth\UserProvider...
return new CustomUserProvider($app['custom.connection']);
});
}
Replace the boot function as below:
public function boot()
{
Auth::provider('customUser', function($app, array $config) {
return new CustomUserProvider($config['model']);
});
}

I keep getting this error SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'videos_slug_unique'what do I do to fix it

I have a site I created that has a blog section and a video section. I had a config file for blog that I tried to share with the video section but it wasn't working properly so I created a separate config for video. and modified my column names for video from
$title and $subtitle
to
$v_title and $v_subtitle.
but when I do I get the following error
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'videos_slug_unique'
for some reason a slug is not being produced and this causes the issue. The slug is unique in my table. If I change the variables to how they were
$title and $subtitle
it works, why is that?
this is my Admin videoController
<?php
namespace App\Http\Controllers\Admin;
use App\Jobs\VideoFormFields;
use App\Http\Requests;
use App\Http\Requests\VideoCreateRequest;
use App\Http\Requests\VideoUpdateRequest;
use App\Http\Controllers\Controller;
use App\Video;
class VideoController extends Controller
{
/**
* Display a listing of the posts.
*/
public function index()
{
return view('admin.video.index')
->withVideos(Video::all());
}
/**
* Show the new video form
*/
public function create()
{
$data = $this->dispatch(new VideoFormFields());
return view('admin.video.create', $data);
}
/**
* Store a newly created Video
*
* #param VideoCreateRequest $request
*/
public function store(VideoCreateRequest $request)
{
$video = Video::create($request->videoFillData());
$video->syncTags($request->get('tags', []));
return redirect()
->route('admin.video.index')
->withSuccess('New Video Successfully Created.');
}
/**
* Show the video edit form
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$data = $this->dispatch(new VideoFormFields($id));
return view('admin.video.edit', $data);
}
/**
* Update the Video
*
* #param VideoUpdateRequest $request
* #param int $id
*/
public function update(VideoUpdateRequest $request, $id)
{
$video = Video::findOrFail($id);
$video->fill($request->videoFillData());
$video->save();
$video->syncTags($request->get('tags', []));
if ($request->action === 'continue') {
return redirect()
->back()
->withSuccess('Video saved.');
}
return redirect()
->route('admin.video.index')
->withSuccess('Video saved.');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$video = Video::findOrFail($id);
$video->tags()->detach();
$video->delete();
return redirect()
->route('admin.video.index')
->withSuccess('Video deleted.');
}
}
this is my videoFormFields
<?php
namespace App\Jobs;
use App\Video;
use App\Tag;
use Carbon\Carbon;
use Illuminate\Contracts\Bus\SelfHandling;
class VideoFormFields extends Job implements SelfHandling
{
/**
* The id (if any) of the Post row
*
* #var integer
*/
protected $id;
/**
* List of fields and default value for each field
*
* #var array
*/
protected $fieldList = [
'v_title' => '',
'v_subtitle' => '',
'page_image' => '',
'content' => '',
'meta_description' => '',
'is_draft' => "0",
'publish_date' => '',
'publish_time' => '',
'layout' => 'video.layouts.v_post',
'tags' => [],
];
/**
* Create a new command instance.
*
* #param integer $id
*/
public function __construct($id = null)
{
$this->id = $id;
}
/**
* Execute the command.
*
* #return array of fieldnames => values
*/
public function handle()
{
$fields = $this->fieldList;
if ($this->id) {
$fields = $this->fieldsFromModel($this->id, $fields);
} else {
$when = Carbon::now()->addHour();
$fields['publish_date'] = $when->format('M-j-Y');
$fields['publish_time'] = $when->format('g:i A');
}
foreach ($fields as $fieldName => $fieldValue) {
$fields[$fieldName] = old($fieldName, $fieldValue);
}
return array_merge(
$fields,
['allTags' => Tag::lists('tag')->all()]
);
}
/**
* Return the field values from the model
*
* #param integer $id
* #param array $fields
* #return array
*/
protected function fieldsFromModel($id, array $fields)
{
$video = Video::findOrFail($id);
$fieldNames = array_keys(array_except($fields, ['tags']));
$fields = ['id' => $id];
foreach ($fieldNames as $field) {
$fields[$field] = $video->{$field};
}
$fields['tags'] = $video->tags()->lists('tag')->all();
return $fields;
}
}
this is my videoCreateRequest
<?php
namespace App\Http\Requests;
use Carbon\Carbon;
class VideoCreateRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'v_title' => 'required',
'v_subtitle' => 'required',
'content_raw' => 'required', // HERE CHANGED
'publish_date' => 'required',
'publish_time' => 'required',
'layout' => 'required',
];
}
/**
* Return the fields and values to create a new VIDEO post from
*/
public function videoFillData()
{
$published_at = new Carbon(
$this->publish_date.' '.$this->publish_time
);
return [
'v_title' => $this->v_title,
'v_subtitle' => $this->v_subtitle,
'page_image' => $this->page_image,
'content_raw' => $this->content_raw, // HERE CHANGED
'meta_description' => $this->meta_description,
'is_draft' => (bool)$this->is_draft,
'published_at' => $published_at,
'layout' => $this->layout,
];
}
}
this is my videoUpdateRequest
class VideoUpdateRequest extends VideoCreateRequest
{
//
}
this is my video model
<?php
namespace App;
use App\Services\Markdowner;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use Sofa\Eloquence\Eloquence;
class Video extends Model
{
use Eloquence;
protected $dates = ['published_at'];
protected $fillable = [
'v_title', 'v_subtitle', 'content_raw', 'page_image', 'meta_description',
'layout', 'is_draft', 'published_at',
];
/**
* The many-to-many relationship between posts and tags.
*
* #return BelongsToMany
*/
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
/**
* Set the title attribute and automatically the slug
*
* #param string $value
*/
public function setTitleAttribute($value)
{
$this->attributes['title'] = $value;
if (! $this->exists) {
$this->setUniqueSlug($value, '');
}
}
/**
* Recursive routine to set a unique slug
*
* #param string $title
* #param mixed $extra
*/
protected function setUniqueSlug($title, $extra)
{
$slug = str_slug($title.'-'.$extra);
if (static::whereSlug($slug)->exists()) {
$this->setUniqueSlug($title, $extra + 1);
return;
}
$this->attributes['slug'] = $slug;
}
/**
* Set the HTML content automatically when the raw content is set
*
* #param string $value
*/
public function setContentRawAttribute($value)
{
$markdown = new Markdowner();
$this->attributes['content_raw'] = $value;
$this->attributes['content_html'] = $markdown->toHTML($value);
}
/**
* Sync tag relation adding new tags as needed
*
* #param array $tags
*/
public function syncTags(array $tags)
{
Tag::addNeededTags($tags);
if (count($tags)) {
$this->tags()->sync(
Tag::whereIn('tag', $tags)->lists('id')->all()
);
return;
}
$this->tags()->detach();
}
/**
* Return the date portion of published_at
*/
public function getPublishDateAttribute($value)
{
return $this->published_at->format('M-j-Y');
}
/**
* Return the time portion of published_at
*/
public function getPublishTimeAttribute($value)
{
return $this->published_at->format('g:i A');
}
/**
* Alias for content_raw
*/
public function getContentAttribute($value)
{
return $this->content_raw;
}
/**
* Return URL to post
*
* #param Tag $tag
* #return string
*/
public function url(Tag $tag = null)
{
$url = url('video/'.$this->slug); // this fixed my problem it was 'blog/'
if ($tag) {
$url .= '?tag='.urlencode($tag->tag);
}
return $url;
}
/**
* Return array of tag links
*
* #param string $base
* #return array
*/
public function tagLinks($base = '/video?tag=%TAG%') // this fixed my problem it was 'blog?tag=%TAG%/'
{
$tags = $this->tags()->lists('tag');
$return = [];
foreach ($tags as $tag) {
$url = str_replace('%TAG%', urlencode($tag), $base);
$return[] = ''.e($tag).'';
}
return $return;
}
/**
* Return next post after this one or null
*
* #param Tag $tag
* #return Post
*/
public function newerPost(Tag $tag = null) // //here newVideo v_index & v_post
{
$query =
static::where('published_at', '>', $this->published_at)
->where('published_at', '<=', Carbon::now())
->where('is_draft', 0)
->orderBy('published_at', 'asc');
if ($tag) {
$query = $query->whereHas('tags', function ($q) use ($tag) {
$q->where('tag', '=', $tag->tag);
});
}
return $query->first();
}
/**
* Return older post before this one or null
*
* #param Tag $tag
* #return Post
*/
public function olderPost(Tag $tag = null) // //here olderVideo v_index & v_post
{
$query =
static::where('published_at', '<', $this->published_at)
->where('is_draft', 0)
->orderBy('published_at', 'desc');
if ($tag) {
$query = $query->whereHas('tags', function ($q) use ($tag) {
$q->where('tag', '=', $tag->tag);
});
}
return $query->first();
}
}
this is my video table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateVideosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string('slug')->unique();
$table->string('v_title');
$table->string('v_subtitle');
$table->text('content_raw');
$table->text('content_html');
$table->string('page_image');
$table->string('meta_description');
$table->boolean('is_draft');
$table->string('layout')
->default('blog.layouts.post');
$table->timestamps();
$table->timestamp('published_at')->index();
});
}
/**
* Reverse the migrations.
*/
public function down()
{
Schema::drop('videos');
}
}
After you changed the column names, your dynamic setters setTitleAttribute and setSubtitleAttribute are not called and the slug does not get updated. You need to change the names of setter methods as well.
public function setVTitleAttribute($value) {
...
}
public function setVSubtitleAttribute($value) {
...
}
it seems you did not refactor title to v_title in the whole class. For example, you should change
public function setTitleAttribute($value)
{
$this->attributes['title'] = $value;
if (! $this->exists) {
$this->setUniqueSlug($value, '');
}
}
to
public function setVTitleAttribute($value)
{
$this->attributes['v_title'] = $value;
if (! $this->exists) {
$this->setUniqueSlug($value, '');
}
}

Yii 2.0 login from database not working

Right i am working on yii 2.0 trying to amend the login system. It works when the users are just a hand coded array. Instead i want to make this work from a database.
I will show you what the initial Model looks like:
<?php
namespace app\models;
class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
private static $users = [
'100' => [
'id' => '100',
'username' => 'admin',
'password' => 'admin',
'authKey' => 'test100key',
'accessToken' => '100-token',
],
'101' => [
'id' => '101',
'username' => 'demo',
'password' => 'demo',
'authKey' => 'test101key',
'accessToken' => '101-token',
],
];
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
okay so as you can see it is working on the hand coded array called $users. So i have made a table called "Users" and made the columns id username password authkey and accessToken.
Hoping that it would do the same thing with a database table, however i am getting an error when i try to log in. This is my new code
<?php
namespace app\models;
/**
* This is the model class for table "Cases".
*
* #property integer $id
* #property string $username
* #property string $password
* #property string $authkey
* #property string $accessToken
*/
class User extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'users';
}
public function rules()
{
return [
[['id','username','password','authkey','accessToken'], 'required'],
[['id'], 'integer'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'id',
'username' => 'username',
'password' => 'password',
'authkey' => 'authkey',
'accessToken' => 'accessToken',
];
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$Users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
The error message i am getting when i try to log in is "Access to undeclared static property: app\models\User::$Users".
If you need to see my LoginForm Model and Controller action i will post them underneath here.
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
and LoginForm model is:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* LoginForm is the model behind the login form.
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* #return array the validation rules.
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* #param string $attribute the attribute currently being validated
* #param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
* #return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}
Can any one advise what i should do , once again the error i get is:
Access to undeclared static property: app\models\User::$Users
and this error corresponds to this section of code
foreach (self::$Users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
In your new User class change this methods:
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
See more in Yii2 Advanced template - https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php#L61
Or take this class(from Yii2 Advanced template) in your app.
Use one Object for User Model instead your three different objects.
class User extends ActiveRecord implements IdentityInterface
{
const LOGIN_SCENARIO = 'login';
const CREATE_SCENARIO = 'create';
const UPDATE_SCENARIO = 'update';
/**
* Table name
*
* #return string
*/
public static function tableName()
{
return 'user';
}
/**
* Primary key
*/
public static function primaryKey()
{
return ['id'];
}
/**
* Set attribute labels
*
* #return array
*/
public function attributeLabels()
{
return [
'login' => Yii::t('app', 'Login'),
'password' => Yii::t('app', 'Password')
];
}
/**
* Rules
*
* #return array
*/
public function rules()
{
return [
[
[
'login',
'password'
],
'required',
'on' => self::LOGIN_SCENARIO
],
[
'password',
'validatePassword',
'on' => self::LOGIN_SCENARIO
],
[
[
'role',
'login',
'confirm',
'password',
],
'required',
'on' => self::CREATE_SCENARIO
],
[
[
'role',
'login',
],
'required',
'on' => self::UPDATE_SCENARIO
],
[
[
'name',
'status',
'password',
'create_dt',
'update_dt'
],
'safe',
],
];
}
/**
* Password validation
*/
public function validatePassword($attribute)
{
// Validate pass
}
/**
* #param null $id
*
* #return bool|mixed
*/
public function saveUser($id = null)
{
/** #var self $user */
$user = $this->findIdentity($id) ? $this->findIdentity($id) : $this;
$user->setScenario($this->scenario);
// Make Save
}
/**
* #param $id
*
* #throws \Exception
*/
public function deleteUser($id)
{
/** #var self $user */
if($user = $this->findIdentity($id)) {
// Make Delete
}
}
/**
* Finds an identity by the given ID.
*
* #param string|integer $id the ID to be looked for
*
* #return IdentityInterface the identity object that matches the given ID.
* Null should be returned if such an identity cannot be found
* or the identity is not in an active state (disabled, deleted, etc.)
*/
public static function findIdentity($id)
{
return static::findOne($id);
}
/**
* Returns an ID that can uniquely identify a user identity.
* #return string|integer an ID that uniquely identifies a user identity.
*/
public function getId()
{
return $this->getPrimaryKey();
}
}
And one User Model working with users, with different scenarios, can create, delete, make login etc.
And at html, for login form, put code like this:
<?php $model = new namespace\User() ?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'login') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
And for login, in controller, put code like this:
/**
* Login action
*
* #return mixed
*/
public function actionLogin()
{
$user = new namespace\User();
$user->setScenario(namespace\User::LOGIN_SCENARIO);
$user->load(Yii::$app->request->post());
if($user->validate()) {
// Make Login
return true;
}
return false;
}

Categories