• 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

General

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

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

Servis table top terbaik daripada TreTop Enterprise

January 21, 2021 by ghazalitajuddin Leave a Comment

Hujung tahun lepas, aku upah tukang table top bagi menggantikan table top lama yang menghadapi masalah reput dan anai-anai.

So macam biasa zaman teknologi di hujung jari hahaha… sebelum apa-apa hal aku pun search dulu di google dan di facebook mencari tukang-tukang rumah yang berpengalaman dalam membuat table top ni. Mana tahu dapat kenal tukang table top terbaik di Kuantan kan? Sambil tu ada juga aku tengok tutorial di youtube konon-kononnya nak try buat sendiri.

Hahaha mimpi jela. [Read more…] about Servis table top terbaik daripada TreTop Enterprise

Filed Under: General, Kuantan Tagged With: harga table top kuantan, table top murah kuantan, tre top entreprise

Pemilikan Kereta Patuh Syariah

January 20, 2021 by ghazalitajuddin Leave a Comment

Kalau tajuk Patuh Syariah ni memang meletop sokmo.

Kebetulan aku terbaca posting pujian Dr UZAR terhadap inisiatif skim pemilikan atau pembelian kereta yang patuh syariah.

UZAR sekadar menyatakan pujian beliau terhadap inisiatif Toyota berkenaan, tidaklah bermaksud apa-apa. Malah beliau juga menyatakan beliau sendiri tiada info berkaitan syarikat atau siapa yang menjadi Penasihat Syariah mereka. 

Tapi bila tengok komen tu seperti biasa ramai mempertikaikan sistem kewangan islam sedia ada. Keadaan sama juga berlaku kepada takaful dan insuran konvensional. Habis segala komen tak berkaitan pun keluar. Itulah keburukan SOSMED, salah guna bawak dosa free je.

[Read more…] about Pemilikan Kereta Patuh Syariah

Filed Under: General Tagged With: conventional insurance, conventional loan, islamic finance, pemilikan kereta patuh syariah, sistem kewangan islam, syariah compliance, Takaful Mahal, toyota kapital, ustaz zaharuddin abd rahman, uzar

Sesungguhnya untung orang berniaga itu bukan sekadar wang ringgit

January 18, 2021 by ghazalitajuddin Leave a Comment

Berniaga ni sunnah. 9/10 rezeki datang daripada berniaga. 

Selain itu orang berniaga ni pun bebas, tak terikat dengan sesiapa.

Namun disebalik kebebasan itu, orang berniaga ni tanggungan dia berat. All responsibilities jatuh atas bahu sendiri.

Peluang untuk buat pahala banyak, buat dosa pun banyak. 

[Read more…] about Sesungguhnya untung orang berniaga itu bukan sekadar wang ringgit

Filed Under: General Tagged With: halal, ibadah, rezeki berkat, rezeki halal, sumber rezeki

Sistem Pendidikan Perlukan Innovasi

January 17, 2021 by ghazalitajuddin Leave a Comment

Semalam kita semua dimaklumkan tentang penangguhan pembukaan sekolah tahun 2021 yang sepatutnya bermula pada 20 Januari 2021.

Dalam group WhatsApp dah huru-hara parent mengamuk tentang penangguhan ini. Mana tak mengamuk kalau masing-masing buat pelbagai persediaan untuk anak-anak ke sekolah. Ini termasuk jugalah pembayaran pendaftaran sekolah dan kelengkapan yang lain. Itu belum kira lagi kalau keluarga mangsa banjir baru ni. Banyak keluar modal weiii.

[Read more…] about Sistem Pendidikan Perlukan Innovasi

Filed Under: General, Kesihatan Tagged With: covid-19, kementerian kesihatan malaysia, kementerian pendidikan malaysia, KPM, pembukaan sekolah ditangguh, sesi persekolahan secara bersemuka

  • Page 1
  • Page 2
  • Page 3
  • Interim pages omitted …
  • Page 28
  • 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

Meraikan hari lahir di Loteng

Laksam Terbaik Di Kuantan, Sanggup Menunggu Sejam

Cendol Terbaik Di Kuantan

Sarapan pagi di Arked Sri Gambut

Breakfast di De Aisyah Kuantan

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. •