Laravel – A Weblog of Priyank Maniar https://priyank.rocks Articles on web development & mobile app development Wed, 22 Dec 2021 10:22:10 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 [Resolved] Scroll issue with the export columns visibility | BackpackForLaravel https://priyank.rocks/resolved-scroll-issue-with-the-export-columns-visibility-backpackforlaravel/ Wed, 22 Dec 2021 10:18:28 +0000 https://priyank.rocks/?p=8711 This solution was tested on BackpackForLaravel Version 4.1.

1
2
3
4
5
6
7
8
9
10
/* File: list.css */

/*------------------------------------------------
    Custom Added
--------------------------------------------------*/


.dt-button-collection {
    overflow-y: scroll;
    max-height: 200px;
}
]]>
Laravel User Model https://priyank.rocks/laravel-user-model/ Fri, 10 Dec 2021 19:41:03 +0000 https://priyank.rocks/?p=8685 A boilerplate for the User model, expected to be reused in future projects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*------------------------------------------------
        Getters and Setters Access Manipulation
    --------------------------------------------------*/


    /**
     * Trim email, otherwise it could cause issues with swiftmailer, as it doesn't like spaces.
     * @source https://github.com/swiftmailer/swiftmailer/issues/382#issuecomment-124560149
     *
     * lowercase should of course be there
     *
     * @param $value
     * @return void
     */

    public function setEmailAttribute($value)
    {

        $this->attributes['email'] = strtolower(trim($value));
    }
]]>
Laravel Dusk Not Working on Mac https://priyank.rocks/laravel-dusk-not-working-on-mac/ Mon, 19 Jul 2021 18:04:49 +0000 https://priyank.rocks/?p=8085 Okay, so I wish I would have found this piece of info sooner. Here it is:

For me, the issue was that Google Chrome the browser was not installed or dropped into the applications folder. Reinstall Google Chrome and drop the Google Chrome in the applications folder and that’s it! That did it for me.

Laravel Dusk then worked perfectly fine!

]]>
Larecipe https://priyank.rocks/larecipe/ Wed, 23 Jun 2021 13:56:17 +0000 https://priyank.rocks/?p=7919 How to change the default font used for the larecipe?

Head to public/vendor/binarytorch/larecipe/assets/css/app.css

look up for font-family:sans

Replace with:

font-family:"Ubuntu", sans-serif
]]>
Laravel Validation Rules https://priyank.rocks/laravel-validation-rules/ Wed, 16 Jun 2021 16:10:34 +0000 https://priyank.rocks/?p=7902 Two out of three fields required
1
2
3
4
5
6
7
8
        $rules = array(
            'title' => 'required',
// If any one of the field is not present from the other two fields. Makes the field being valided as required.
            'issue_letter' => Rule::requiredIf(!$request->call_issue || !$request->twitter_issue),
            'call_issue' => Rule::requiredIf(!$request->issue_letter || !$request->twitter_issue),
            'twitter_issue' => Rule::requiredIf(!$request->issue_letter || !$request->call_issue),
            'slug' => 'required'
        );
]]>
Problem with Laravel Accessors and Mutators https://priyank.rocks/problem-with-laravel-accessors-and-mutators/ Sat, 12 Jun 2021 18:16:26 +0000 https://priyank.rocks/?p=7859 update() does not trigger mutators. There is a workaround to it that does work. Problem 2: For the ->sum() the getters/accessors do not...]]> Problem 1:

->update() does not trigger mutators. There is a workaround to it that does work.

Problem 2:

For the ->sum() the getters/accessors do not work.

1
PaymentMade::whereUserId($userId)->sum('amount')

The above trick does not help either. At that moment, I felt I don’t know how many problems we are going to run into. With as much less time we developers have, it felt wise to not use it.

]]>
Backpack for Laravel roles and permissions for the Users module https://priyank.rocks/backpack-for-laravel-roles-and-permissions-module/ Thu, 27 May 2021 16:10:41 +0000 https://priyank.rocks/?p=7790 All details can be found here about the package.

A thing to note here is the package comes with the roles and permissions manageable out of the box. Check out this part for customizing on the user’s module.

We can use our own UsersCrudController as it is far more likely there will be some customization required. For whatever we require from their setup we can copy from their file.

