• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

GhazaliTajuddin.com

Another Kuantan Blogger

  • Home
  • Blog
    • Kuantan
    • Foods
    • Technology
    • Health
  • Stock Photography
    • Senarai Microstock Agency
    • Membuka akaun contributor Shutterstock.com
    • Tips untuk 10 keping gambar pertama Shutterstock.com
    • Mengapa Shutterstock.com reject gambar / submission
    • Model Release
    • Bagaimana withdraw earning daripada Fotolia
    • Bagaimana untuk mengisi keyword kepada imej dengan menggunakan Adobe Photoshop

Technology

BadMethodCallException Method Illuminate\Database\Eloquent\Collection::roles does not exist.

July 27, 2023 by ghazalitajuddin Leave a Comment

ERROR

BadMethodCallException Method Illuminate\Database\Eloquent\Collection::roles does not exist.
BadMethodCallException Method Illuminate\Database\Eloquent\Collection::permissions does not exist.

The hint here is ‘Collection‘…

If somehow you got this error while you have check all code is ok, relationship is ok, then try to check either you use first() or get() method.

Supposedly you use first() instead of get() method as get() method will return a collection() while first() just return a record.

Tinker

$r = App\Models\Role::where('slug','super-admin')->first()
= App\Models\Role {#7268
    id: 1,
    name: "Super Admin",
    slug: "super-admin",
    created_at: "2023-07-27 01:11:24",
    updated_at: "2023-07-27 01:11:24",
  }

 $u = App\Models\User::where('name','Ghazali Tajuddin')->first()
= App\Models\User {#7278
    id: 1,
    name: "Ghazali Tajuddin",
    email: "ghazali.tajuddin@gmail.com",
    email_verified_at: "2023-07-27 01:11:24",
    #password: "",
    #remember_token: null,
    created_at: "2023-07-27 01:11:24",
    updated_at: null,
  }

Filed Under: Technology Tagged With: error, Framework, laravel, relationship

User Roles And Permissions Without Package Laravel 10

July 25, 2023 by ghazalitajuddin Leave a Comment

Role Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Role extends Model
{
    use HasFactory;

     /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'slug',
    ];

    /**
     * The users that belong to the Role
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }

    /**
     * The roles that belong to the Role
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function permissions(): BelongsToMany
    {
        return $this->belongsToMany(Permission::class,'role_permission');
    }


    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value;
        $this->attributes['slug'] = Str::slug($value);
    }


}

Role Migration

        Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
    

    

Permission Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Permission extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'slug',
    ];

    /**
     * The roles that belong to the Permission
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }

    /**
     * The roles that belong to the Permission
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class,'role_permission');
    }

    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value;
        $this->attributes['slug'] = Str::slug($value);
    }
}

Permission Migration


        Schema::create('permissions', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->timestamps();

        });

App\Services\HasPermissionsTraits.php

<?php

namespace App\Services;

use App\Permission;
use App\Role;

trait HasPermissionsTrait {

   public function givePermissionsTo(... $permissions) {

    $permissions = $this->getAllPermissions($permissions);
    if($permissions === null) {
      return $this;
    }

    $this->permissions()->saveMany($permissions);
    return $this;

  }

  public function withdrawPermissionsTo( ... $permissions ) {

    $permissions = $this->getAllPermissions($permissions);
    $this->permissions()->detach($permissions);
    return $this;

  }

  public function refreshPermissions( ... $permissions ) {

    $this->permissions()->detach();
    return $this->givePermissionsTo($permissions);

  }

  public function hasPermissionTo($permission) {

    return $this->hasPermissionThroughRole($permission) || $this->hasPermission($permission);

  }

  public function hasPermissionThroughRole($permission) {

    foreach ($permission->roles as $role){
      if($this->roles->contains($role)) {
        return true;
      }
    }
    return false;

  }

  public function hasRole( ... $roles ) {

    foreach ($roles as $role) {
      if ($this->roles->contains('slug', $role)) {
        return true;
      }
    }
    return false;

  }

  public function roles() {

    return $this->belongsToMany(Role::class,'users_roles');

  }
  public function permissions() {

    return $this->belongsToMany(Permission::class,'users_permissions');

  }
  protected function hasPermission($permission) {

    return (bool) $this->permissions->where('slug', $permission->slug)->count();
  }

  protected function getAllPermissions(array $permissions) {

    return Permission::whereIn('slug',$permissions)->get();

  }
}

Create custom provider

php artisan make:provider PermissionsServiceProvider

App\Providers\PermissionsServiceProvider.php

<?php

namespace App\Providers;

use App\Services;
use App\Models\Permission;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;


class PermissionsServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     */
    public function boot()
    {
        try {
            Permission::get()->map(function ($permission) {
                Gate::define($permission->slug, function ($user) use ($permission) {
                    return $user->hasPermissionTo($permission);
                });
            });
        } catch (\Exception $e) {
            report($e);
            return false;
        }

        //Blade directives
        Blade::directive('role', function ($role) {
             return "if(auth()->check() && auth()->user()->hasRole({$role})) :"; //return this if statement inside php tag
        });

        Blade::directive('endrole', function ($role) {
             return "endif;"; //return this endif statement inside php tag
        });
    }
}

