ahmadbadpey

ahmadbadpey

Member Since 3 Years Ago

Experience Points 7,160
Experience Level 2

2,840 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 3
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

17 Nov
8 months ago

ahmadbadpey started a new conversation Sort A Collection According To An Array Of IDs In Laravel

Suppose I have a collection like this named categories :

    Collection {#447
      #items: array:3 [
        0 => array:6 [
          "pos" => "0"
          "col" => "1"
          "row" => "1"
          "size_x" => "2"
          "size_y" => "1"
          "cat_id" => "1"
        ]
        1 => array:6 [
          "pos" => "0"
          "col" => "3"
          "row" => "1"
          "size_x" => "1"
          "size_y" => "1"
          "cat_id" => "11"
        ]
        2 => array:6 [
          "pos" => "0"
          "col" => "1"
          "row" => "2"
          "size_x" => "2"
          "size_y" => "1"
          "cat_id" => "10"
        ]
    ]
    }

On the other hand there is an array of IDs like this :

    [11,10,1]

Now I want to sort element of that collection based on their cat_id index as sorted in an array. means I want result array to be like this :

    Collection {#447
      #items: array:3 [
        0 => array:6 [
          "pos" => "0"
          "col" => "3"
          "row" => "1"
          "size_x" => "1"
          "size_y" => "1"
          "cat_id" => "11"
        ]
        1 => array:6 [
          "pos" => "0"
          "col" => "1"
          "row" => "2"
          "size_x" => "2"
          "size_y" => "1"
          "cat_id" => "10"
        ]
        2 =>array:6 [
          "pos" => "0"
          "col" => "1"
          "row" => "1"
          "size_x" => "2"
          "size_y" => "1"
          "cat_id" => "1"
        ] 
    ]
    }

I used below codes but does not work properly:

    $grids_arr  = [11,10,1];

    $categories = $categories->sortBy(function ($model) use ($grids_arr) {
        return array_search($model->cat_id, $grids_arr);
    });

Update : This is my completed Code I'm using:

            $categories = Category::isTile()->get();

            $grids = collect(config('settings.data_grids'));// This is an array of IDs
            if ($grids->isNotEmpty()) {

                $grids_arr = $grids->pluck("cat_id")->toArray();
                $grids_arr = array_map('intval', $grids_arr); //convert string array elements to integer

                $categories = $categories->sortBy(function ($catg) use ($grids_arr) {
                    return array_search($catg->cat_id, $grids_arr);
                });
            }

Note that it is possible count of array elements was not equal elements of collection.

04 Nov
8 months ago

ahmadbadpey started a new conversation Route Parameter Contain Slashes And Dot Does Not Recognized In New Server

I used thephpleague/glide package in my laravel application to resize images.

I wrote a route like below to get width , height and path of an image on the server and then using that package modify that image and return it.

Route::get('/showImage/{w}/{h}/{src}', [
        'as'   => 'showImage',
        'uses' => function (League\Glide\Server $server, $w, $h, $src) {
            $server->outputImage($src, ['w' => $w, 'h' => $h, 'fit' => 'crop']);
        }
    ])->where('src', '.+');

Suppose I requested http://www.example.com/showImage/300/168/galleries/mypic.jpg url. but while galleries/mypic.jpg is right and exists on the server , I got a 404 not found error.

I have used exactly this route in other projects but on a new host I have encountered this problem.

I think that problem is on src parameter that can contain / and . signs. Because when I use a string without any / and . , that works and can access to src parameter.

11 Sep
10 months ago

ahmadbadpey started a new conversation What DBMS Can Be Used To Implement An ERP In Php (laravel)

In our team included some laravel(php) developers, we want to implement an ERP web based application.

As you know probably, each ERP system is contain many sub components like HR , CRM ,Finance and Billing , Product and Stock ,accounting and so on. so we need to know that what is most appropriate DBMS for that.

for php/laravel developer using MySQL is a common choice. but after analyse and many search on the web , I found that MySQL is not a right choice for big data (like this article).

Now we want to know what is proper and best choice as DBMS : Oracle , SQL Server , MongoDB or ... .

In addition, we want to see how are their compatibility with php/larvel?

19 Aug
11 months ago

ahmadbadpey started a new conversation Prepend To Paginator Fo Dingo Api In Laravel

I'm using Dingo laravel api package. as you know this package has many features include pagination results.

Suppose in a controller method I want to return paginated Post of my app. like this :

    public function category_posts ($cat_id)
    {
        $posts =
            Post::where('active',true)
                ->whereHas(
                    'categories', function ($query) use ($cat_id) {
                    $query->where('categories.cat_id', $cat_id);
                })
                ->paginate(10);


        return $this->paginator($posts, new PostTransformer());
    }

As you see I first select all posts and then paginate them and in each page 10 posts is returned.

But some posts are pinned.means that have a pin field that is true.

Now I want, when user requests posts, if current page is 1 , I select that pin posts and prepend to $posts collection. But I do not know how can I do?

Update :

each category can have some posts and on the other hand each post is belongs to many category .in this case I have manyToMany relation between post and category . in addition to, when user requested a category posts I want to prepend latest pin post that is assigned to that category

10 Aug
11 months ago

ahmadbadpey started a new conversation "Call To Undefined Relationship [latest_posts]" Error On Getting N Related Models Per Parent

I have a Category and Post Model that have a ManyToMany relationships.

like this :

class Category extends Model
{
        public function posts ()
        {
            return $this->belongsToMany('App\Post', 'category_post', 'cat_id', 'post_id')->orderBy('created_at', 'desc');
        }

}

And Post model like this :

class Post extends Model
{
    public function categories ()
    {
        return $this->belongsToMany('App\Category', 'category_post', 'post_id', 'cat_id');
    }

}

Now I want to fetch some categories with their X posts of each them.

I searched a lot and tried different solutions,until I found this solution. According that solution first I added scopeNPerGroup function to Category model and this new relation to that :

    public function latest_posts()
    {
        return $this->posts()->latest()->nPerGroup('cat_id', 3);
    }

But When I want to select some categories and fetch their limited posts like this :

Category::with('latest_posts')
        ->whereIn('cat_id', [1,2,3,4])
        ->get();

I got this error :

Call to undefined relationship [latest_posts] on model [App\Category].

In addition to I want to make a dynamically capability where can sent a x parameter that specify count related models that should be fetch.

24 May
1 year ago

ahmadbadpey started a new conversation Restrict Access Of A Member To Whole Project So That Can Push Only And Can Not Pull In Git And Git Lab

we've working on an ERP project in our company as a team and Our team has a number of members.

Each team member works on specific module that I have determined for them.

To manage codes , we're using git , gitlab and SourceTree git GUI.

The challenge we are facing is when a new member is added to team. In fact I do not want a new member can access to whole project codes. But for other members who have a long history and are trusted is not any limit to access codes.

In fact I am looking for a way that each member can access only to their own codes, means that they can push last changes in their code but can not pull whole project from master for example.

23 Apr
1 year ago

ahmadbadpey left a reply on Check Existence Of Combination Of Two Record In A One To Many Relation Laravel

@Vilfago , No count of attribute is variable and each variation can have some attributes.

ahmadbadpey started a new conversation Check Existence Of Combination Of Two Record In A One To Many Relation Laravel

Suppose I have a Variation model like this :

class Variation extends Model
{
        protected $primaryKey = 'variation_id';

        protected $fillable = ['product_id', 'creator'];

        public function attributes ()
        {
            return $this->hasMany(VariationAttribute::class, 'variation_id', 'variation_id');
        }

        public function product ()
        {
             return $this->belongsTo(Product::class, 'product_id', 'product_id');
        }
}

Each Variation is belongs to a Product Model.

And on the other hand VariationAttribute is like :

class VariationAttribute extends Model
{
    protected $table = 'variation_attribute';
    protected $primaryKey = 'va_id';
    protected $fillable = ['value', 'attribute_id'];

    public $timestamps = FALSE;

    public function value()
    {
        return $this->belongsTo(AttributeOption::class, 'value', 'attribute_option_id');
    }

    public function attribute()
    {
        return $this->belongsTo(Attribute::class, 'attribute_id', 'attribute_id');
    }
}

As you can see there is a OneToMany relation between them.

In fact each Variation is a combination of some attributes that can have a value.

For example some records of variations table can be like this :

+-------+--------------+--------------+-------+
| va_id | variation_id | attribute_id | value |
+-------+--------------+--------------+-------+
|    28 |            6 |           12 |    11 |
|    29 |            6 |           29 |    57 |
|    30 |            7 |           12 |    12 |
|    31 |            7 |           29 |    58 |
+-------+--------------+--------------+-------+

