• 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

laravel

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

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

Laravel + VueJS: Calling POST API with Object Input

April 1, 2019 by ghazalitajuddin Leave a Comment

In this example, to insert data to our table, we use axios to make POST request to our API with json object data. Example structure of our object as illustrates

API Test with Insomnia

The data object is passed from our front end form to our store.js. In our store.js, inside our actions

let { data } = await Axios.post('http://localhost:8888/test/public/api/learners', {
                body: learnerdetail
            });

When the object received by the controller, it will pass to the appropriate method which in this case is store method().

public function store(Request $request)
    {
        $learner = new Learner();
        $learner->name = $request->input('body.name');
        $learner->learner_id = $request->input('body.learner_id');
        $learner->section = $request->input('body.section');
        $learner->save();

        //return $learner;
    }

 

 

Filed Under: Technology Tagged With: api, axios, json, laravel, object, POST, vuejs

Laravel + VueJS: Handling Exception In Vuex

March 26, 2019 by ghazalitajuddin Leave a Comment

Example 1

a) Controller 

When using get() method, you can provide constraint that will return collection in array. 

If no object. This will return empty array []

public function search($search)
    {
        
        $group = Group::query($search)
        ->where('name', '=', $search) 
        ->get();

        return response()->json($group, 200);
}

b) Thus, in Store.js (Vuex). We can do like this.

actions : {
        
        checkGroupName : async (context, name) => {

                let { data } = await Axios.get('http://localhost:8888/test/public/api/groups/search/'+name);

                if(data.length === 0){
                
                    context.commit('setGroup',{id:0,name:""}); //set to data to null
                    context.commit('setGroupAvailable',false); //set group availability to false

                }else{

                    context.commit('setGroup',data[0]);
                    context.commit('setGroupAvailable',true);

                }
}
}

Example 2

a) Controller

If you are using first() or firstOfFail() it will retrieve the first results of the query. If not, it will throw an exception (Illuminate\Database\Eloquent\ModelNotFoundException)

public function search($search)
    {
        
        $group = Group::query($search)
        ->where('name', '=', $search) 
        ->first();

        return $group;

    }

b) Store.js

By using try .. catch you can captured any exception occurs during API request.

actions : {
        
        checkGroupName : async (context, name) => {
                
                try{
                
                let { data } = await Axios.get('http://localhost:8888/test/public/api/groups/search/'+name);

                console.log(data)
                
                context.commit('setGroup',data);
                context.commit('setGroupAvailable',true);

            } catch (err){
                
                context.commit('setGroup',{id:0,name:""}); //set to data to null
                context.commit('setGroupAvailable',false); //set group availability to false

            }
}
}

 

 

 

Filed Under: Technology Tagged With: laravel, try catch, vuejs, vuetify, vuex

Migrate:Refresh does not work after deleting / renaming migration

March 7, 2019 by ghazalitajuddin Leave a Comment

If you just like me, accidently renaming the migration and then later realise something goes wrong or having some kind of migration error that really makes you want to jump out shouting hardly, this is might be a solution for you.

First just reset your migration.

php artisan migrate: reset

Then browse to your migration tables, suppose to be empty. BUT there will a record left that you can manually delete it.

Then try to migrate again. Hope it will settle your problem. Good luck!

Reference: https://github.com/laravel/framework/issues/2105

 

 

Filed Under: Technology Tagged With: laravel, migration, reset, Seeder

Laravel Passport: How to hide Client_Secret using GuzzleHttp

February 21, 2019 by ghazalitajuddin Leave a Comment

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. … Middleware system allows you to augment and compose client behavior.Apr 22, 2018

How GuzzleHttp helps?

The idea is to create an endpoint at our back end, that we can make a request to the backend endpoint that contain those secret information that we need to keep secret. This way we can avoid to embed / hard coded all the important information on our javascript request each time..

Install the package on our Laravel.

composer require guzzlehttp/guzzle

Make a route on our api. Let say AuthController

Route::post('/login','Auth\AuthController@login');

Create a controller route. 

php artisan make:controller Auth/AuthController

Paste this on our controller

public function login(Request $request)
    {
        $http = new \GuzzleHttp\Client;

        try{
            $response = $http->post('http://localhost:8888/test/public/oauth/token',[
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => 2,
                    'client_secret' => 'Fi7uzcm31Luf3LTz5ZevBVL',
                    'username' => $request->username ,
                    'password' => $request->password ,
                ]
            ]);

                    return $response->getBody();

        } catch (\GuzzleHttp\Exception\BadResponseException $e){

            if($e->getCode()==400){
                return response()->json('Invalid Request. Please enter a username or a password', $e->getCode());
            }else if($e->getCode()==401){
                return response()->json('Your credential is incorrect. Please try again.', $e->getCode());
            }

        return response()->json('Something wrong on the server.',$e->getCode());
        
        }


    }

 

Filed Under: Technology Tagged With: api, GuzzleHttp, kuantan web developer, kuantan webmaster, laravel, Laravel API, Passport, startup

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

I Am Donut

Day Trip Kuantan – Kuala Gandah – Temerloh – Kuantan

Variasi Coconut Shake Hogoh De Coco

Lain macam Nasi Kerabu Mekla ni

Cendol Terbaik Di 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. •