Register our provider at Config\App.php


    'providers' => ServiceProvider::defaultProviders()->merge([
        /*
         * Package Service Providers...
         */

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        App\Providers\PermissionsServiceProvider::class,
    ])->toArray(),


Tinker

$u = App\Models\User::where('name','Ghazali Tajuddin')->first()
= App\Models\User {#7268
    id: 1,
    name: "Ghazali Tajuddin",
    email: "ghazali.tajuddin@gmail.com",
    email_verified_at: "2023-07-27 06:24:48",
    #password: "",
    #remember_token: null,
    created_at: "2023-07-27 06:24:48",
    updated_at: null,
  }
$p = App\Models\Permission::where('slug','create-neighbourhood')
->first()
= App\Models\Permission {#7274
    id: 19,
    name: "Create Neighbourhood",
    slug: "create-neighbourhood",
    created_at: "2023-07-27 06:24:49",
    updated_at: "2023-07-27 06:24:49",
  }
$r = App\Models\Role::where('slug','super-admin')->first()
= App\Models\Role {#7283
    id: 1,
    name: "Super Admin",
    slug: "super-admin",
    created_at: "2023-07-27 06:24:49",
    updated_at: "2023-07-27 06:24:49",
  }
//Attach Roles To User
$u->roles()->attach($r)

//Attach Permissions To User
$u->permissions()->attach($p)
//Test if user has permission to "create-neighbourhood" slug
$u->can('create-neighbourhood')
= true

//Test if user has role "super-admin" slug
$u->hasRole('super-admin')
= true

//Test $u
$u
= App\Models\User {#7268
    id: 1,
    name: "Ghazali Tajuddin",
    email: "ghazali.tajuddin@gmail.com",
    email_verified_at: "2023-07-27 06:24:48",
    #password: "",
    #remember_token: null,
    created_at: "2023-07-27 06:24:48",
    updated_at: null,
    permissions: Illuminate\Database\Eloquent\Collection {#7288
      all: [
        App\Models\Permission {#7291
          id: 19,
          name: "Create Neighbourhood",
          slug: "create-neighbourhood",
          created_at: "2023-07-27 06:24:49",
          updated_at: "2023-07-27 06:24:49",
          pivot: Illuminate\Database\Eloquent\Relations\Pivot {#7289
            user_id: 1,
            permission_id: 19,
          },
        },
      ],
    },
    roles: Illuminate\Database\Eloquent\Collection {#7298
      all: [
        App\Models\Role {#7293
          id: 1,
          name: "Super Admin",
          slug: "super-admin",
          created_at: "2023-07-27 06:24:49",
          updated_at: "2023-07-27 06:24:49",
          pivot: Illuminate\Database\Eloquent\Relations\Pivot {#7276
            user_id: 1,
            role_id: 1,
          },
        },
      ],
    },
  }
