Tuesday, March 8, 2022

How to create custom module in Laravel 8

 In this article, we will learn about how we can create custom module in Laravel 8.

To create custom module in Laravel 8 we will use nwidart/laravel-modules.

nwidart/laravel-modules is a Laravel package that was created to manage your large Laravel app using modules. The module is like a Laravel package, it has some views, controllers or models. This package is supported and tested in Laravel 5+

The nwidart/laravel-modules package is a re-published, re-organised and maintained version of ‘pingpong/modules’, which isn’t been maintained anymore. For more information about this package. Click Here.

What we all learn in this article

Step – 1 Installation of Laravel Application

Run the below command to install Laravel

composer create-project --prefer-dist laravel/laravel learn

Step -2 Now we will install our nwidart/laravel-modules package

Run the below command to install nwidart/laravel-modules package.

composer require nwidart/laravel-modules

Step -3 How to create custom module

Run the below command to create a module under your nwidart/larave-modules

php artisan module:make Customer

The above will command will create Customer module, you can check under Module/customer.

Step – 4 How to create a model

Run the below command to create a model

php artisan module:make-model Customer Customers

Step – 5 How to create a migration and model together

Run the below command to create a migration and model together, here -m is use for creating the model, model will created inside your entities folder.

php artisan module:make-model Customer -m Customers

Step – 6 How to create a controller

Run the below command to create a controller inside your module

php artisan module:make-controller CustomersController Customer

Step – 7 How to create a seeder

Run the below command to create a seeder

php artisan module:make-seed StatesTableSeeder Customers

The above code will generate a seed file like the one shown below:

<?php
namespace Modules\Customers\Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class StatesDatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();        // $this->call("OthersTableSeeder");
    }
}

Step-: 8 How to Delete a module

php artisan module:delete Customers 

I hope you like the above article, and you understood how to create a custom module in laravel 8, if you like the article please rate us 5

Build a REST API with Laravel API resources

 https://blog.codehunger.in/build-a-rest-api-with-laravel-api-resources/

Laravel Unique Visitor Counter

 https://blog.codehunger.in/laravel-unique-visitor-counter/

Laravel Eloquent When Condition With Example

 

Hello everyone, I hope you are doing well, In this article, we will get to know how to use when conditions in Laravel Eloquent with example.

Most of the time we have to use if else on the same eloquent, and it’s not the correct way of doing, because in that case you are calling the same query inside if and else statement. To get rid of this thing laravel has introduced When Condition.

Now let’s look for the below example where I am trying to get post related to the particular user, I thought you will also do in the below way, if you don’t know about the when condition.

Example:1 Getting Data by using if condition

In the below code I am trying to get Post related to the authenticated user and to get the authenticated user we have to Auth facade.

$posts = Post::select("*");
$userID = Auth::user()->id;
if ($userID) {
    $posts = $posts->where('user_id', $userID);
}
$posts = $posts->get();

Example:2 By using When Condition

Now we will do the same thing by using laravel eloquent when condition.

$userID = Auth::user()->id;
$posts = Post::select("*")
->when($userID), function ($query) use ($request) {
    $query->where('user_id', $userID);
})
->get();

Now the question is what to do in case of multiple if else condition, don’t worry about that I am here to rid of this thing also. see the below example.

Example:3 By using if-else condition

In the below example what I am trying to do is, I would like to sort it in ascending order based on published date, and if published date is not available then it will get data by created_at

 public function index(Request $request)
    {
        $posts = Post::select("*");
        if ($request->get('order_by') == "publish_date") {
            $posts = $posts->orderBy('publish_date', 'desc');
        } else {
            $posts = $posts->orderBy('created_at', 'desc');

        }
        $posts = $posts->get();
        dd($posts);
    }

Example:4 By using multiple when condition

Now we will do the same thing by using multiple when condition, Look for the below example.

public function index(Request $request)
{
    $posts = Post::select("*")
                ->when($request->get('order_by') == "publish_date", function ($query) {
                        return $query->orderBy('publish_date', 'desc');
                    }, function ($query) {
                        return $query->orderBy('created_at', 'desc');
                    })
                    ->get();

    dd($posts);
}