Means that variation with number 6 is a combination of attributes by id of 12 (that have value 11) and 29 (that have value 57).

what I want to do is when creation of a new variation for a specific product.

Suppose client sent an array of attributes and their values as attributes like this :

[
 12 => 11
 29 => 57
]

before insert , I want to check whether is a variation exactly with same attribute and value or not??

what I wrote to insert attributes of a new variations is :

$variations = $request->get('variations');
collect($variations)->each(function ($var) {

    \DB::transaction(function () use ($var) {

        $variation = Variation::find($var['variation_id']);

        if (!empty($var['attributes'])) {

            $variation->attributes()->delete();

            foreach ($var['attributes'] as $attribute_id => $value) {
                $variation->attributes()->create(compact('attribute_id', 'value'));
            }
    }
}

If someone has a solution, give it.

11 Apr
1 year ago

ahmadbadpey started a new conversation Prevent Adding Automatically Translations Relation To Responded Result

I used https://github.com/dimsav/laravel-translatable package to make translatable my eloquent models.

In the other hand, I'm using [dingo api][1] laravel package.

Now suppose I have an Attribute model that should be translatable. in this case my model is like :

namespace Modules\Product\Entities;

use Modules\Product\Entities\ProAttr;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Attribute extends Model
{
    use \Dimsav\Translatable\Translatable;
    use SoftDeletes;

    protected $primaryKey = 'attribute_id';

    public $translatedAttributes = ['title'];
    protected $fillable = ['name', 'attribute_group_id', 'creator', 'type'];


    public function options()
    {
        return $this->hasMany(AttributeOption::class, 'attribute_id', 'attribute_id');
    }

}

Furthermore, I used a method to return success response that is customized like this :

public function successResponse($data = null)
{
    return new \Dingo\Api\Http\Response($data ?
        ['success' => true , 'result' => $data] : ['success' => true]);
}

As you can see I used \Dingo\Api\Http\Response to return responses.

Now when I call Attribute model for example in a controller method and want to respond result like this :

public function add_variation(Request $request, Product $product)
    {
        $attributes = Attribute::get();

        return $this->successResponse($attributes);
    }

Always in the result for each Attribute there is translations property that is contain all translated properties like this :

{
    "success": true,
    "result": [
        {
            "attribute_id": 12,
            "name": "simcard_count",
            "attribute_group_id": 5,
            "type": "select",
            "creator": 1,
            "created_at": "2018-03-29 12:46:33",
            "updated_at": "2018-03-29 12:46:33",
            "deleted_at": null,
            "translations": [
                {
                    "id": 17,
                    "attribute_id": 12,
                    "title": "تعداد سیم کارت",
                    "locale": "fa"
                },
                {
                    "id": 18,
                    "attribute_id": 12,
                    "title": "simcard count",
                    "locale": "en"
                }
            ],
            "title": "تعداد سیم کارت"
        }
    ]
}

But if I remove \Dingo\Api\Http\Response from response method and method be like this :

public function successResponse($data = null)
    {
        return $data ? ['success' => true , 'result' => $data] : ['success' => true];
    }

problem be solved and tranlations removed from result.

what is problem? [1]: https://github.com/dingo/api

14 Feb
1 year ago

ahmadbadpey started a new conversation Accessor Considered As Foreign Key Defined In OneToMany Relations

My User model have these fields :

user_id
username
name
family
supervisor

And in that model I defined an accesssor that same name as supervisor attribute like this (because I want to return supervisor user as an User object and not a simple id):

public function getSupervisorAttribute($value)
{
    return is_null($value) ? null : User::select('user_id', 'name', 'family')->find($value);
}

In the other hand there is a OneToMany relationship like this:

public function child()
{
    return $this->hasMany(self::class, 'supervisor', 'user_id');
}

Now each time I call child() relation it return Illegal offset type error. seems that supervisor field does not recognized in second argument of hasMany method.

There is any way to solve this problem Without having to change accessor name.

13 Feb
1 year ago

ahmadbadpey started a new conversation Illegal Offset Type Error On Fetching A Relations To Self Class In Laravel

My User model is like this :

class User extends Authenticatable
{
    protected $primaryKey = 'user_id';
    protected $fillable = [
        'username',
        'password',
        'name',
        'family',
        'supervisor'
    ];

    public function children()
    {
        return $this->hasMany(\App\User::class, 'supervisor', 'user_id')->with('children');
    }

}

As you can see there a supervisor column that specify parent of a user.

Now to fetch all children of user models that have supervisor= null, I wrote this :

return User::with('children')->whereNull('supervisor')->get();

but it return this error always :

PHP Warning:  Illegal offset type in D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\HasOneOrMany.php on line 168

Table users have these data :

+---------+-------------+---------+--------------+------------+
| user_id |  username   |  name   |    family    | supervisor |
+---------+-------------+---------+--------------+------------+
|       1 | 09139616246 | ahmad   | badpey       | null       |
|       7 | alinasiri   | ali     | nasiri arani | 1          |
|       8 | zahedi      | mostafa | zahedi       | 1          |
|       9 | hsan        | hasan   | ghanati      | 8          |
+---------+-------------+---------+--------------+------------+

Even I tried solution here but same error occurred.

11 Feb
1 year ago

ahmadbadpey left a reply on Make A Hierarchical Structure For Instances Of A Model In Laravel

@burlresearch , if you are with https://github.com/etrepat/baum laravel package,it is an implementation of the Nested Set pattern for Laravel 5's Eloquent ORM.

it has a toHierarchy method that returns a nested collection representing the queried tree like this for example :

[
  ['id' => 1, 'name' => 'TV & Home Theather'],
  ['id' => 2, 'name' => 'Tablets & E-Readers'],
  ['id' => 3, 'name' => 'Computers', 'children' => [
    ['id' => 4, 'name' => 'Laptops', 'children' => [
      ['id' => 5, 'name' => 'PC Laptops'],
      ['id' => 6, 'name' => 'Macbooks (Air/Pro)']
    ]],
    ['id' => 7, 'name' => 'Desktops', 'children' => [
      // These will be created
      ['name' => 'Towers Only'],
      ['name' => 'Desktop Packages'],
      ['name' => 'All-in-One Computers'],
      ['name' => 'Gaming Desktops']
    ]]
    // This one, as it's not present, will be deleted
    // ['id' => 8, 'name' => 'Monitors'],
  ]],
  ['id' => 9, 'name' => 'Cell Phones']
];

Now I want when call my hierarchical it return an structure like that for User model

ahmadbadpey started a new conversation Argument 2 Passed To Dingo\Api\Auth\Provider\JWT::authenticate() Must Be An Instance Of Dingo\Api\Routing\Route

I'm using dingo/api along with nWidart/laravel-modules packages to create an API.

We know that in nwidart package each Module can it's model and service provider.

Now suppose we have a PriceList model like this :

class PriceList extends Model
{
    protected $primaryKey = 'price_list_id';

    protected $fillable = ['title', 'name', 'country', 'rate', 'creator'];

    public function __construct(array $attributes = [])
    {
        $attributes['creator'] = app('Dingo\Api\Auth\Auth')->user()->user_id;
        parent::__construct($attributes);
    }
}

Then in the PriceListServiceProvider of that module, for some reason , I need to fetch a specific price list and store id of that in config. For that I wrote these:

class PriceListServiceProvider extends ServiceProvider
{
    protected $defer = FALSE;

    public function boot()
    {
        $this->registerTranslations();
        $this->registerConfig();
        $this->registerViews();
        $this->registerFactories();
        $this->loadMigrationsFrom(__DIR__ . '/../Database/Migrations');

        $priceList =
            PriceList::where('rate', 'toman')->orderBy('created_at', 'asc')->first();

        if ($priceList) {
            $defaultPriceList = $priceList->price_list_id;
        }

        config('pricelist.default',$defaultPriceList);

    }

}

But after running project I got this error every time :

Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Argument 2 passed to Dingo\Api\Auth\Provider\JWT::authenticate() must be an instance of Dingo\Api\Routing\Route, null given, called in D:\wamp\www\zarsam-app\vendor\dingo\api\src\Auth\Auth.php on line 82 in file D:\wamp\www\zarsam-app\vendor\dingo\api\src\Auth\Provider\JWT.php on line 41
Stack trace:
  1. Symfony\Component\Debug\Exception\FatalThrowableError->() D:\wamp\www\zarsam-app\vendor\dingo\api\src\Auth\Provider\JWT.php:41
  2. Dingo\Api\Auth\Provider\JWT->authenticate() D:\wamp\www\zarsam-app\vendor\dingo\api\src\Auth\Auth.php:82
  3. Dingo\Api\Auth\Auth->authenticate() D:\wamp\www\zarsam-app\vendor\dingo\api\src\Auth\Auth.php:151
  4. Dingo\Api\Auth\Auth->getUser() D:\wamp\www\zarsam-app\vendor\dingo\api\src\Auth\Auth.php:166
  5. Dingo\Api\Auth\Auth->user() D:\wamp\www\zarsam-app\Modules\PriceList\Entities\PriceList.php:18
  6. Modules\PriceList\Entities\PriceList->__construct() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:1450
  7. Illuminate\Database\Eloquent\Model->__callStatic() D:\wamp\www\zarsam-app\app\Providers\AppServiceProvider.php:37
  8. App\Providers\AppServiceProvider->boot() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:29
  9. call_user_func_array() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:29
 10. Illuminate\Container\BoundMethod->Illuminate\Container\{closure}() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:87
 11. Illuminate\Container\BoundMethod->callBoundMethod() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:31
 12. Illuminate\Container\BoundMethod->call() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Container\Container.php:549
 13. Illuminate\Container\Container->call() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:792
 14. Illuminate\Foundation\Application->bootProvider() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:775
 15. Illuminate\Foundation\Application->Illuminate\Foundation\{closure}() [internal]:0
 16. array_walk() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:776
 17. Illuminate\Foundation\Application->boot() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\BootProviders.php:17
 18. Illuminate\Foundation\Bootstrap\BootProviders->bootstrap() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:213
 19. Illuminate\Foundation\Application->bootstrapWith() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:162
 20. Illuminate\Foundation\Http\Kernel->bootstrap() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:146
 21. Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter() D:\wamp\www\zarsam-app\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:116
 22. Illuminate\Foundation\Http\Kernel->handle() D:\wamp\www\zarsam-app\public\index.php:55

And if I remove those lines, no errors occurred.

10 Feb
1 year ago

ahmadbadpey left a reply on Make A Hierarchical Structure For Instances Of A Model In Laravel

@burlresearch, what about nested relations? my structure may have unlimited nested levels like this :

[ { user_id : 1, supervisor: { user_id : 2, supervisor: { user_id : 3, supervisor: { user_id : 4, supervisor: { user_id :5 ....... } } } } } ]

ahmadbadpey started a new conversation Make A Hierarchical Structure For Instances Of A Model In Laravel

In the User model I added a column named supervisor that can hold another user_id for each user.

In fact each User can have a supervisor user that specified by that column.

For that I added a hierarchical method like this :

    protected function hierarchical($users)
    {
        $users = $users->toArray();

        $nestedKeys = array();

        foreach ($users as $key => $node) {
            $supervisor_id = $node['supervisor']['user_id'];
            $index         = array_search($supervisor_id, array_column($users, 'user_id'));

            if (!is_null($supervisor_id) && $index != -1) {

                $users[$index]['children'][] = $node;

                $nestedKeys[] = $node['user_id'];
            }
        }

        return $users;
    }

That method accepts a $users that is a collection comes from User::all() for example, that created a response like this But the result is not what I want:

[
    {
        "user_id": 1,
        "supervisor": null,
        "name": "ahmad",
        "family": "badpey",
        "full_name": "ahmad badpey",
        "children": [
            {
                "user_id": 7,
                "supervisor": {
                    "user_id": 1,
                    "name": "ahmad",
                    "family": "badpey",
                    "full_name": "ahmad badpey"
                },
                "name": "ali",
                "family": "nasiri arani",
                "full_name": "ali nasiri arani"
            },
            {
                "user_id": 8,
                "supervisor": {
                    "user_id": 1,
                    "name": "ahmad",
                    "family": "badpey",
                    "full_name": "ahmad badpey"
                },
                "name": "مصطفی",
                "family": "زاهدی",
                "full_name": "مصطفی زاهدی"
            }
        ]
    },
    {
        "user_id": 7,
        "supervisor": {
            "user_id": 1,
            "name": "ahmad",
            "family": "badpey",
            "full_name": "ahmad badpey"
        },
        "name": "ali",
        "family": "nasiri arani",
        "full_name": "ali nasiri arani"
    },
    {
        "user_id": 8,
        "supervisor": {
            "user_id": 1,
            "name": "ahmad",
            "family": "badpey",
            "full_name": "ahmad badpey"
        },
        "name": "مصطفی",
        "family": "زاهدی",
        "full_name": "مصطفی زاهدی",
        "children": [
            {
                "user_id": 9,
                "supervisor": {
                    "user_id": 8,
                    "name": "مصطفی",
                    "family": "زاهدی",
                    "full_name": "مصطفی زاهدی"
                },
                "name": "حسین",
                "family": "قناتی",
                "full_name": "حسین قناتی"
            }
        ]
    },
    {
        "user_id": 9,
        "supervisor": {
            "user_id": 8,
            "name": "مصطفی",
            "family": "زاهدی",
            "full_name": "مصطفی زاهدی"
        },
        "name": "حسین",
        "family": "قناتی",
        "full_name": "حسین قناتی"
    }
]

As you can see created structure is not correct because subordinate users comes Separate again.

What is the best approch to create what I want for model with similar structure?

30 Jan
1 year ago

ahmadbadpey left a reply on Rate Limiting Does Not Work In Dingo Laravel

yes , I always used it and what I showed in previous answer was an output of that.

ahmadbadpey left a reply on Rate Limiting Does Not Work In Dingo Laravel

No, I'm using laravel.

since I'm using dingo api package when I run php artisan api:routes output is like this that is not included any middlewares :

| Host              | Method    | URI                                                                | Name                                     | Action
                      | Protected | Version(s) | Scope(s) | Rate Limit |
+-------------------+-----------+--------------------------------------------------------------------+------------------------------------------+----------------------------------------------------------
----------------------+-----------+------------+----------+------------+
| api.zarsystem.dev | GET|HEAD  | /v1/admin/branches/datatable                                       | admin.branches.datatable                 | Modules\Branch\Http\Controllers\[email protected]
e                     | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/branches/{branch}/addUser                                | admin.branches.add_user                  | Modules\Branch\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/branches/{branch}/removeUser                             | admin.branches.remove_user               | Modules\Branch\Http\Controllers\[email protected]
er                    | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/branches/{branch}/removeRoleFromUser                     | admin.branches.remove_role_from_user     | Modules\Branch\Http\Controllers\[email protected]
leFromUser            | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/branches/{branch}/users/datatable                        | admin.branches.users_datatable           | Modules\Branch\Http\Controllers\[email protected]
ersDatatable          | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/branches/{branch}/user/{user}                            | admin.branches.user                      | Modules\Branch\Http\Controllers\[email protected]
erShow                | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT       | /v1/admin/branches/{branch}/user/{user}                            | admin.branches.user.update               | Modules\Branch\Http\Controllers\[email protected]
erUpdate              | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/branches/{branch}/addWarehouse                           | admin.branches.add_warehouse             | Modules\Branch\Http\Controllers\[email protected]
ouse                  | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/branches/{branch}/removeWarehouse                        | admin.branches.remove_warehouse          | Modules\Branch\Http\Controllers\[email protected]
rehouse               | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/branches/{branch}/warehouses                             | admin.branches.warehouses                | Modules\Branch\Http\Controllers\[email protected]
es                    | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/branches/{branch}/warehouses/datatable                   | admin.branches.warehouses_datatable      | Modules\Branch\Http\Controllers\[email protected]
es_datatable          | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/branches                                                 | admin.branches.index                     | Modules\Branch\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/branches                                                 | admin.branches.store                     | Modules\Branch\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/branches/{branch}                                        | admin.branches.show                      | Modules\Branch\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT|PATCH | /v1/admin/branches/{branch}                                        | admin.branches.update                    | Modules\Branch\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | DELETE    | /v1/admin/branches/{branch}                                        | admin.branches.destroy                   | Modules\Branch\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/packages/datatable                                       | admin.packages.datatable                 | Modules\Package\Http\Controllers\[email protected]
ble                   | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/packages                                                 | admin..packages.index                    | Modules\Package\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/packages                                                 | admin..packages.store                    | Modules\Package\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/packages/{package}                                       | admin..packages.show                     | Modules\Package\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT|PATCH | /v1/admin/packages/{package}                                       | admin..packages.update                   | Modules\Package\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | DELETE    | /v1/admin/packages/{package}                                       | admin..packages.destroy                  | Modules\Package\Http\Controllers\[email protected]
y                     | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/price_lists/datatable                                    | admin.price_lists.datatable              | Modules\PriceList\Http\Controllers\[email protected]
tatable               | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/price_lists/{price_list}/addPrices                       | admin.price_lists.addPrices              | Modules\PriceList\Http\Controllers\[email protected]
dPrices               | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/price_lists/{price_list}/prices                          | admin.price_lists.prices                 | Modules\PriceList\Http\Controllers\[email protected]
ices                  | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT       | /v1/admin/price_lists/{price_list}/discounts                       | admin.price_lists.update_discounts       | Modules\PriceList\Http\Controllers\[email protected]
date_discounts        | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/price_lists/{price_list}/discounts                       | admin.price_lists.discounts              | Modules\PriceList\Http\Controllers\[email protected]
scounts               | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/price_lists/{price_list}/formal_invoice/preview          | admin.price_lists.formal_invoice.preview | Modules\PriceList\Http\Controllers\FormalInvoiceControlle
[email protected]             | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/price_lists/{price_list}/formal_invoice                  | admin.formal_invoice.index               | Modules\PriceList\Http\Controllers\FormalInvoiceControlle
[email protected]               | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/price_lists/{price_list}/formal_invoice                  | admin.formal_invoice.store               | Modules\PriceList\Http\Controllers\FormalInvoiceControlle
[email protected]               | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/price_lists/{price_list}/formal_invoice/{formal_invoice} | admin.formal_invoice.show                | Modules\PriceList\Http\Controllers\FormalInvoiceControlle
[email protected]                | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT|PATCH | /v1/admin/price_lists/{price_list}/formal_invoice/{formal_invoice} | admin.formal_invoice.update              | Modules\PriceList\Http\Controllers\FormalInvoiceControlle
[email protected]              | Yes       | v1         |          |            |
| api.zarsystem.dev | DELETE    | /v1/admin/price_lists/{price_list}/formal_invoice/{formal_invoice} | admin.formal_invoice.destroy             | Modules\PriceList\Http\Controllers\FormalInvoiceControlle
[email protected]             | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/price_lists                                              | admin..price_lists.index                 | Modules\PriceList\Http\Controllers\[email protected]
dex                   | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/price_lists                                              | admin..price_lists.store                 | Modules\PriceList\Http\Controllers\[email protected]
ore                   | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/price_lists/{price_list}                                 | admin..price_lists.show                  | Modules\PriceList\Http\Controllers\[email protected]
ow                    | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT|PATCH | /v1/admin/price_lists/{price_list}                                 | admin..price_lists.update                | Modules\PriceList\Http\Controllers\[email protected]
date                  | Yes       | v1         |          |            |
| api.zarsystem.dev | DELETE    | /v1/admin/price_lists/{price_list}                                 | admin..price_lists.destroy               | Modules\PriceList\Http\Controllers\[email protected]
stroy                 | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/products/search                                          | admin.products.search                    | Modules\Product\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/products/datatable                                       | admin.products.datatable                 | Modules\Product\Http\Controllers\[email protected]
ble                   | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/products/{product}/prices                                | admin.products.prices                    | Modules\Product\Http\Controllers\[email protected]
ces                   | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/products/{product}/priceHistory/{price_list_id?}         | admin.products.priceHistory              | Modules\Product\Http\Controllers\[email protected]
istory                | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/products/{product}/correctStock                          | admin.products.correctStock              | Modules\Product\Http\Controllers\[email protected]
tStock                | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/products/{product}/transfer                              | admin.products.transfer                  | Modules\Product\Http\Controllers\[email protected]
er                    | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/products/{product}/movements/datatable                   | admin.products.movements_datatable       | Modules\Product\Http\Controllers\[email protected]
nts_datatable         | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/products/{product}/warehouses                            | admin.products.warehouses                | Modules\Product\Http\Controllers\[email protected]
uses                  | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/products/{product}/warehouses/datatable                  | admin.products.warehouses_datatable      | Modules\Product\Http\Controllers\[email protected]
uses_datatable        | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/products/{product}/stockTotal                            | admin.products.stockTotal                | Modules\Product\Http\Controllers\[email protected]
otal                  | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/products                                                 | admin..products.index                    | Modules\Product\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/products                                                 | admin..products.store                    | Modules\Product\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/products/{product}                                       | admin..products.show                     | Modules\Product\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT|PATCH | /v1/admin/products/{product}                                       | admin..products.update                   | Modules\Product\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | DELETE    | /v1/admin/products/{product}                                       | admin..products.destroy                  | Modules\Product\Http\Controllers\[email protected]
y                     | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/{type}/tag/products                                      | admin.tag.products                       | Modules\Tag\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | PATCH     | /v1/admin/{type}/tag/move                                          | admin.tag.move                           | Modules\Tag\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/{type}/tag/tagsSelect                                    | admin.tag.tagsSelect                     | Modules\Tag\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/{type}/tag                                               | admin.tag.index                          | Modules\Tag\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/{type}/tag                                               | admin.tag.store                          | Modules\Tag\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/{type}/tag/{tag}                                         | admin.tag.show                           | Modules\Tag\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT|PATCH | /v1/admin/{type}/tag/{tag}                                         | admin.tag.update                         | Modules\Tag\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | DELETE    | /v1/admin/{type}/tag/{tag}                                         | admin.tag.destroy                        | Modules\Tag\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/warehouses/types/datatable                               | admin.warehouses.types.datatable         | Modules\Warehouse\Http\Controllers\WarehouseTypeControlle
[email protected]           | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/warehouses/types                                         | admin.types.index                        | Modules\Warehouse\Http\Controllers\WarehouseTypeControlle
[email protected]               | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/warehouses/types                                         | admin.types.store                        | Modules\Warehouse\Http\Controllers\WarehouseTypeControlle
[email protected]               | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/warehouses/types/{type}                                  | admin.types.show                         | Modules\Warehouse\Http\Controllers\WarehouseTypeControlle
[email protected]                | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT|PATCH | /v1/admin/warehouses/types/{type}                                  | admin.types.update                       | Modules\Warehouse\Http\Controllers\WarehouseTypeControlle
[email protected]              | Yes       | v1         |          |            |
| api.zarsystem.dev | DELETE    | /v1/admin/warehouses/types/{type}                                  | admin.types.destroy                      | Modules\Warehouse\Http\Controllers\WarehouseTypeControlle
[email protected]             | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/warehouses/datatable                                     | admin.warehouses.datatable               | Modules\Warehouse\Http\Controllers\[email protected]
tatable               | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/warehouses/search                                        | admin.warehouses.search                  | Modules\Warehouse\Http\Controllers\[email protected]
arch                  | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/warehouses/{warehouse}/products                          | admin.warehouses.products                | Modules\Warehouse\Http\Controllers\[email protected]
oducts                | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/warehouses/{warehouse}/products/datatable                | admin.warehouses.products_datatable      | Modules\Warehouse\Http\Controllers\[email protected]
oducts_datatable      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/warehouses/{warehouse}/products/search                   | admin.warehouses.products.search         | Modules\Warehouse\Http\Controllers\[email protected]
archInProducts        | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/warehouses/{warehouse}/movements/datatable               | admin.warehouses.movements_datatable     | Modules\Warehouse\Http\Controllers\[email protected]
vements_datatable     | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/warehouses/{warehouse}/addUser                           | admin.warehouses.add_user                | Modules\Warehouse\Http\Controllers\[email protected]
dUser                 | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/warehouses/{warehouse}/removeUser                        | admin.warehouses.remove_user             | Modules\Warehouse\Http\Controllers\[email protected]
moveUser              | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/warehouses/{warehouse}/removeRoleFromUser                | admin.warehouses.remove_role_from_user   | Modules\Warehouse\Http\Controllers\[email protected]
moveRoleFromUser      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/warehouses/{warehouse}/users/datatable                   | admin.warehouses.users_datatable         | Modules\Warehouse\Http\Controllers\[email protected]
rehouseUsersDatatable | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/warehouses/{warehouse}/user/{user}                       | admin.warehouses.user                    | Modules\Warehouse\Http\Controllers\[email protected]
rehouseUserShow       | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT       | /v1/admin/warehouses/{warehouse}/user/{user}                       | admin.warehouses.user.update             | Modules\Warehouse\Http\Controllers\[email protected]
rehouseUserUpdate     | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/warehouses                                               | admin.warehouses.index                   | Modules\Warehouse\Http\Controllers\[email protected]
dex                   | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/warehouses                                               | admin.warehouses.store                   | Modules\Warehouse\Http\Controllers\[email protected]
ore                   | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/warehouses/{warehouse}                                   | admin.warehouses.show                    | Modules\Warehouse\Http\Controllers\[email protected]
ow                    | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT|PATCH | /v1/admin/warehouses/{warehouse}                                   | admin.warehouses.update                  | Modules\Warehouse\Http\Controllers\[email protected]
date                  | Yes       | v1         |          |            |
| api.zarsystem.dev | DELETE    | /v1/admin/warehouses/{warehouse}                                   | admin.warehouses.destroy                 | Modules\Warehouse\Http\Controllers\[email protected]
stroy                 | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/auth/checkUser                                                 |                                          | App\Http\Controllers\Auth\[email protected]
                      | No        | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/auth/verifyCode                                                |                                          | App\Http\Controllers\Auth\[email protected]
                      | No        | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/auth/signOut                                                   |                                          | App\Http\Controllers\Auth\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/role/savePerms                                           | admin.savePerms                          | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/role/allPerms                                            | admin.allPerms                           | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/role/permissions                                         | admin.permissions                        | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/role/group/{group}                                       | admin.role.filter_group                  | App\Http\Controllers\[email protected]_group
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/role/datatable                                           | admin.role.datatable                     | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/role/{role}/perms                                        | admin.role.perms                         | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/role/groups                                              | admin.role.groups                        | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/role                                                     | admin.role.index                         | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/role                                                     | admin.role.store                         | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/role/{role}                                              | admin.role.show                          | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT|PATCH | /v1/admin/role/{role}                                              | admin.role.update                        | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | DELETE    | /v1/admin/role/{role}                                              | admin.role.destroy                       | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/user/attachRoles/{user}                                  | admin.attachRoles                        | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/user/supervisors                                         | admin.supervisors                        | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/user/datatable                                           | admin.user.datatable                     | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/user/{user}/branches/datatable                           | admin.user.branches_datatable            | App\Http\Controllers\[email protected]_datatable
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/user/search                                              | admin.user.search                        | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/user                                                     | admin.user.index                         | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | POST      | /v1/admin/user                                                     | admin.user.store                         | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/user/{user}                                              | admin.user.show                          | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | PUT|PATCH | /v1/admin/user/{user}                                              | admin.user.update                        | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | DELETE    | /v1/admin/user/{user}                                              | admin.user.destroy                       | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/admin/modules                                                  | admin.modulesList                        | App\Http\Controllers\[email protected]
                      | Yes       | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/getCities/{province}                                           | getCities                                | App\Http\Controllers\[email protected]
                      | No        | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/getProvinces                                                   | getProvinces                             | App\Http\Controllers\[email protected]
                      | No        | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/getCountries                                                   | getCountries                             | App\Http\Controllers\[email protected]
                      | No        | v1         |          |            |
| api.zarsystem.dev | GET|HEAD  | /v1/getRates                                                       | getRates                                 | App\Http\Controllers\[email protected]
                      | No        | v1         |          |            |
+-------------------+-----------+--------------------------------------------------------------------+------------------------------------------+----------------------------------------------------------
----------------------+-----------+------------+----------+------------+
29 Jan
1 year ago

ahmadbadpey started a new conversation Navigate On Images Of A Product In A Telegram Bot

I'm working on a telegram bot shop via https://github.com/php-telegram-bot/core in laravel.

In this app , each Product has many images that path of them is stored on th DB.

Now I want when send details of a product , images of that shown one by one that user can navigate them via a prev and next inline keyboard. like this picture :

enter image description here

For that after show all products in the shop as a inline query and after use choose one of them , On Chosen inline result Command, I get a product Id and fetch first image of that from DB like this :

class ChoseninlineresultCommand extends SystemCommand
    {
    public function execute ()
    {
        $chosenInlineResult   = $this->getChosenInlineResult();
        $chosenInlineResultId = $product_id = $chosenInlineResult->getResultId();
        $chat_id              = $chosenInlineResult->getFrom()->getId();

        $product = Product::findOrFail($product_id);

        $picture = $product->images->first();

        $keyboard = KeyboardController::showProductKeyboard($product_id, $chat_id);

        $result = view('show-product', compact('product','picture'))->render();

        Request::sendMessage([
            'chat_id'      => $chat_id,
            'text'         => $result,
            'reply_markup' => $keyboard,
            'parse_mode'   => 'HTML'
        ]);
    }
    }

Also showProductKeyboard of KeyboardController is like this :

    static public function showProductKeyboard ($product_id, $user_id)
    {

        $inlineKeyboard = new InlineKeyboard([]);
        $inlineKeyboard->addRow(new InlineKeyboardButton([
            'text'          => ' previous picture ⬅️️',
            'callback_data' => 'prev_pic'
        ]), new InlineKeyboardButton([
            'text'          => '➡️ next picture ',
            'callback_data' => 'next_pic'
        ]));

        return $inlineKeyboard;
    }

And finally show-product blade is simple as :

?️ <b>{{$product->title}}</b>

✅ <b>{{str_limit(strip_tags($product->desc), 50)}}</b>

? <b>{{number_format($product->price)}}</b> dollor

<a href="{{config('app.url').'/upload/'. $picture}}"> Picture</a>

Problem is that I do not know how can I implement what I want .

ahmadbadpey started a new conversation Rate Limiting Does Not Work In Dingo Laravel

According to this guidance ,I added a throttle functionality to a specific route in my laravel project like this :

$api->group(['prefix' => 'auth'], function ($api) {
    $api->post('checkUser', ['middleware' => 'api.throttle', 'limit' => 3, 'expires' => 20, 'uses' => 'Auth\[email protected]']);
});

As you can see I added a throttle , limit of 3 with an expiration time of **20** minutes for this specific route.

But even I request that rout more than 3 times, no things occurred.

I do not know what is problem or is need any more step or not?

18 Jan
1 year ago

ahmadbadpey started a new conversation Send Extra Arguments To TriggerCommand In Laravel Telegram Bot

I'm using irazasyed/telegram-bot-sdk/ laravel package to make a telegram bot for a simple shopping.

I used inline queries to show many product until users can pick what those want.

to show a list of products I wrote this :

public function Webhook ()
{
    $update = Telegram::commandsHandler(true);


if ($update->isType('inline_query')) {
                $inlineQuery   = $update->getInlineQuery();
                $inlineQueryId = $inlineQuery->getId();

                $query = $inlineQuery->getQuery();

                $category    = Category::where('cat_alias', $query)->first();
                $catProducts = $category->products;

                if (!empty($catProducts)) {
                    $results = array ();

                    foreach ($catProducts as $product) {
                        $results[] = array (
                            'type'         => 'article',
                            'id'           => $product->product_id,
                            'title'        =>  $product->title
                        );
                    }


                    Telegram::answerInlineQuery([
                        'inline_query_id' => $inlineQueryId,
                        'cache_time'      => 0,
                        'results'         => $results
                    ]);


                }


            }
else if ($update->isType('chosen_inline_result')) {


                $chosenInlineResult   = $update->getChosenInlineResult();
                $chosenInlineResultId = $product_id = $chosenInlineResult->getResultId();


                Telegram::triggerCommand('show_product');

            }

}

As you can see in the second else if I checked whether update message is type of chosen_inline_result or not? if it is , I fetch the ID of selected product and called another defined Command named show_product .

But whenever it called I got this error:

Type error: Argument 2 passed to Telegram\Bot\Api::triggerCommand() must be an instance of Telegram\Bot\Objects\Update, none given

Even when send $update parameter to triggerCommand as second paramter I got this error in this case:

 Call to a member function getText() on null {"exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0):

I want in fact, when a user chosen an option, get the product ID and send it to show_product defined and manage other jobs there.

06 Jan
1 year ago

ahmadbadpey started a new conversation Access To Other Relations Via Intermediate Table Models

I'm working on a role based system in laravel.

Suppose we have three models:

User :

class User extends Authenticatable
{
    public function roles()
    {
        return $this->belongsToMany(\App\Role::class, 'role_user', 'user_id', 'role_id')->using(UserRole::class);
    }

}

Role :

class Role extends EntrustRole
{
    public function users()
    {
        return $this->belongsToMany(\App\User::class, 'role_user', 'role_id', 'user_id')->using(UserRole::class);
    }
}

Branch :

class Branch extends Model
{
    public function user_roles()
    {
        return $this->morphMany(\App\UserRole::class, 'roleable');
    }
}

Each User can have some roles on different Branches(or do not working on any Branch). because of that I changed role_user table to a Model like this :

class UserRole extends Pivot
{
    protected $table = 'role_user';

    public function roleable()
    {
        return $this->morphTo();
    }

    public function role()
    {
        $this->belongsTo(Role::class, 'role_id', 'role_id');
    }

    public function user()
    {
        $this->belongsTo(User::class, 'user_id', 'user_id');
    }
}

That have this structure :

+---------+---------+-------------+--------------------------------+
| user_id | role_id | roleable_id |         roleable_type          |
+---------+---------+-------------+--------------------------------+
|       1 |       2 | null        | null                           | 
|       1 |       3 | null        | null                           | 
|       8 |       3 | 1           | Modules\Branch\Entities\Branch |
+---------+---------+-------------+--------------------------------+

Now I want to get all Users that works on a specific branch via relations defined in those models. But I do not know.

I want to define a users() relation on Branch model that do what I want. But I do not know how?

03 Jan
1 year ago

ahmadbadpey started a new conversation Choose To Include Or No Translated Fields To Model In Dimsav/laravel-translatable And Fractal

I'm using dimsav/laravel-translatable laravel package to make an api (written in dingo/laravel and spatie/laravel-fractal) translatable.

Suppose to save a translatable model I used this :

$warehouse = Warehouse::create([
    'type' => 'technical',
    'city' => 'manchster',
    'en'   => ['name' => 'warehouse 1','desc'=>'this is Description'],
    'fa'   => ['name' => 'انبار 1','desc'=>'توضیحات انبار']
]);

As you can see I sent translated fields as en and fa arrays.

Now all things that I want to do is when fetching a model , it returned as same format automatically.

I readed this Issue that is similar to my Question that suggested to use $warehouse->getTranslationsArray(); method to return translated fields. but this can return only translated fields while I want response format was like this (included other fields that do not be translate):

[
    'type' => 'technical',
    'city' => 'manchster',
    'en'   => ['name' => 'warehouse 1','desc'=>'this is Description'],
    'fa'   => ['name' => 'انبار 1','desc'=>'توضیحات انبار']
]

Of course we know that it converts to a json formatted text like this :

    {
        'type' : 'technical',
        'city' : 'manchster',
        'en'   : {'name' : 'warehouse 1','desc':'this is Description'},
        'fa'   : ['name' : 'انبار 1','desc':'توضیحات انبار'}
    }

Another problem is that beacause I used fractal transformers to return warehouse models I want to be able to choose that to return translated fields or no.

WarehouseTransformer is like this :

class WarehouseTransformer extends TransformerAbstract
{
   
    protected $availableIncludes = [
        'translations'
    ];

    
    public function transform(Warehouse $warehouse)
    {
        $transforms = [
            'warehouse_id'          => $warehouse->warehouse_id,
            'type'                 => $warehouse->type,
            'city'           => $warehouse->city,
        ];

       
        return $transforms;
    }

    
    public function includeTranslations(Warehouse $warehouse)
    {
        $translations = $warehouse->translations;

        /***
        I WANT ATTACH ARRAY OF TRANSLATIONS RELATION TO CURRENT MODEL HERE.
        ****/
    }
}

After that any time I request for example /warehouse/1 it return :

[
  'type' => 'technical',
  'city' => 'Manchester',
  'name' => 'warehouse 1', //BASED ON CURRENT LOCALE
  'desc' => 'this is Description' //BASED ON CURRENT LOCALE
]

And if I request /warehouse/1?include=translations it return :

    [
        'type' => 'technical',
        'city' => 'manchster',
        'en'   => ['name' => 'warehouse 1','desc'=>'this is Description'],
        'fa'   => ['name' => 'انبار 1','desc'=>'توضیحات انبار']
    ]

But from now on, I do not know what to do?

02 Jan
1 year ago

ahmadbadpey started a new conversation Validate Translatable Fields With Unique Rule In Dimsav/laravel-translatable

I'm using dimsav/laravel-translatable to make an api translatable.

I have three locale fa, en and ar and there is a WarehouseType model like this :

class WarehouseType extends Model
{
    use \Dimsav\Translatable\Translatable;

    protected $fillable = ['name'];

    public $translatedAttributes = ['title'];    
}

On the other hand I have created a WarehouseTypeTranslation like this:

class WarehouseTypeTranslation extends Model
{
    protected $fillable = ['title'];
    public $timestamps = FALSE;
}

Now I want to validation incoming requests. for that I wrote a FormRequest like this :

public function rules()
{
    switch ($this->method()) {
        case 'POST': {
            return [
                'name'    => 'required|unique:warehouse_types',
                '*.title' => 'required|unique:warehouse_type_translations,title',
            ];
        }
    }
}

As you can see title field must be unique in the database. but I want only fa[title] be unique and be check in the DB.

With those codes I have been wrote , I got this error always :

{
    "success": false,
    "message": "422 Unprocessable Entity",
    "errors": {
        "name.title": [
            "name.title is required."
        ]
    },
    "status_code": 422
}
31 Dec
1 year ago

ahmadbadpey started a new conversation Where To Place Translations In JSON Or A Separate Table

I found that there are two common approaches to make a translatable web application in laravel and MySQL.

First uses extra table to save translatable fields. like this :

Schema::create('countries', function(Blueprint $table)
{
    $table->increments('id');
    $table->string('code');
    $table->timestamps();
});

Schema::create('country_translations', function(Blueprint $table)
{
    $table->increments('id');
    $table->integer('country_id')->unsigned();
    $table->string('name');
    $table->string('locale')->index();

    $table->unique(['country_id','locale']);
    $table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
});

dimsav/laravel-translatable package uses this approach.

On the other hand there is a json based approach that only works in MySQL 5.7 or above. as you know , in this case all translations saved on one table and field.

spatie/laravel-translatable package uses this approach.

My question is that what approach is better? in performance and speed? in Memory usage?

I'm working on a large api project that need to be translatable to three different language.

25 Dec
1 year ago

ahmadbadpey left a reply on Automatically Currency Rate Conversion In Laravel Models

@bobbybouwmann , thanks for your help. your explanation was helpful. but another issue that I have is that in my models there are many financial field. in this case do I add one accesssor for each of them ?

I was searched for l package that mange this case automatically.

ahmadbadpey started a new conversation Automatically Currency Rate Conversion In Laravel Models

I have a Product model included sale_price , purchase_price.this fields holds values as IRR (Iranian rial) currency, means that when an operator user is saving a product ,specifies Sale and Purchase prices in IRR currency in default.

Now in many situations I want to show a list of all products along with their prices that default is same currency that I stored in DB.

Then I want User can switch to another currency(for example via a combo box) and page refreshed and same list of products shown with new selected currency .

I have checked some currency exchange rate packages like laravel-swap and laravel-currency but I did not find any capability to do what I want.

Seems that one approach is define an accessor for each financial fields that uses methods of one of the mentioned packages. but it's Time-consuming if there are many fields.

On the Other hand when a user uses a currency Opposite of Default then we must to define a mutator to convert it and save in DB.

I am confused which approach should be used and what is best and common way.

22 Dec
1 year ago

ahmadbadpey left a reply on Remove Data Key From Included Attributes

@bobbybouwmann, yes if I do not use datatable all things worked fine but if I want to return a datatable formatted response it occurred.

21 Dec
1 year ago

ahmadbadpey left a reply on Remove Data Key From Included Attributes

@bobbybouwmann, as you can see in the first codes I pass false to last parameter to remove data but it does not removed. problem is really that.

ahmadbadpey started a new conversation Remove Data Key From Included Attributes

I want to use laravel-datatables-fractal for transforming server-side response using Fractal.

First I wrote a transformer for Product model like this :

class ProductTransformer extends TransformerAbstract
{
    protected $availableIncludes = [
        'prices'
    ];

    public function transform(Product $product)
    {
        $transforms = [
            'product_id'     => $product->product_id,
            'code'           => $product->code,
            'title'          => $product->title,
            'description'    => $product->description,
        ];

        return $transforms;
    }

    public function includePrices(Product $product)
    {
        $prices = $product->prices;

        return $this->collection($prices, new PriceTransformer, FALSE);
    }
}

As you can see there is an included prices attribute that uses another transformer named PriceTransformer.

And in the ProductController that makes and returns result of all products as a datatable formatted response I have a datatable method like this:

public function datatable(Request $request)
    {
        return app('datatables')->of(Product::all())
            ->setTransformer(new ProductTransformer)
//            ->setSerializer(new CustomArraySerializer())
            ->make(TRUE);
    }

Response is returned but a problem that I have is : when I want to return prices included attribute , it returned as a data attribute like this :

{
    "draw": 0,
    "recordsTotal": 8,
    "recordsFiltered": 8,
    "data": [
        {
            "product_id": 1,
            "title": "Product Title 1",
            "for_sale": true,
            "for_purchase": true,
            "changeable": false,
            "returnable": false,
            "sale_price": "40000.00",
            "purchase_price": "5000.00",
            "creator": 1,
            "created_at": "2017-12-11 12:21:49",
            "updated_at": "2017-12-14 11:55:52",
            "prices": {
                "data": [
                    {
                        "sale_price": "30000.00",
                        "created_at": "2017-12-11 12:21:49"
                    },
                    {
                        "sale_price": "40000.00",
                        "created_at": "2017-12-11 12:39:00"
                    },
                ]
            }
        },
        {
            "product_id": 11,
            "title": "Product Title 11",
            "for_sale": true,
            "for_purchase": true,
            "changeable": false,
            "returnable": false,
            "sale_price": "50000.00",
            "purchase_price": "40000.00",
            "creator": 1,
            "created_at": "2017-12-16 11:07:43",
            "updated_at": "2017-12-16 11:07:43",
            "prices": {
                "data": [
                    {
                        "sale_price": "50000.00",
                        "created_at": "2017-12-16 11:07:43"
                    }
                ]
            }
        }
    ],
    "input": {
        "include": "prices"
    }
}

I want to remove data from included attributes and they be in this format for example :

"prices": [
           {
            "sale_price": "50000.00",
            "created_at": "2017-12-16 11:07:43"
           }
          ]

Even I added a serializer (as you see in above code and is commented) with below content that I used it for all other responses and worked well :

class CustomArraySerializer extends ArraySerializer
{
    public function collection($resourceKey, array $data)
    {
        if ($resourceKey === FALSE) {
            return $data;
        }

        return ['success' => TRUE, 'result' => $data];
    }

    public function item($resourceKey, array $data)
    {
        if ($resourceKey === FALSE) {
            return $data;
        }

        return ['success' => TRUE, 'result' => $data];
    }
}

But when use it I got this error :

{
    "draw": 0,
    "recordsTotal": 8,
    "recordsFiltered": 0,
    "data": [],
    "error": "Exception Message:\n\nUndefined index: data"
}

What is problem and how can solve that ?

18 Dec
1 year ago

ahmadbadpey started a new conversation Get Total Input Stock Value In Warehouse Via Many To Many Relationship

There is a Product Model that has a ManyToMany relation to another model named Warehouse.

Product model:

class Product extends Model
{
    protected $primaryKey = 'product_id';
    protected $fillable = ['code', 'title', 'price'];
        
    public function warehouses()
    {
        return $this->belongsToMany(Warehouse::class,
                         'product_warehouse', 'product_id', 'warehouse_id')
                    ->withPivot('stock')
                    ->withTimestamps();
    }
}

Warehouse model :

class Warehouse extends Model
{
    protected $primaryKey = 'warehouse_id';

    protected $fillable = ['name'];

    public function products()
    {
        return $this->belongsToMany(Product::class, 
                        'product_warehouse', 'product_id', 'warehouse_id')
                    ->withPivot('stock')
                    ->withTimestamps();
    }
}

In the pivot table there is a stock column that holds stock of a product in a specific warehouse.

Suppose product_warehouse table is like :

+------------+--------------+-------+
| product_id | warehouse_id | stock |
+------------+--------------+-------+
|          1 |            1 |    10 |
|          2 |            1 |    30 |
|          1 |            2 |    15 |
+------------+--------------+-------+

And products table is :

+------------+-------+
| product_id | price |
+------------+-------+
| 1          | 20000 |
| 2          | 50000 |
+------------+-------+

As you can see each product has a price column.

For example in warehouse #1, beacause we have **20** of the product #1 with price **20000** (20 * 20000 = 400000) and **30** of product #2 with price **50000** (30 * 50000 = 1500000) , as a result warehouse #1 has (400000 + 1500000 = 1900000) input value stock.

Now suppose we have selected a warehouse and want to get total price of input stock. I know that should first get stocks of each products from product_warehouse table and then multiply each them in it's price and sum total of them But I do not know how can I write it with eloquent relations laravel.

10 Dec
1 year ago

ahmadbadpey started a new conversation Manage End User Defined Permissions On The Developing Level In Laravel

I'm working on a inventory system based On larvel 5.5 and I used Zizaco/entrust to manage Roles and permissions.

In that system each warehouse can have a warehouse type(or suppose as a role) for example technical , estate and etc.

Also each type can have some permissions for example transfer products to other warehouses , Unable to sell and etc.

Note that all warehouse types and their permissions define by an End user.

Now when a warehouse was created, it's type and permissions are determined too.

But we know to control access of other users that work on different types of warehouses we should use middleware like this :

'middleware' => ['ability:technical,transfer|unable_sell']

Means that a developer should be know what roles and permissions an end user is created while developing process is a separate task from end User operations.

I want in this system all things be dynamically. defining warehouse types, it's permissions and that each warehouse type what can do. but I do not know how can manage permissions defined in End User level.

08 Dec
1 year ago

ahmadbadpey started a new conversation Conditional Attributes In Fractal Laravel Transformers

I'm using Fractal laravel package as a presentation and transformation layer for complex data output.

I wrote a UserTransformer like this :

public function transform(User $user)
    {
        return [
            'user_id'            => (int)$user->user_id,
            'name'               => $user->name,
            'family'             => $user->family,
            'username'           => $user->username,
            'token'              => $user->token,
            'mobile'             => $user->mobile,
            'email'              => $user->email,
            'sex'                => $user->sex,
            'tel'                => $user->tel,
            'province'           => $user->province,
            'city'               => $user->city,
            'picture'            => $user->picture,
            'birthday'           => $user->birthday,
            'wedding_date'       => $user->wedding_date,
            'wife_birthday'      => $user->wife_birthday,
            'desc'               => $user->desc,
            'active'             => (bool) $user->active,
            'supervisor'         => $user->supervisor,
            'two_factor_enabled' => (bool) $user->two_factor_enabled,
            'address'            => $user->address,
            'created_at'         => $user->created_at,
        ];
    }

Now in some situation I want to return specific fields of User model as a collection like this :

public function index()
    {
        return $this->collection(User::get(['user_id','name','family','username','created_at']), new UserTransformer());
    }

But in this case result is like this :

"result": [
        {
            "user_id": 1,
            "name": "ahmad",
            "family": "badpey",
            "username": "09139616246",
            "token": null,
            "mobile": null,
            "email": null,
            "sex": null,
            "tel": null,
            "province": null,
            "city": null,
            "picture": null,
            "birthday": null,
            "wedding_date": null,
            "wife_birthday": null,
            "desc": null,
            "active": false,
            "supervisor": null,
            "two_factor_enabled": false,
            "address": null,
            "created_at": {
                "date": "2017-11-15 10:01:24.000000",
                "timezone_type": 3,
                "timezone": "Asia/Tehran"
            }
        }
]

As you can see fields that not included on selection User model, have null value and returned. But I want only included fields return. how can I do that ?

01 Dec
1 year ago

ahmadbadpey started a new conversation Use Validate Method To Display A List Of Valid Parameters Instead Formrequest In Laravel-apidoc-generator

I want to use laravel-apidoc-generator to create api docs in my laravel project.

From here , seems that it's required to write FormRequest to create list of valid parameters.

But there is situation that we do not use FormRequest and prefer to use other validation methods like $request->validate :

public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid...
}

how can I generate valid parameters of methods in this case ?

28 Nov
1 year ago

ahmadbadpey started a new conversation Dynamically Permissions Based On Routes Path In Larvel Via Entrust

To create a Role/permission bases laravel app I'm using Zizaco/entrust package.

Now I want to use an approach that no need to assign defined perms to routes as different middlewares in web.php and that is :

First fetches all defined routes (via Route::getRoutes()->getRoutes() ) and store each of them in permissions table.

We can get all routes by this code :

$routes = collect(Route::getRoutes()->getRoutes())->reduce(function ($carry = [], $route) {
           
            $carry[] = $route->uri();
            return $carry;
        });

On the other hand we can define roles that have those permissions and attach those to user in normal way.

Now when a user want to access a page , first we get route path name and then by can method defined in entrust we check that user can access to that route or not. this can done via a simple middleware named checkAccess for example that is added to all routes as a route group. like this :

class checkAccess
{
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {

           $currentName    =   Route::getCurrentRoute()->getPath();
            if (Auth::user()->can($currentName)) {
                return $next($request);
            }else{
                return response()->view('errors.403', ['prevPage'=> URL::previous()]);
            }*/
            
            return $next($request);

        }
        return Redirect::to('/admin/login');
    }
}

Route::middleware(['checkAccess'])->group(function () {
     //Other routes 
});

But a problem is that some resource routes have same route path but different method access. like:

+-----------+-----------------+---------+----------------+
|  METHOD   |       URL       | Action  |   Route Name   |
+-----------+-----------------+---------+----------------+
| GET       | /photos/{photo} | show    | photos.show    |
| PUT/PATCH | /photos/{photo} | update  | photos.update  |
| DELETE    | /photos/{photo} | destroy | photos.destroy |
+-----------+-----------------+---------+----------------+

And this is cause duplicate permission name Although they are really different in action.

I want to know are there any relative way to create dynamically permission. or what can I do that to solve this problem in this case ?

26 Nov
1 year ago

ahmadbadpey started a new conversation Where Can Set A Package Configuration That Is Used In A Modules Of Laravel-modules

I want to use laravel-modules package to create a modular laravel app.

For example one of the custom module that I want to create is called Tag .for that I want to use etrepat/baum package (that seems is best in this case).

My first question is which composer file I should add Baum package ? individual Tag module or main composer file of whole project? and what is differences ?

And second is suppose I added it to Tag composer.json file , but then where do I added should 'Baum\Providers\BaumServiceProvider' that is required to run Baum package while there is not any app.php file in Config directory created in Tag module.

24 Nov
1 year ago

ahmadbadpey left a reply on Two-factor SMS Authentication Workflow In Laravel

thanks for your guide. But the problem that I have now is that beacause I'm working on a API via dingo laravel package seem I can not use session for store some data like created token.

What can I do instead of that ?

23 Nov
1 year ago

ahmadbadpey left a reply on Using Sessions With Dingo Api And Jwt

@TECHTRAV, Have you gotten the answer to this problem?

ahmadbadpey started a new conversation Two-factor SMS Authentication Workflow In Laravel

I want to make a SMS 2-factor authentication system but I do not know what is workflow in this case and which methods should be used.

I want to use a Boolean field named isTwoFactorActive for user model and when a user attempt to login if it's TRUE then go to a view for enter SMS code that received.

In addition to, I'm using Dingo laravel package to create an API and all this operations should be under API.

I do not know what is best approach and workflow. if any One has knowledge in this case please help me.

17 Nov
1 year ago

ahmadbadpey started a new conversation “Unauthenticated” Error Message For Logged In Users In Larvel 5.5

I'm using [Dingo/api][1] laravel package to create an API. I worked with it before and I have not this problem.

this is my routes in the api.php file :

$api = app('Dingo\Api\Routing\Router');
$api->version('v1', ['prefix' => 'v1', 'namespace' => 'App\Http\Controllers'], function ($api) {

    $api->group(['prefix' => 'auth'], function ($api) {
        $api->post('signIn', 'Auth\[email protected]');
    });

    $api->group(['middleware' => 'api.auth'], function ($api) {
        $api->get('signOut', ['uses' => 'Auth\[email protected]']);

        $api->get('test', function () {
            return response()->json(['foo' => 'bar']);
        });
    });

});

/signIn route works fine and respond a token that can used in other protected endpoint like /test and /test directory works fine.

But I want to Sign out a user and call /signOut route it responses this always:

{
    "success": false,
    "message": "Unauthenticated.",
    "status_code": 500
}

This is signOut method in LoginController :

public function signOut()
    {
        //return 'Hiiiii Alll';
        try {
            $token = \Tymon\JWTAuth\Facades\JWTAuth::getToken();
            \Tymon\JWTAuth\Facades\JWTAuth::invalidate($token);
            return [
                'success' => true,
                'message' => 'You Signed Out Successfully'
            ];

        } catch (\Exception $e) {
            return $this->response->error('Something went wrong', 404);
        }
    }

Even when I return a Simple string from that method it does not run, seems problem is in ['middleware' => 'api.auth'] that I used But if it's right why problem does not occurred for test directory that in in the same route group?

05 Nov
1 year ago

ahmadbadpey started a new conversation Two Different Models For Authentication In Larvel 5.4

Suppose I have two different models and tables named user and company.

As you know laravel uses User model to manage Authentication. but beacause I have two different model I want can manage them separately.

I'm using laravel 5.4 and I do not know how can do that.

03 Nov
1 year ago

ahmadbadpey started a new conversation Why Paramter In A Route Group Is Required In All Sub Resource Route Methods

I have a route group that has a parameter like this :

Route::prefix('/website/{account}')->group(function () {
        Route::group(['middleware' => ['auth']], 
            Route::resource('/member', 'MemberController');
        });
    });

As you see there is a account parameter in route group.

Now to show member-create page I added this to MemberController :

public function create ($account)
        {
            return view('admin/pages/members/members-create',compact('account'));
        }

Now when I want to create a form that send request to store function of MemberController like this (in member-create.blade.php) :

{!! Form::open(array('action' =>['[email protected]'],  'id'=>'createMemberForm')) !!}

laravel says that :

Missing required parameters for [Route: member.store] [URI: website/{account}/member].

That's because, I must to add a $account parameter to store function. in fact beacause I used a parameter in route grouping, I have to always send a value as that parameter first to create function and then from there passe it to store function that, Naturally, this takes a lot of time from me.

Is there any way to solve this problem where $account parameter send to functions automatically or any alternate way

30 Oct
1 year ago

ahmadbadpey started a new conversation Acrylic DNS Proxy Does Not Work To Create Dynamically Wildcard Sub Domain

In Laravel 5.4 I want to create dynamically subdomain.

According to This Answer in SO I followed this instructions to do that:

First I downloaded and installed Acrylic DNS Proxy program. then I added this line at end of Acrylic Host file like this:

127.0.0.1 *.loverspay.dev loverspay.dev

And added this to httpd-vhosts in apache extra directory:

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot 'd:/wamp/www/loverspay/public'
    ServerName loverspay.dev
    ServerAlias *.loverspay.dev
    <Directory 'd:/wamp/www/loverspay/public'>
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Also I changed Preferred DNS Server to 127.0.0.1 in Local Area Connection Properties.

And this is my route to control wildcard subdomain that should show main route in larvel :

Route::group(['domain' => '{account}.loverspay.dev'], function ($account) {
        Route::get('/', function ($account, $id) {
            return view('home');
        });
    });

Now after starting acrylic DNS proxy when I go to loverspay.dev all things worked find But when I want to open ahmad.loverspay.dev for example only a This site can’t be reachedessage shown in chrome.

17 Oct
1 year ago

ahmadbadpey started a new conversation Laravel Mix Could Not Compile A Scss File Contains Compass/css3 Import

I have a file named main.scs that imported a general.scss file that has at the first line this :

@import "compass/css3";

As you can see I imported compass/css3 to use some predefined mixins.

Of course all of them are in a larvel project. larvel have a built-in Mix library to compile scss and other type files.

Also I wrote these to webpack.mix.js file :

let mix = require('laravel-mix');

mix.sass('resources/assets/sass/main.scss', 'public/main/css');

But when running npm run production command I got this error:

 error  in ./resources/assets/sass/main.scss

Module build failed:
@import "compass/css3";
^
      File to import not found or unreadable: compass/css3.
Parent style sheet: D:/wamp/www/loverspay/resources/assets/sass/_general.scss
      in D:\wamp\www\loverspay\resources\assets\sass\_general.scss (line 1, column 1)

Even I installed compass in the project directory But there is still that problem

What do I do?

20 Aug
1 year ago

ahmadbadpey left a reply on Go Back To Impersonator User After Logout Impersonated User

For that I should know that current user is Impersonated or not.right? how can I detect that ?

ahmadbadpey started a new conversation Go Back To Impersonator User After Logout Impersonated User

To implement an authenticate as other users mechanism in laravel, I'm using 404labfr/laravel-impersonate package.

Impersonate as other users works fines. But after a impersonated user logs out parent user (impersonator user) logs out too , while I'm looking for a solution that after impersonated user logouts go back to impersonator user session.

It even seems there is not any built-in method for that.

Anyway, Now I don't know how can I solve this problem. if anyone knows please help me.

04 Jul
2 years ago
03 Jul
2 years ago

ahmadbadpey started a new conversation Disabling Always_populate_raw_post_data In Php.ini Does Not Work

Today when I want to send some data via axios Vuejs plugin, php throws this error:

Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0

Warning: Cannot modify header information - headers already sent in Unknown on line 0

After googling and searching for solution I found that , I can uncomment and change the value of always_populate_raw_post_data to -1 can solve the problem. But that could not solve problem and it is continued.

I used phpinfo() to detect real php.ini file and sure that I changed it properly.

I'm using php 5.6.25 and wamp 3.0.6 64bit on windows 8.

23 Jun
2 years ago

ahmadbadpey started a new conversation Customize Directory Destination For ES6 Compiled Files Via Babel Watcher In PhpStorm

I have a directory structure like below:

enter image description here

All ES6 files are in the js directory. Now I want after compiling those files to put all of them into a dist directory but I do not know how can I do that.

I've added a Babel watcher in PhpStorm that has this configuration :

program :

D:\wamp\www\vuejs\node_modules\.bin\babel.cmd

Arguments :

$FilePathRelativeToProjectRoot$ --out-dir dist --source-maps --presets env

Output path to refresh :

dist\$FileDirRelativeToProjectRoot$\$FileNameWithoutExtension$.js:dist\$FileDirRelativeToProjectRoot$\$FileNameWithoutExtension$.js.map

What changes should I make in the watcher configuration?