private member attribute is not working CI - codeigniter

Here is my model class
class Sessions_model extends CI_Model
{
private $permission = array()
public function __construct()
{
parent::__construct();
}
public function is_login()
{
if($this->session->userdata('logged_in')) return TRUE;
else return false;
}
public function login($username,$password)
{
$this->db->where('username',$username);
$this->db->where('password',$password);
$query = $this->db->get('users');
if($query->num_rows()==1){
$user = $query->row();
$this->set_authnication($user->id);
return TRUE;
}
}
public function logout()
{
$this->session->sess_destroy();
}
public function set_authnication($user_id)
{
$this->load->helper('date');
$query = $this->db->where('id',$user_id)->get('users');
$user = $query->row();
$auth_data = array(
'user_id' => $user_id,
'logged_in' => 1,
'name' => $user->name,
'username'=> $user->username,
'email' => $user->email,
'role' => $this->initRole($user_id),
'lastVisitDate'=> now()
);
$this->session->set_userdata($auth_data);
}
public function initRole($id)
{
$role_perm = array();
$role = $this->db->where('id',$id)->get('roles')->row();
return $role_perm= array(
$role->description => $this->getPerm($role->id)
);
}
public function getPerm($id)
{
$perms = $this->db->where('role_id',$id)->get('permissions')->result();
foreach ($perms as $perm) {
$this->permissions[$perm->permission] = true;
}
return $this->permissions;
}
public function hasPermTo()
{
// $this->getPerm('1');
// return (isset($permissions[$perm]))? 'true' : 'false';
// print_r($this->session->userdata('role'));
print_r($this->permissions);
}
}
when i loggin username and password is set and call set_authnication($user_id).When this login method completed i've got Role with permissions.i set my private attribute with associate permission ..all things seem ok so far
My prob when user who is authnicated come i try to validate that this user has permission to the that class ,so i call function
$this->sessions_model->hasPermTo();
but this time my private attribute is empty array() .. it have nth ...
i dont' what the problem is ?

Your private variable is permission but you're settings permissions (note the S at the end).

Related

Testing BelongsToMany relationship with pivot table

I'm trying to figure out how to create all the data based on this relationship testing in Laravel.
Company Model
class Company
{
public function stores()
{
return $this->hasMany(Store::class, 'company_id');
}
public function employers()
{
return $this->belongsToMany(User::class, 'employers',
'company_id', 'user_id');
}
}
Store Model
class Store
{
public function company()
{
return $this->belongsTo(Company::class, 'company_id');
}
public function employers()
{
return $this->belongsToMany(User::class, 'employers',
'store_id', 'user_id');
}
}
User Model
class User
{
public function company()
{
return $this->belongsToMany(Company::class, 'employers',
'user_id', 'company_id');
}
public function store()
{
return $this->belongsToMany(Store::class, 'employers',
'user_id', 'store_id');
}
}
$company = Company::factory()->hasStores(
Store::factory()->hasEmployers(User::factory())
)->create();
dd($company) // App\Models\Company {#2470... Ok!
$store = $company->store()->first();
dd($store) // App\Models\Store {#2479... Ok!
$user = $store->employers()->first();
dd($user) // null (T-T)
Background: this is an application that allows a proprietor to own several companies. For that reason, I got many relationships, and even so, employees sometimes can only belong to a single company or store.
Try:
$store = $company->store->first();
dump($store);
$user = $store->employers->first();
dump($user);
Try something like this with DB Facade
private $employ;
public function setUp(): void
{
$this->employ = Employ::factory()->create([
'id' => 14,
'name' => 'Name Employ'
]);
}
public function test_pivote_table()
{
$user = User::factory()->create([
'name' => 'User test'
);
//here :)
DB::table('name_pivote_table')->insert([
'user_id' => $user->id,
'employ_id' => $this->employ->id
]);
}
Credits to Fguzman :)

How can I test a store function with Laravel and Mockery