It’s not just a prettier way to write the same “IF” but is also a great way to organize conditional queries.

I hope now you understood, that how we can use laravel eloquent when condition, then how about giving me 5 stars. Thanks.

Deploy Laravel On Shared Hosting without moving public folder

 https://blog.codehunger.in/deploy-laravel-on-shared-hosting-without-moving-public-folder/

Hello everyone, I hope you guys are doing well, and in this article, we will learn about how we can deploy laravel on shared hosting without moving public folder data outside.

Or you can say, we can deploy laravel with changing in public folder, or Upload laravel to shared hosting without changing in public folder.

You can also follow up on this example if you are uploading/deploying laravel projects on GoDaddy, hostinger, Bluehost etc.

We will follow the below steps to deploy/upload laravel on shared hosting

  1. Zip our local project
  2. Upload the zip in your public_html folder
  3. Unzip the folder
  4. Change in .env
  5. Copy .htacces and update the code
  6. Visit your url

Step-1 Zip our local Project

This one is the very basic step that you all have to do, is to your project root path and zip your project as like I have done in my local computer. my project zip file named as eye-clinic.zip I have marked that one with the red marker, you can see that one in the below image

local-zip-folder-ready-to-upload-on-shared hosting

Step-2 Upload the zip in your public_html folder on shared hosting

Now you have to log in to your shared hosting account, I have my GoDaddy account so I will explain this one with my GoDaddy account, If you are also deploying your laravel project on GoDaddy then you have an image as like below when you log in.

godaddy cpanel image

Now you have to go into your cPanel admin, when clicking on cPanel admin then you have the image like the below one.

godaddy cpanel admin

Now you have to click on file manager from your admin panel, when you click on the file manager you have the image like the below one.

Now click on public_html, if you have a single hosting website plan then you can directly unzip the folder inside public_html, and if you have an ultimate plan then your public_html will look like the below one as I have the ultimate plan and deploy the laravel project inside staging.kumareyecentre.in the website.

Step-3 Unzip the folder

Now it’s time to upload your zip project folder to the shared hosting, I will upload the zip folder in my staging.kumareyecentre.in folder.

Now unzip your folder, my zip folder name was eye-clinic.zip, when I unzip it, it will create a folder named as eye-clinic, now we have to move all the folder and files to our root folder, for me I have to put in staging.kumareyecenter.in folder as like the below image.

file are upload on the shared hosting

Step-4 Change in .env

Now we have to set our app URL in the .env file, as I have done you can see that thing in the below image, I have marked it with the red arrow.

update .env file

Step-5 Copy .htacces and update the code

Now you have to copy your .htacces from the public folder paste them into your project root folder, now replace the .htacces code with the below one.

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1 

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php
</IfModule>

Step-6 Visit your URL

Now all done, it’s time to visit your URL my website looks like the below one

Add custom attribute to laravel eloquent on load

 

Hello there, I hope you are doing well, in this article we will learn about how to add custom attributes to laravel eloquent on load.

Or you can also say add an attribute to the model collection, we will use an accessor to achieve our goal, look for the below example.

Let’s suppose you need an IsAdmin attribute to check whether the user is admin or not, how we can do this we will learn in the below example.

Occasionally, when converting models to arrays or JSON, you may wish to add attributes that do not have a corresponding column in your database. To do so, first define an accessor for the value:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Determine if the user is an administrator.
     *
     * @return bool
     */
    public function getIsAdminAttribute()
    {
        return $this->attributes['admin'] === 'yes';
    }
}

Now the part is we have to append it into our array. so we have to add an attribute name to the appends property of your model. so the final code will be something like below.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{  
     /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['is_admin'];

    /**
     * Determine if the user is an administrator.
     *
     * @return bool
     */
    public function getIsAdminAttribute()
    {
        return $this->attributes['admin'] === 'yes';
    }
}

If you want to learn more about how to add attributes to an object or custom attributes to eloquent then you can visit the laravel official website from here.

I hope now you understood that how we can inject custom attributes to eloquent during load time.

Google Recaptcha v3 in Laravel without package

 https://blog.codehunger.in/google-recaptcha-v3-in-laravel-without-package/