For example: the following gives the manageable roles fields. Copied from their file as is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
$this->crud->addFields([
      [
          'tab' => 'Roles',
        // two interconnected entities
        'label'             => trans('backpack::permissionmanager.user_role_permission'),
        'field_unique_name' => 'user_role_permission',
        'type'              => 'checklist_dependency',
        'name'              => ['roles', 'permissions'],
        'subfields'         => [
            'primary' => [
                'label'            => trans('backpack::permissionmanager.roles'),
                'name'             => 'roles', // the method that defines the relationship in your Model
                'entity'           => 'roles', // the method that defines the relationship in your Model
                'entity_secondary' => 'permissions', // the method that defines the relationship in your Model
                'attribute'        => 'name', // foreign key attribute that is shown to user
                'model'            => config('permission.models.role'), // foreign key model
                'pivot'            => true, // on create&update, do you need to add/delete pivot table entries?]
                'number_columns'   => 3, //can be 1,2,3,4,6
            ],
            'secondary' => [
                'label'          => ucfirst(trans('backpack::permissionmanager.permission_singular')),
                'name'           => 'permissions', // the method that defines the relationship in your Model
                'entity'         => 'permissions', // the method that defines the relationship in your Model
                'entity_primary' => 'roles', // the method that defines the relationship in your Model
                'attribute'      => 'name', // foreign key attribute that is shown to user
                'model'          => config('permission.models.permission'), // foreign key model
                'pivot'          => true, // on create&update, do you need to add/delete pivot table entries?]
                'number_columns' => 3, //can be 1,2,3,4,6
            ],
        ],
    ],
]);

Gotcha #1

If you are using Mutator for the password field on the Users model. Be sure to update the code accordingly. Here’s what I mean:

1
2
3
4
5
6
7
8
        // Encrypt password if specified.
        if ($request->input('password')) {
//            $request->request->set('password', Hash::make($request->input('password')));
            // Removed hash because User model has a mutator on the password.
            $request->request->set('password', $request->input('password'));
        } else {
            $request->request->remove('password');
        }

Gotcha #2

When the password is updated user is logged out and if you are using prefix, you are logged in to /login which is not even your admin login page.

First, let’s understand why we are logged out? Read this post.

The backpack version of solution to it is the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
     * Update the specified resource in the database.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update()
    {

        $this->crud->setRequest($this->crud->validateRequest());
        $this->crud->setRequest($this->handlePasswordInput($this->crud->getRequest()));
        $this->crud->unsetValidation(); // validation has already been run

        $return = $this->traitUpdate();

        /**
         * Otherwise the use will be logged out when the password is changed!
         * @source https://stackoverflow.com/questions/47147988/prevent-logout-after-updating-user-password-in-laravel-5-5
         */
        Auth::loginUsingId(Request::segment(3));

        return $return;
    }
]]>
Spatie Laravel Roles and Permissions https://priyank.rocks/spatie-laravel-roles-and-persmissions/ Thu, 27 May 2021 08:02:59 +0000 https://priyank.rocks/?p=7765 Database Tables Used

model_has_roles

model_has_roles table

The role_id is foreign to roles table, straight-forward. model_type is self-explanatory. model_id is the id for the users table.

Query based on roles

Please note the ->hasRoles does not work with query. That works on the user model as a method to check something.

For query perhaps we can use the following:

1
$query->role($userRole);

https://laracasts.com/discuss/channels/laravel/get-spatie-roles-included-with-the-query-builder?page=1#reply=609463

How to get all the roles of the users? Further putting all the role ids into an Array.

1
2
3
4
5
6
7
8
9
10
11
12
$userRoleIdsArray = [];
                    $userRoles = User::whereId(Auth::id())->with('roles')->first();

                    if (!empty($userRoles)) {

                        foreach ($userRoles->roles as $role) {
                            array_push($userRoleIdsArray, $role->id);
                        }
                        unset($userRoles);
                    } else {
                        Log::error("Plan.userRow not found for the user Id -" . Auth::id());
                    }

More details can be found here.

How to write a relationship to Roles Model since we do not have one by default?

This is useful when let’s say we want to have a plans table and we want plans and roles to be mapped with a pivot table. So we can create a many-to-many relationship between roles and plans. Here’s how to do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Role extends \Spatie\Permission\Models\Role
{
    use HasFactory;

    public function plans()
    {
        return $this->belongsToMany(Plan::class);
    }

}

Read more about this over here.

]]>
JetStream Fortify check if the user belongs to a specific role or is active while logging in https://priyank.rocks/fortify-check-if-the-user-belongs-to-a-specific-role-or-is-active/ Sun, 04 Apr 2021 12:24:27 +0000 https://priyank.rocks/?p=7588 This guide is helpful.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// JetstreamServiceProvider.php

Fortify::authenticateUsing(function (Request $request) {
            $user = User::where('email', $request->email)->whereFileNumber($request->fileNumber)->userActive()->role('Debtor')->first();

            if ($user &&
                Hash::check($request->password, $user->password)) {

                $userLoginDetailObj = new UserLoginDetail();
                $userLoginDetailObj->loginDetails($user->id);

                return $user;
            }
        });
]]>
Fortify signup user with default as email verified | Inertia https://priyank.rocks/fortify-signup-user-with-default-as-email-verified-inertia/ Thu, 04 Mar 2021 15:00:48 +0000 https://priyank.rocks/?p=7568 The users table has email_verified_at. Fill this in when the user is created and this will mark the user as verified. It’s that simple.

]]>