I want to test a repository pattern in Laravel 5.6 using PHPUnit and Mockery.
This is my code:
// PackageControllerTest.php
namespace Tests\Feature;
use Tests\TestCase;
use App\Contracts\PackageInterface;
use App\Http\Controllers\PackageController;
use Illuminate\Database\Eloquent\Collection;
class PackageControllerTest extends TestCase
{
protected $mock;
protected $target;
public function setUp()
{
parent::setUp();
parent::initDatabase();
$this->mock = $this->initMock(PackageInterface::class);
$this->target = $this->app->make(PackageController::class);
}
public function testIndex()
{
$expected = new Collection([
['name' => 'Name 1', 'html_url' => 'HTML URL 1'],
['name' => 'Name 2', 'html_url' => 'HTML URL 2'],
['name' => 'Name 3', 'html_url' => 'HTML URL 3'],
]);
$this->mock
->shouldReceive('getAllPackages')
->once()
->andReturn($expected);
$actual = $this->target->index()->packages;
$this->assertEquals($expected, $actual);
}
public function testUpdate()
{
//
}
public function tearDown()
{
parent::resetDatabase();
$this->mock = null;
$this->target = null;
}
}
// PackageControllerTest.php
...
public function index()
{
$packages = $this->package->getAllPackages();
return view('package.index', compact('packages'));
}
public function update($package_id)
{
$package = $this->package->updatePackage($package_id);
return redirect()->back();
}
// PackageRepository.php
...
public function getAllPackages()
{
$packages = $this->package->all();
return $packages;
}
public function updatePackage($package_id)
{
$package = $this->package->find($package_id);
$package->description = $this->request->description;
$package->save();
return $package;
}
The part of "testIndex()" works.
But next, I want to test the part of "testUpdate()".
How can I do?
Please help, thanks.
like this
$this->mock
->shouldReceive('updatePackage')
->with(1)
->once()
->andReturn($expected);
$actual = $this->target->update(1);
$this->assertRedirect('edit page url');
or
use DatabaseTransactions in top of class
$id = DB::table('your_table')->insertGetId(['description' => 'old'])
request()->set('description', 'test');
$actual = $this->target->update(id);
$this->assertDatabaseHas('your_table', [
'id' => $id,
'description' => 'test'
]);

BelongsTo relationship returns null when using relation name "user"