//Get Super Admin Role
$r = App\Models\Role::where('slug','super-admin')->first()
= App\Models\Role {#7268
    id: 1,
    name: "Super Admin",
    slug: "super-admin",
    created_at: "2023-07-27 07:17:27",
    updated_at: "2023-07-27 07:17:27",
  }
//Get role permissions only 'name' attribute 
$r->permissions()->pluck('name')
= Illuminate\Support\Collection {#7292
    all: [
      "Create User",
      "Read User",
      "Update User",
      "Delete User",
      "List User",
    ],
  }
//Get Property Residential Id 1 Neighbourhood Record
$pr = App\Models\PropertyResidential::find(1)
->property->street->neighbourhood
= App\Models\Neighbourhood {#7328
    id: 1,
    name: "Taman Koperasi Guru",
    acronym: "tkg",
    subdomain: "tkg",
    slug: "taman-koperasi-guru",
    postcode: "25150",
    city: "Kuantan",
    state: "Pahang",
    resgistrar_id: null,
    created_at: null,
    updated_at: null,
  }
//Get Property Id 1 Neighbourhood Record 
$pr = App\Models\Property::find(1)->street->neighbourhood
= App\Models\Neighbourhood {#7328
    id: 1,
    name: "Taman Koperasi Guru",
    acronym: "tkg",
    subdomain: "tkg",
    slug: "taman-koperasi-guru",
    postcode: "25150",
    city: "Kuantan",
    state: "Pahang",
    resgistrar_id: null,
    created_at: null,
    updated_at: null,
  }
//Get property with number(1) neighbourhood record
$pr = App\Models\Property::where('number','1')
->first()->street->neighbourhood
= App\Models\Neighbourhood {#7336
    id: 1,
    name: "Taman Koperasi Guru",
    acronym: "tkg",
    subdomain: "tkg",
    slug: "taman-koperasi-guru",
    postcode: "25150",
    city: "Kuantan",
    state: "Pahang",
    resgistrar_id: null,
    created_at: null,
    updated_at: null,
  }
//Get Property Id(1) Neighbourhood Name
$pr = App\Models\Property::find(1)->street->neighbourhood->name
= "Taman Koperasi Guru"
//Get Property Id(1) Street Name
$pr = App\Models\Property::find(1)->street->name
= "Lorong Karyawan 1"
//Get property record with number (2) on street (1) only with full_name and created_at attribute
$pr = App\Models\Property::where('number','2')
->where('street_id','1')
->first()
->residents
->map->only('full_name','created_at')
= Illuminate\Support\Collection {#7371
    all: [
      [
        "full_name" => "Ghazali Tajuddin",
        "created_at" => Illuminate\Support\Carbon @1690467115 {#7268
          date: 2023-07-27 14:11:55.0 UTC (+00:00),
        },
      ],
      [
        "full_name" => "Ida",
        "created_at" => Illuminate\Support\Carbon @1690467115 {#7344
          date: 2023-07-27 14:11:55.0 UTC (+00:00),
        },
      ],
    ],
  }


//Get property residential with male disabilities and take 2 records
$pr = App\Models\PropertyResidential::
whereNotNull('male_disabilities')
->where('male_disabilities','>',0)->take(2)->get()
= Illuminate\Database\Eloquent\Collection {#7269
    all: [
      App\Models\PropertyResidential {#7268
        id: 1,
        property_id: 1,
        registrar_id: null,
        male_babies: 2,
        female_babies: 2,
        male_childs: 2,
        female_childs: 2,
        male_adults: 2,
        female_adults: 2,
        male_seniors: 2,
        female_seniors: 2,
        male_disabilities: 2,
        female_disabilities: 2,
        has_health_problem: 2,
        health_description: "2",
        total_resident: 2,
        occupancy_status: 2,
        created_at: "2023-07-28 02:26:24",
        updated_at: null,
      },
      App\Models\PropertyResidential {#7271
        id: 2,
        property_id: 2,
        registrar_id: null,
        male_babies: 2,
        female_babies: 2,
        male_childs: 2,
        female_childs: 2,
        male_adults: 2,
        female_adults: 2,
        male_seniors: 2,
        female_seniors: 2,
        male_disabilities: 2,
        female_disabilities: 2,
        has_health_problem: 2,
        health_description: "2",
        total_resident: 2,
        occupancy_status: 2,
        created_at: "2023-07-28 02:26:24",
        updated_at: null,
      },
    ],
  }
