jlanzas

jlanzas

Member Since 11 Months Ago

Experience Points 4,050
Experience
Level
Lessons Completed 31
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

06 Dec
1 week ago

jlanzas left a reply on Pass Model To Repository From Decorator

Has anyone face this before?

jlanzas started a new conversation Pass Model To Repository From Decorator

I have the following interface:

<?php

namespace App\Repositories;

interface MainRepository
{
    public function all();

    public function create(array $data);

    public function update(array $data, $id);

    public function delete($id);

    public function show($id);
}

From this interface I have the following repository

<?php

namespace App\Repositories;

use Illuminate\Database\Eloquent\Model;

class DefaultRepository implements MainRepository
{
    // model property on class instances
    protected $model;

    // Constructor to bind model to repo
    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    public function modelName()
    {
        return $this->model->getTable();
    }

    // Get all instances of model
    public function all()
    {
        return $this->model->all()->each->setAppends(['permissions']);
    }

    // create a new record in the database
    public function create(array $data)
    {
        return $this->model->create($data);
    }

    // update record in the database
    public function update(array $data, $id)
    {
        return $this->model->find($id)->update($data);
    }

    // remove record from the database
    public function delete($id)
    {
        return $this->model->destroy($id);
    }

    // // show the record with the given id
    public function show($id)
    {
        return $this->model - findOrFail($id);
    }
}

And finally, my cache decorator

<?php

namespace App\Repositories;

use Illuminate\Contracts\Cache\Repository as Cache;

class CacheRepository implements MainRepository
{
    private $repository;
    private $cache;

    public function __construct(MainRepository $repository, Cache $cache)
    {
        $this->repository = $repository;
        $this->cache = $cache;
    }

    public function all()
    {
        return $this->cache->tags($this->repository->modelName())->remember('all', 1, function () {
            return $this->repository->all();
        });
    }

    public function create(array $data)
    {
        $this->cache->tags($this->repository->modelName())->flush();
        return $this->repository->create($data);
    }

    public function update(array $data, $id)
    {
        $this->cache->tags($this->repository->modelName())->flush();
        return $this->repository->update($data, $id);
    }

    public function delete($id)
    {
    }

    public function show($id)
    {
    }
}

Everything works, the problem is that I'm always sending the same model to the cache decorator:

$this->app->singleton(MainRepository::class, function () {
    return new CacheRepository(
        new DefaultRepository(new \App\Inventory\Unit),
        $this->app['cache.store']
    );
});

I want to dynamically send the model. Is it possible? How can I achieve this, is there other option?

Below my controller.

use App\Repositories\MainRepository;

class UnitController extends Controller
{
    private $repository;

    public function __construct(MainRepository $repository)
    {
        $this->repository = $repository;
    }
}

Everything works, each function, method, etc. But I wasnt able to figure out how to send dynamically the model from the controller when I call my Interface.

Thank you in advance.

27 Nov
2 weeks ago

jlanzas left a reply on Queue Observer

@d9705996 Yeah, in my scenario I have an external DB that I need to sync whenever a user saves a product. This is tacking a bit of time, so, i dont want my saving process to take that time it takes to sync the external DB. thats the main reason I want to queue these events.

jlanzas started a new conversation Queue Observer

Is it possible to queue all observer events?

19 Sep
2 months ago

jlanzas left a reply on Obtain Specific Attributes From Collection

Thank you @Leandro_Haruki && @D9705996 for the help and the time.

jlanzas left a reply on Obtain Specific Attributes From Collection

Has anyone faced this issue?

jlanzas left a reply on Obtain Specific Attributes From Collection

This is how my dd looks:

Collection {#855 ▼
    #items: array:32 [▼
        0 => Product {#1104 ▶}
        1 => Product {#1103 ▶}
        2 => Product {#1099 ▶}
       3 => Product {#1095 ▶}
    ]
}

jlanzas started a new conversation Obtain Specific Attributes From Collection

I have the following collection:

[{
        id: 1,
        sku: null,
        code: "000000000000",
        name: "Galaxy S",
        description: null,
        maker: "Samsung",
        model: "S",
        serial: null,
        price: "3500.0000000000",
        image: null,
        status: true,
        created_at: "30/08/2018",
        updated_at: "2018-08-30 23:02:27",
        deleted_at: null
    },
    {
        id: 1,
        sku: null,
        code: "000000000000",
        name: "Galaxy S2",
        description: null,
        maker: "Samsung",
        model: "S",
        serial: null,
        price: "3500.0000000000",
        image: null,
        status: true,
        created_at: "30/08/2018",
        updated_at: "2018-08-30 23:02:27",
        deleted_at: null
    },
    {
        id: 1,
        sku: null,
        code: "000000000000",
        name: "Galaxy S3",
        description: null,
        maker: "Samsung",
        model: "S",
        serial: null,
        price: "3500.0000000000",
        image: null,
        status: true,
        created_at: "30/08/2018",
        updated_at: "2018-08-30 23:02:27",
        deleted_at: null
    },
    {
        id: 1,
        sku: null,
        code: "000000000000",
        name: "Galaxy S4",
        description: null,
        maker: "Samsung",
        model: "S",
        serial: null,
        price: "3500.0000000000",
        image: null,
        status: true,
        created_at: "30/08/2018",
        updated_at: "2018-08-30 23:02:27",
        deleted_at: null
    },

]

I had the following code to get specific attributes:

$data = $products->map(function ($product) {
    return $product->only(['id', 'name']);
});

The only thing is that only is returning an array which conflicts with another function I have in my app where it loops the attributes. So I'm getting the following error:

Call to a member function getAttributes() on array
10 Sep
3 months ago

jlanzas started a new conversation Dynamically Add Select, With, Or Withcount To A Model

Is is possible to dynamically add these functions to a model, for example: I have a custom helper class which receives a class, columns, relations, with-count parameters and the idea is to return a model response from the class..

function getModel($model, $columns = null, $relations = null, $withCount = null)
{
    if (isset($columns)) {
        $model::select($columns);
    }

    if (isset($relations)) {
        $model->with($relations)
    }

    // Same logic with withCount
}

This is how I call this helper function,

$relations = ['branch'];
$columns = ['id', 'branch_id', 'code', 'name'];
$withCounts = ['products'];

$data = getModel(Warehouse::class, $columns, $relations, $withCounts);

My relationships and everything is working, the reason I want to know if adding functions dynamically is possible is because I have several if in my logic like this...

if (isset($columns) && isset($relations) && isset($withCount)) {
            $model = $model::select($columns)->with($relations)->withCount($withCount)->get();
        } elseif (isset($columns) && isset($relations) && !isset($withCount)) {
            $model = $model::select($columns)->with($relations)->get();
        } elseif (isset($columns) && !isset($relations) && isset($withCount)) {
            $model = $model::select($columns)->withCount($withCount)->get();
        } elseif (isset($columns) && !isset($relations) && !isset($withCount)) {
            $model = $model::select($columns)->get();
        } elseif (!isset($columns) && isset($relations) && isset($withCount)) {
            $model = $model::with($relations)->withCount($withCount)->get();
        } elseif (!isset($columns) && isset($relations) && !isset($withCount)) {
            $model = $model::with($relations)->get();
        } else {
            $model = $model::all();
        }
06 Sep
3 months ago

jlanzas left a reply on Dynamically Loop Relationships

Accesor changes the field when saving, mutator changes when getting information

jlanzas left a reply on Dynamically Loop Relationships

this is not a relationship, is a mutator of the model.

jlanzas started a new conversation Dynamically Loop Relationships

Is it possible to dynamically loop relationships from a modelo? This is what a will like to accomplish, I have the following append in many of my model

Product.php

protected $appends = [
    'permissions'
];

Which is working great but I don't need this $append to be added when Eager Loading. I know this setAppends([]) removes this field.

What I want to do is something like

foreach ($model->relationships() as $relationship) {
    $relationship->setAppends([]);
}

Since, this is going to be a global function I don't specifically know the amount of relations there have been set. So that the reason I want to loop the model dynamically.

04 Sep
3 months ago

jlanzas left a reply on Custom Intermediate Table Models

Thank you @tykus and @staudenmeir for the time and help.

jlanzas left a reply on Custom Intermediate Table Models

No I had,

Warehouse::with('branch')->withCount('products')->select('id', 'name')->get()

jlanzas left a reply on Custom Intermediate Table Models

Found the problem, apparently adding select->('id', 'column1', 'column2') does not play well withCount

jlanzas left a reply on Custom Intermediate Table Models

select `warehouses`.*, (select count(*) from `products` inner join `product_warehouse` on `products`.`id` = `product_warehouse`.`product_id` where `warehouses`.`id` = `product_warehouse`.`warehouse_id`) as `products_count` from `warehouses`

Which does return the column but my result is not showing anything.

jlanzas left a reply on Custom Intermediate Table Models

Sure I forgot to added, but here it is

public function products()
{
    return $this->belongsToMany('App\Inventory\Product')
        ->withPivot('stock', 'average_cost', 'total_cost', 'minimum', 'ideal', 'maximum')
        ->using('App\Inventory\ProductWarehouse');
}

jlanzas started a new conversation Custom Intermediate Table Models

How can I implement withCount on a many-to-many relationship that has Custom Intermediate Table Model

I have the following models

class Product extends Model
{
}
class Warehouse extends Model
{
}
class ProductWarehouse extends Pivot
{
}

I had before Warehouse::withCount('products') which returned a {relation}_count. This doesn't return the count when I added the custom intermediate table model

31 Aug
3 months ago

jlanzas left a reply on Ignore $append When Eagerloading

I have tried constraining the eager load but regardless of the fields I select I get the $appends attributes added.

jlanzas started a new conversation Ignore $append When Eagerloading

I have the following model

class Unit extends Model
{
    protected $fillable = [
        'abbreviation',
        'name',
        'status'
    ];

    protected $casts = [
        'status' => 'boolean',
    ];

    protected $appends = [
        'permissions'
    ];

    public function getPermissionsAttribute($value)
    {
         // Login that check user permissions for this model
    }
}

When I call this model everything works. However, my issue comes when I want to eager load the model mention above. Like so:

$products = Product::with(['unit']);

I'm getting the $appends variable there too. Is there anyway I can remove the $append when eager loading?

27 Jul
4 months ago

jlanzas left a reply on Copy Config File To Storage

I ended up using native php copy

jlanzas started a new conversation Copy Config File To Storage

Hello everyone, quick question: Is it possible to copy a config file to the Storage folder? This is my code:

Storage::copy(config_path('zeusconfiguration.php'), storage_path('app/zeusconfiguration.php));

Im getting the following error:

File not found at path: Users/aguilar/projects/zeus/config/zeusconfiguration.php
27 Jun
5 months ago

jlanzas left a reply on Collection Apply Where Case Insensitive

I ended up using filtering with strcasecmp this is what I did incase someone finds it helpful...

function filterCollection($collection, $attribute, $toSearch)
{
    return $collection->filter(function ($value, $key) use ($attribute, $toSearch) {
        return strcasecmp($value->{ $attribute }, $toSearch) == 0;
    });
}
26 Jun
5 months ago

jlanzas started a new conversation Collection Apply Where Case Insensitive

I'm trying to apply a where clause to a collection but it seems it is case sensitive... for example:

$this->units->where('abbreviation', 'km')->count()

returns 0 since my collections has "KM" in uppercase.

Anyway I can apply a where case insensitive.

25 Apr
7 months ago

jlanzas left a reply on B"string" Error

I got it working, I can't remember where I found an example of a MSSQL database connection. But it turns out i had 'characterset' => 'utf8'

'local' => [
    'driver'    => 'sqlsrv',
    'host'      => env('DB_HOST'),
    'database'  => 'localhost',
    'username'  => env('DB_USERNAME'),
    'password'  => env('DB_PASSWORD'),
    'charset'   => 'utf8',
    'collation' => 'SQL_Latin1_General_CP1_CI_AS',
    'prefix'    => '',
],

Just changed that property and everything is working fine.

jlanzas left a reply on B"string" Error

I have the following response

array:3 [▼
  0 => {#1156 ▼
    +"observaciones": b"Some text"
  }
  1 => {#1157 ▼
    +"observaciones": "Text"
  }
  2 => {#1158 ▼
    +"observaciones": "Test"
  }
]

And I get the following error: (1/1) InvalidArgumentException Malformed UTF-8 characters, possibly incorrectly encoded

23 Apr
7 months ago

jlanzas left a reply on B"string" Error

has anyone run into this problem?

20 Apr
7 months ago

jlanzas left a reply on B"string" Error

@lostdreamer_nl it does affect when I want to return a JSON response. I get

jlanzas left a reply on B"string" Error

Everything seems to work on my production environment which is Linux.

jlanzas started a new conversation B"string" Error

Laravel is returning some strings as binary. I have found that it happens on string that contain the following character ñ This doesn't happen with other special characters like `é í ?d it only happens on my MacOS which is running High Sierra.

I'm working with SQL SERVER 2016 and the oficial Microsoft PDO libraries for PHP.

12 Apr
8 months ago

jlanzas left a reply on Tinker - Could Not Find Driver

Thank you @Helmchen the drivers were missing. I don't know why my extensions got disabled.

11 Apr
8 months ago

jlanzas left a reply on Tinker - Could Not Find Driver

@rumm.an Im working on a Mac. The weird thing is that it used to worked. I dont know it doesnt anymore.

jlanzas left a reply on Tinker - Could Not Find Driver

@Cronix my app works just fine. My tinker is not.

jlanzas left a reply on Tinker - Could Not Find Driver

@Cronix a simple search

Psy Shell v0.8.18 (PHP 7.1.14 — cli) by Justin Hileman
>>> $user = App\User::find(1)
Illuminate\Database\QueryException with message 'could not find driver (SQL: select top 1 * from [users] where [users].[id] = 1)'
>>>

jlanzas started a new conversation Tinker - Could Not Find Driver

I'm trying to interact with my mssql server from tinker but I'm getting the following error:

Illuminate\Database\QueryException with message 'could not find driver

My application works ok, only tinker is giving me that error

27 Mar
8 months ago

jlanzas left a reply on Filter Results

thank you @lostdreamer_nl and @tykus both your answers helped me get where I need it.

jlanzas left a reply on Filter Results

The filtering will only be based on $unit instance.

jlanzas started a new conversation Filter Results

I have the following data:

Unit::with('products')->get();

Based on that initial collection I need to filtered it. I need a way to search all columns without naming each one in a

->where
->orWhere

So, I was trying the following:

$filtered = $this->units->filter(function ($unit) use ($filter) {
    return $unit->contains($filter);
});

But I keep getting:

BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::contains()

Can anyone help me out.

27 Feb
9 months ago

jlanzas left a reply on Boolean Field Returns Empty When Set To False In Blade

Thank you very much @sutherland appreciate the time.

jlanzas started a new conversation Boolean Field Returns Empty When Set To False In Blade

Is there a reason why my boolean field returns an empty string when I used in in blade? When I use the following code:

var xxx = "{{ Auth::user()->alertConfigs->progress_bar }}"

and it sets to true (1) I get a 1 in my blade view. I get:

var xxx = "1"

However, when I changed its value to False (0) I'm getting and empty string.

var xxx = ""

Can anyone help me out.

17 Feb
9 months ago

jlanzas left a reply on Pass Variable To Api Resource Collections

Thank you for the answers guys... @skliche I'm working with datatables and pagination. So I need to send back, the page number, total pages, item count, per-page amount, sort field and sort order.

I can get a few fields like the item count, total pages, but the page number is send on a variable the same goes for the per-page amount and the sorting field and order.

So thats the reason I want to send those fields to the ResourceCollection.

jlanzas started a new conversation Pass Variable To Api Resource Collections

Is there anyway I can pass variable to a resource collection? I have been looking around but can't figure it out.

Any help will be greatly appreciated.

08 Feb
10 months ago

jlanzas started a new conversation Permissions Optimization In Blade

I'm currently working on a system which uses Roles & Permissions to control its security. I have implemented Bouncer successfully. However, there are times where an user will have access to only one "report" inside the reports submodule of a bigger module. Instead of creating a role with a single permission I have added that permission directly onto the user. And everything works ok. No problem there.

Here is my question. Lets say I have a module call Purchases. Inside Purchases I have Products, Orders, Suppliers, Reports, etc. In my blade I have the following syntax:

@if( $user->isAn('role1', 'role2', 'etc'))
<h1>Purchases</h1>
<ul>
    @can('view-orders')
    <li>
        Icon - Orders
    </li>
    @endcan

    @can('view-suppliers')
    <li>
        Icon - Suppliers
    </li>
    @endcan

    @can('view-reports')
    <li>
        Icon - Reports
        <ul>
            <li>Report 1</li>
            <li>Report 2</li>
            <li>Report 3</li>
        </ul>
    </li>
    @endcan
</ul
@endif

The problem now is that my user may only have access to reports directly without needing to be assign to a role. Looking for roles assigned to an user is no longer the best approach.

I found a solution but its to search every single permission at the begging just to paint the main module and the search the submodule individually.

Any ideas will be greatly appreciated and I hope I have explain myself.