When creating a simple one-to-one relationship in Laravel 5.5, $person->user is returning a null value whenever I use the method/relation name user. If I change the name to foo, User, or login the code seems to work fine. This is the second project I've had this same issue on. Can anyone see what I'm doing wrong?
In Person model:
public function user() {
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function foo() {
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function getUser() {
if ($this->user_id) {
return User::find($this->user_id);
} else {
return null;
}
}
In PersonTest:
$user = factory(User::class)->create();
$person = factory(Person::class)->create(['user_id' => $user->id]);
// This works
$this->assertTrue( $person->getUser()->is($user) );
// This works
$this->assertTrue( !is_null($person->foo) );
if ( $person->foo ) {
$this->assertTrue( $person->foo->is($user) );
}
// This fails
$this->assertTrue( !is_null($person->user) );
if ( $person->user ) {
$this->assertTrue( $person->user->is($user) );
}
By request, here is all of the code relating to Person,
Entire App\Models\Person.php:
use App\Models\User;
use App\Models\Asset;
use App\Traits\HasGuid;
use App\Traits\HasNotes;
use App\Traits\HasModifiedBy;
use App\Traits\HasAttachments;
use App\Traits\HasRelationships;
use App\Transformers\PersonTransformer;
use App\Models\Abstracts\HasTypeModelAbstract;
use App\Models\Interfaces\HasTypeModelInterface;
class Person extends HasTypeModelAbstract implements HasTypeModelInterface {
use HasModifiedBy,
HasNotes,
HasAttachments,
HasRelationships;
protected $fillable = [
'person_type_id',
'email',
'fname',
'lname',
'user_id',
'modified_by_user_id',
'audited_at',
'custom_attributes'
];
protected $casts = [
'custom_attributes' => 'json',
'user_id' => 'integer',
'modified_by_user_id' => 'integer',
'person_type_id' => 'integer'
];
protected $dates = [
'audited_at'
];
public static $transformer = PersonTransformer::class;
public function user() {
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function type() {
return $this->belongsTo(PersonType::class, 'person_type_id');
}
public function assets() {
return $this->hasMany(Asset::class, 'person_id');
}
Traits:
trait HasNotes {
protected static function bootHasNotes() {
static::deleting(function ($instance) {
$instance->notes->each(function ($note) {
$note->delete();
});
});
}
public function notes() {
return $this->morphMany(Note::class, 'notable');
}
}
trait HasModifiedBy {
protected static function bootHasModifiedBy() {
static::saving(function ($instance) {
$instance->modified_by_user_id = Auth::id();
});
}
public function modifiedBy() {
return $this->belongsTo(User::class, 'modified_by_user_id');
}
}
trait HasAttachments {
protected static function bootHasAttachments() {
static::deleting(function ($instance) {
$instance->attachments->each(function ($attachment) {
$attachment->delete();
});
});
}
public function attachments() {
return $this->morphMany(Attachment::class, 'attachable');
}
}
trait HasRelationships {
protected static function bootHasRelationships()
{
static::deleting(function ($instance) {
Relation::forObject( $instance )->delete();
});
}
public function related() { ...[long polymorphic relationship here]... }
/App/Models/Abstracts/HasTypeModelAbstract
use Illuminate\Database\Eloquent\Model;
// This thing just appends some custom attributes dynamically in the JSON and array forms. And no, 'user' is not a custom attribute key.
abstract class HasTypeModelAbstract extends Model {
public function newFromBuilder($attributes = array(), $connection = NULL) {
$instance = parent::newFromBuilder($attributes);
$instance->appendCustomAttributes();
return $instance;
}
protected function appendCustomAttributes() {
$this->append( $this->getCustomAttributesFromType() );
}
public function getCustomAttributesFromType() {
if ($this->type) {
return $this->type->custom_attributes ?
array_keys((array) $this->type->custom_attributes) : [];
} else {
return [];
}
}
protected function setCustomAttributesFromType($attributes = array()) {
if ($this->type) {
$custom_attribute_keys = $this->getCustomAttributesFromType();
$custom_attributes = (array) $this->custom_attributes ?: [];
foreach ($custom_attribute_keys as $key) {
$attributes[$key] = array_get($custom_attributes, $key);
}
}
return $attributes;
}
protected function addMutatedAttributesToArray(array $attributes, array $mutatedAttributes) {
$this->appendCustomAttributes($this, $attributes);
$attributes = $this->setCustomAttributesFromType($attributes);
return parent::addMutatedAttributesToArray($attributes, $mutatedAttributes);
}
protected function mutateAttribute($key, $value)
{
$keys = $this->getCustomAttributesFromType();
if ( in_array($key, $keys) ) {
return $this->getCustomAttributeValue( $key, $value );
}
return parent::mutateAttribute($key, $value);
}
protected function getCustomAttributeValue($key, $value) {
$custom_attributes = (array) $this->custom_attributes ?: [];
return array_get($custom_attributes, $key, $value);
}
I have to be honest - quickly looking at the code I don't see anything wrong but it doesn't mean everything is for sure ok.
If I were you, I would try to limit Person model just to:
class Person extends \Illuminate\Database\Eloquent\Model {
protected $fillable = [
'person_type_id',
'email',
'fname',
'lname',
'user_id',
'modified_by_user_id',
'audited_at',
'custom_attributes'
];
protected $casts = [
'custom_attributes' => 'json',
'user_id' => 'integer',
'modified_by_user_id' => 'integer',
'person_type_id' => 'integer'
];
protected $dates = [
'audited_at'
];
public static $transformer = PersonTransformer::class;
public function user() {
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function type() {
return $this->belongsTo(PersonType::class, 'person_type_id');
}
public function assets() {
return $this->hasMany(Asset::class, 'person_id');
}
}
and now I would verify if everything is fine. If it's fine, now you could investigate this further, add one trait and verify, add second trait and verify, finally extend from same class.
There must be bug somewhere but looking at this code it's hard do find anything
user is reserved name in eloquent.
try User instead of user
public function User() {
return $this->belongsTo(User::class, 'user_id', 'id');
}

Call to a member function associate() on a non-object

Error Message: http://puu.sh/d4l0F/5b0ac07e68.png
I've even saved the $transportation object before trying to create associations. I've verified that both $transporation, $from and $to are all their respective objects and they are.
I'm sure I'm missing something stupid here but I'm out of ideas.
My code:
class RideBuilder implements RideBuilderInterface
{
public function create(Advance $advance)
{
$ride = new Ride;
if($ride->validate(Input::all())) {
$ride->save();
$to = Location::find(Input::get('dropoffLocation'));
$from = Location::find(Input::get('pickupLocation'));
$transportation = new Transportation;
$transportation->save();
$transportation->transportable()->associate($ride);
$transportation->to()->associate($to);
$transportation->from()->associate($from);
$event = new Event;
$event->start = Input::get('ridePickUpTime');
$event->save();
$event->eventable->save($transportation);
$event->subjectable->save($advance);
}
return $ride;
}
}
Location Model:
class Location extends Elegant
{
protected $table = 'locations';
public $rules = array(
'label' => 'required|min:2',
'street' => 'required',
'city' => 'required',
'state' => 'required',
'type' => 'required',
);
public function advance()
{
return $this->belongsTo('Booksmart\Booking\Advance\Model\Advance');
}
public function locationable()
{
return $this->morphTo();
}
}
Transportation Model:
class Transportation extends Elegant
{
protected $table = 'transportations';
public function event()
{
$this->morphOne('Booksmart\Component\Event\Model\Event');
}
public function start_location()
{
$this->belongsTo('Booksmart\Component\Location\Model\Location', 'start_location');
}
public function end_location()
{
$this->belongsTo('Booksmart\Component\Location\Model\Location', 'end_location');
}
}
I had a similar issue. I made the stupid mistake of not adding the "return" in the relationship method!
Make sure you return the relationship... Obviously this will not work:
public function medicineType()
{
$this->belongsTo('MedicineType', 'id');
}
This is the correct way:
public function medicineType()
{
return $this->belongsTo('MedicineType', 'id');
}
Easy to miss, hard to debug...

how to return the user id when the user logged in successfully in codeigniter

here is the controller to login form, after the login process the user will be able to do add posts to database, so i need to collect some data as the username of the current logged user & the id of this user in the {users table}
<?php
class login extends CI_Controller{
function index()
{
$this->load->view('login_form');
}
function proccess()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated ..
{
$data = array(
'username_usr' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('view=dogo&do=new_post');
}
else
{
$this->index();
}
}
function signup()
{
//signup proccess
}
}
and here is the model of login process
<?php
class Membership_model extends CI_Model{
function validate()
{
$this->db->where('username_usr', $this->input->post('username'));
$this->db->where('password_usr', md5($this->input->post('password')));
$query = $this->db->get('hs_users_usr');
if($query->num_rows == 1)
{
return true;
}
}
}
I can return the username of the logged user, i need also to return the id of this user
You can return the query if it's successful and pull the user id from it:
Controller
<?php
class login extends CI_Controller{
function index()
{
$this->load->view('login_form');
}
function proccess()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query !== FALSE) // if the user's credentials validated ..
{
$user_data = $query->row();
$data = array(
'user_id' => $user_data->id,
'username_usr' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('view=dogo&do=new_post');
}
else
{
$this->index();
}
}
function signup()
{
//signup proccess
}
}
Model
<?php
class Membership_model extends CI_Model{
function validate()
{
$this->db->where('username_usr', $this->input->post('username'));
$this->db->where('password_usr', md5($this->input->post('password')));
$query = $this->db->get('hs_users_usr');
if($query->num_rows == 1)
{
return $query;
}
else
{
return FALSE;
}
}
}

Resources