//Get first record property record
$pr->get(0)->property
= App\Models\Property {#7259
    id: 1,
    type: 1,
    number: "1",
    street_id: 1,
    owner_name: null,
    owner_contact: null,
    neighbourhood_id: 1,
    registrar_id: 1,
    created_at: null,
    updated_at: null,
  }

Reference link.

Filed Under: General, Kuantan Web Developer, Technology

Laravel Many To Many Relationship

July 22, 2023 by ghazalitajuddin Leave a Comment

Property Class

class Property extends Model
{
    protected $table = 'properties';
    use HasFactory;

    /**
     * Get the Street that owns the Property
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function street(): BelongsTo
    {
        return $this->belongsTo(Street::class);
    }

    /**
     * Get the Neighbourhood that owns the Property
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function neighbourhood(): BelongsTo
    {
        return $this->belongsTo(Neighbourhood::class);
    }
}

Resident Class

class Resident extends Model
{
    use HasFactory;
    protected $guarded = [];
    
    /**
     * The Property that belong to the Resident
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function properties(): BelongsToMany
    {
        return $this->belongsToMany(Property::class);
    }
}

Pivot class, PropertyResident class.

class PropertyResident extends Model
{

    use HasFactory;
    protected $fillable = ['property_id', 'resident_id'];

}

Use tinker to test

php artisan tinker 

//To find resident id
$r=App\Models\Resident::find(1)

//To get all resident properties
$r->properties

//To count all resident properties
$r->properties->count()

//To find resident id(1) neighbourhood trough properties (many to many relationship)
$r->properties->find(5)->neighbourhood->name

//To get all resident id(1) property "property_id"
$r->properties()->pluck('property_id')

//To get distinct(*) neighbourhood
$r->properties()->distinct()->pluck('neighbourhood_id')

//To get all neighbourhood id group by neighbourhood id
$r->properties()->groupBy('neighbourhood_id')->pluck('neighbourhood_id')

Filed Under: Kuantan, Kuantan Web Developer, Technology Tagged With: laravel, many to many, many to many relationship, pivot table, relationship, tinker

Linux Copy & Zip

November 8, 2022 by ghazalitajuddin Leave a Comment

Computer code
Computer code by Markus Spiske is licensed under CC-CC0 1.0
zip -r  /path/to/save/destination_folder.zip /path/to/folder

Zip is command on *nix.
-r Recursive to subfolders.

Filed Under: Technology Tagged With: command line, linux, Linux Command

Joomlatools – Professional Tools but Unprofessional Service

November 7, 2022 by ghazalitajuddin Leave a Comment

Sigh. I hate to write down this. I believe there should be other way to solve this.Its really unprofessional service. Since they got me 2 times. This time i should stop this and i think i should share this to others.

If you believe your product is good, you should not have to worry customer will come and recommend to others easy peasy.

If you honest in business, you will have customer trust.

I have 2 scenario why you should stay away from Joomlatools.

  1. I request to update or remove current payment information.
  • They say “Payment information cannot be remove”.
  • See the screen shot
Joomlatools Unprofessional Service
Payment Information Cannot Be Removed
Joomlatools Unprofessional Service
They did not store credit card details. But keep on charge their customer.
  • Come on. It is 2022 already. What the hell of services in 2022 that cannot update or remove payment information?

2. I open two (2) tickets regarding on “Payment Cancellation and Cancel Subscription and Request Refund”

  • They remove those tickets!!!
Joomlatools Unprofessional Service
Before
Joomlatools Unprofessional Service
After

You did not believe it? I also did not believe this. Just see the screen shot taken. See the date how they did not response to any of the tickets.

I hope this post will create some awareness to others before they make any purchase from Joomlatools. I really disappointed with what has they done.

Looking for webhosting?

Filed Under: General, Technology Tagged With: joomla, joomlatools, PHP, subscriptions

How to organise your media files in WordPress?

December 16, 2021 by ghazalitajuddin

Organise your media files
How to organise your media files in WordPress? – Filebird Plugin

When developing a website with WordPress, one of important thing you need to consider before you start to upload tonne of media files to your media library is how to organise your media files. At the early stage after WordPress installation it may not seems any issue, but in long run you will realise how bad is WordPress in organising media files that have been uploaded. Its a total failure since WordPress Media Library does not have any media library manager or even basic folder function that should come natively with the cms.

[Read more…] about How to organise your media files in WordPress?

Filed Under: Technology Tagged With: filebird, media files, mediabay, organise files, organise media files, plugin, wordpress media library

  • Page 1
  • Page 2
  • Page 3
  • Interim pages omitted …
  • Page 24
  • Go to Next Page »

Primary Sidebar

“Solat. Sabar. Syukur. Senyum. Sedekah.”

For Collaboration, Events & Review, kindly contact me at +6016[-]9212092 or click Whatsapp button on this page.

Sponsor

Recent Posts

BadMethodCallException Method Illuminate\Database\Eloquent\Collection::roles does not exist.

User Roles And Permissions Without Package Laravel 10

Laravel Many To Many Relationship

Makan malam bersama keluarga di Awangan Palace

Sarapan pagi di Warung Gulai Kawah

Recent Comments

  • helmi on Personal Tips Berhenti Merokok
  • ghazalitajuddin on Personal Tips Berhenti Merokok
  • helmi on Personal Tips Berhenti Merokok
  • ghazalitajuddin on Nasi Lemak Kukus Restoran Zaman. Otai masih berbisa.
  • ghazalitajuddin on Air tangki radiator Proton Exora cepat kering? Cuba tukar penutup radiator!
  • Mal on Nasi Lemak Kukus Restoran Zaman. Otai masih berbisa.
  • Firdaus on Air tangki radiator Proton Exora cepat kering? Cuba tukar penutup radiator!

My Link

  • Takaful Insurance Web

JJCM

Lain macam Nasi Kerabu Mekla ni

Aneka Kuih Tradisional

Nasi Lemak Kukus Restoran Zaman. Otai masih berbisa.

Berpagian di Restoran Astana Cafe

Minuman Diet

Tags

bebas rokok berhenti merokok breakfast Controller Framework Gezzeg Photography & Design health jalan-jalan cari makan jalan-jalan cari makan kuantan jjcm jjcm kuantan Jurufoto Kuantan Kuantan Kuantan Photographer kuantan programmer kuantan web developer kuantan webmaster laravel merokok merbahayakan kesihatan model MVC nikmat rokok OOP Pahang Pahangtourism pahang tourism Photo Manipulation PHP rajalanun retired smoking revisit pahang 2018 shutterstock stop smoking stop smoking tips stop smoking withdrawal symptom tips tips berhenti merokok View visit malaysia 2020 visit pahang visitpahang white wordpress yii Yii Framework

Recent Posts

  • BadMethodCallException Method Illuminate\Database\Eloquent\Collection::roles does not exist.
  • User Roles And Permissions Without Package Laravel 10
  • Laravel Many To Many Relationship
  • Makan malam bersama keluarga di Awangan Palace
  • Sarapan pagi di Warung Gulai Kawah

Copyright © 2025 — Ghazali Tajuddin • All rights reserved. •