romulo27

romulo27

Member Since 10 Months Ago

Fortaleza

Experience Points 7,770
Experience Level 2

2,230 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 36
Lessons
Completed
Best Reply Awards 0
Best Reply
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.

15 Apr
2 months ago

romulo27 started a new conversation How To Synchronize HasMany Relationship With BelongsTo?

I have a relationship between Site andSite Version

I need to create a method, which when the user clicks, modify the state of the Site, which is DRAFT forSTAGING.

The state of the site is saved in the table:site_version

How to make?

Site Model

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function versions(): HasMany
    {
        return $this->hasMany(SiteVersion::class);
    }



Site Version Model

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function site() {
        return $this->belongsTo(Site::class);
    }
14 Apr
2 months ago

romulo27 started a new conversation Update The Field Of An Objec

Hello Devs. I have a little problem.

Hello Devs. I have a little problem.

I have a button where I modify the STATEof asite, initially thesitehasSTATEasDRAFTas it is created. There is an option where the user clicks that modifies theSTATEof this site, only switchesSTATE: DRAFTto STATE: STAGING`. How would I make this modification?

MODEL SITE

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function versions(): HasMany
    {
        return $this->hasMany(SiteVersion::class);
    }


MODEL SITE_VERSION

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function site() {
        return $this->belongsTo(Site::class);
    }

05 Apr
2 months ago

romulo27 left a reply on How To Copy Files And Folders In Laravel

@SNAPEY - I actually want to copy the files that are in that folder.

romulo27 started a new conversation How To Copy Files And Folders In Laravel

In laravel as I do to copy the files from one folder to another. In case I have the following folder.

app / themes / default / public and I want to copy all the files from the public folder and put in that directory,app / websites-published /. app / websites-published / '. $ content-> nanoid

How do I do this?

03 Apr
2 months ago

romulo27 started a new conversation Json Fields With Laravel Auditing

Hi everyone, I'm implementing Laravel Auditing in my application and I'm in a dilemma.

In my model I have a json field, with several fields, the moment I have update, it returns me the full json, but I actually just wanted it to return to the fields that actually have been updated.

Anyone have any solutions or implemented this package at this level?

26 Mar
2 months ago

romulo27 started a new conversation Record The Relationship Between 3 Tables.

I have a form where I choose the bikes for a dealership at the time of registering I want to link and synchronize the data to save in the bank, I am breaking the head so I can register, but to no avail. I made a dd () in request ()

In the first array Brands I have the id of the brand and soon after in the position motorcycles the motorcycles that I need to register.

Result of dd () with the data coming from the form.

array:3 [▼
  "_method" => "PUT"
  "_token" => "XFZ5BlmBA8gajxjenJuGvFl7PZVXLYUG702Nxchw"
  "brands" => array:2 [▼
    1 => array:1 [▼
      "motorcycles" => array:2 [▼
        0 => "1"
        1 => "2"
      ]
    ]
    5 => array:1 [▼
      "motorcycles" => array:2 [▼
        0 => "5"
        1 => "6"
      ]
    ]
  ]
]



dealership(Concessionária)
dealership
- id
- name
- slug
- nanoid
Model Dealership
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function dealershipBrands()
    {
        return $this->hasMany(BrandDealerships::class)
            ->with('brand');
    }



BrandDelaership(MarcasConcessionára)
brand_dealerships
- id
- dealership_id
- brand_id
Model BrandDealership
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function dealershipMotorcycle()
    {
        return $this->hasMany(DealershipMotorcycle::class, 'brand_id');
    }




DealershipMotorcycle(Concessionária Motocicleta)
dealership_motorcycles
- id
- brand_id
- motorcycle_id
Model DealershipMotorcycle
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function brandDealership()
    {
        return $this->belongsTo(BrandDealerships::class, 'brand_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function motorcycle()
    {
        return $this->belongsTo(Motorcycle::class, 'motorcycle_id');
    }




Método do Controller responsavel pelo Sync
    /**
     * Sync de Motorcycles e Stores
     *
     * @param Request $request
     * @param Model $model
     */
    public function syncMotorcycleStore(Request $request, Model $model)
    {
        dd($request->all());
        // $model->brands()->sync($request->input('brands'));

        $model->dealershipBrands();
    }
21 Mar
3 months ago

romulo27 left a reply on Associating Models

But, @ it helped me pakas, did not think it was that simple.

romulo27 left a reply on Associating Models

In that case does he pay for all the brands? In case they are json to do this part.

romulo27 left a reply on Associating Models

@ETTORE - Using attach dont work.

romulo27 left a reply on Associating Models

I try this

romulo27 left a reply on Associating Models

The brand has already been created, in the above method I create them.

romulo27 left a reply on Associating Models

The brand :: all () was just an example

romulo27 left a reply on Associating Models

@ETTORE - @ettore This method read a Json to make a seed in the bank, it does a seed in the dealerships, being without the relationship of the brand that it belongs, being that in the file json has a parameter that refers to the brand, I get this file in the variable $ filename, and now I need to bind the dealership with the brand or vice versa.

romulo27 left a reply on Associating Models

@ETTORE - @ettore I'm getting the $ filename variable

romulo27 left a reply on Associating Models

$brand = Brand::all();
                // Brands()
                if (isset($filename)) {
                    $dealership->brands()->syncWithoutDetaching($brand);
                }

that way it takes all the tags and binds, being that I want the value that is in $ filename

romulo27 started a new conversation Associating Models

I have a seed, I wanted the moment he created the Dealerships he assosed Brand, how to do it?

    private function fillDealerships(array $files)
    {
        foreach ($files as $file) {
            $data = $this->getFileContent($file);

            foreach ($data as $item) {
                $slug = isset($item['u']) ? Str::slug($item['u']) : $file['filename'];
                $filename = $file['filename'];

                /* @var $dealership Dealership */
                $dealership = Dealership::query()->updateOrCreate([
                    'slug' => $slug,
                ], [
                    'name' => $item['n'] ?? $slug,
                ]);
                $brand = Brand::class;
                dd($brand);
                // Brands()
                if (isset($filename)) {
                    $dealership->brands();
                }

                $this->fillDealershipStore($dealership, $relation = null, $item);
            }
        }
    }
20 Mar
3 months ago

romulo27 left a reply on Accessing Objects From A JSON

In case I can do it to get the data, I need to relate Dealership to Brand, the parameter is in $ filename, as I pass this parameter so that it registers the Dealeships with the $ filename parameter

   private function fillDealerships(array $files)
    {
        foreach ($files as $file) {
            $data = $this->getFileContent($file);

            foreach ($data as $item) {
                $slug = isset($item['u']) ? Str::slug($item['u']) : $file['filename'];
                $filename = $file['filename'];

                /* @var $dealership Dealership */
                $dealership = Dealership::query()->updateOrCreate([
                    'slug' => $slug,
                ], [
                    'name' => $item['n'] ?? $slug,
                ]);

                // Brands()
                if (isset($filename)) {
                    $relation = $dealership->brands();
                }

                $this->fillDealershipStore($dealership, $relation, $item);
            }
        }
    }

romulo27 left a reply on Accessing Objects From A JSON

Here I get the name $ filename = $ file ['filename']; Now with this I need to relate Dealership to Brands, how do I?

romulo27 left a reply on Accessing Objects From A JSON

Deu certo aqui! :D

romulo27 started a new conversation Accessing Objects From A JSON

I have the following .json file, in case I want to access initial data, called suzuki at the beginning of json, how do I get this information?

This .json is responsible for doing the data seed in the database, and that field is the one of the relationship, I just need to get it in the class.

The rest of the other data I can get the value and save in the bank.

Method of registration of the Concessionaire.

    private function fillDealerships(array $files)
    {
        foreach ($files as $file) {
            $data = $this->getFileContent($file);

            foreach ($data as $item) {
                $slug = isset($data['u']) ? Str::slug($item['slug']) : $file['filename'];

                /* @var $dealership Dealership */
                $dealership = Dealership::query()->firstOrCreate([
                    'slug' => $slug,
                    $dealership->brands()
                ], [
                    'name' => $item['n'] ?? $slug,
                ]);

                $this->fillDealershipStore($dealership, $item);
            }
        }
    }
{
  "suzuki": [
    {
      "n": "MOTO MAIS",
      "u": "moto-mais",
      "e": {
        "l": "Av. Oswaldo Da Silva",
        "n": "710",
        "m": "",
        "b": "Conjunto Habitacional Ana Jacinta",
        "u": "19064070",
        "c": {
          "i": "9286",
          "n": "Presidente Prudente"
        },
        "s": {
          "i": "26",
          "n": "Sao Paulo"
        },
        "r": "https:\/\/goo.gl\/maps\/aYoJgneRsTo",
        "g": [
          "-22.1505632",
          "-51.4526682"
        ]
      },
      "c": {
        "t": {
          "c": {
            "n": "(18) 3901-1911",
            "l": "1839011911"
          }
        }
      },
      "r": {},
      "g": null,
      "t": "concessionaria-autorizada"
    }
}
18 Mar
3 months ago

romulo27 left a reply on Syncing Permissions With Spatie Permission

protected function syncPermissions(Request $request, Model $model) { $model->brands()->sync($request->input('brands')); $model->dealerships()->sync($request->input('dealerships'));

    $roles = [];
    $permissions = $request['permissions'];

    foreach ($permissions as $context => $permission) {
        // Verificando o primeiro nivel de permissão do novo usuário
        if ($context === 'admin') {
            foreach ($permission as $value) {
                $roles[] = $context . '.' . $value;
            }
        } else {
            // Verificando as permissões que o user tem em Brands e Dealeships
            foreach ($permission as $key => $value) {
                $roles[] = str_singular($context) . ':' . $key . ':' . $value;
            }
        }
    }
    $model->syncRoles($roles);
}

romulo27 started a new conversation Syncing Permissions With Spatie Permission

Hey guys. I need a little help, I need to synchronize permissions when creating and editing a user within Administrator.

I can give Sync in the roles, but not in the permissions of this role, how to do?

` protected function syncPermissions(Request $request, Model $model) { $model->brands()->sync($request->input('brands')); $model->dealerships()->sync($request->input('dealerships'));

    $roles  = [];
    $permissions = [];


    dd($request->input('permissions'));

    $model->syncPermissions($permissions);
    $model->syncRoles($roles);
}

`

` dd($request->input('permissions')); array:3 [▼ "admin" => array:1 [▼ 0 => "admin" ] "brands" => array:1 [▼ "haojue" => "admin" ] "dealerships" => array:1 [▼ "fortaleza" => "admin" ] ]

`

26 Feb
3 months ago

romulo27 started a new conversation Relationship With 3 Tables

I'm confusing a relationship with more than 3 tables. I have the DealershipStore,DealershipsStoreBrand and DealershipsStoreCategoryOptions models. As soon as I paste data into DealershipStore, I store that id in theDealershipsStoreBrand table and so on DealershipsStoreCategoryOptions, but for that I need a sync. The problem is failing to relate the sync between them.

class DealershipStore extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function dealershipStoreBrands(): BelongsToMany
    {
        return $this->belongsToMany(DealershipsStoreBrand::class);
            // ->with(BrandDealerships::class)
            // ->with(Brand::class);
    }
}
class DealershipsStoreBrand extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function dealershipStore()
    {
        return $this->belongsTo(DealershipStore::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function dealershipBrand()
    {
        return $this->belongsTo(BrandDealerships::class);
    }
}
class DealershipsStoreCategoryOptions extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function dealershipStoreBrand()
    {
        return $this->belongsTo(DealershipsStoreBrand::class);
    }

    public function brandStoreOption()
    {
        return $this->belongsTo(BrandStoreCategoryOption::class);
    }

}
16 Feb
4 months ago

romulo27 started a new conversation Validation With Lumen.

Can I validate the class in a Lumen api, how do I use it and an api laravel application?

14 Feb
4 months ago

romulo27 started a new conversation Laravel Sortable Rutorika

Has anyone used this package yet?

I have a project that uses it, to do this, but not how to implement it. I installed the package, I made the fields in the models, but I'm stuck in the method that will manage. In my database I have site_contents andsite_contents_components, the ordering will be for site_contents_components.

class SiteContentComponent extends Model implements HasMedia {

    use SortableTrait, HasMediaTrait, BelongsToSortedManyTrait;

    protected static $sortableGroupField = 'sitecontent_id';

    protected static $sortableField = 'order';

    protected $fillable = [
        'sitecontent_id',
        'component',
        'metadata',
        'order',
        'id',
    ];

    protected $casts = [
        'metadata' => 'array'
    ];

    /**
     * {@inheritdoc}
     */
    public function getRouteKeyName() : String {

        return 'slug';
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function content(){
        return $this->belongsTo(SiteContent::class, 'sitecontent_id');
    }
13 Feb
4 months ago

romulo27 started a new conversation Check Field In Relationship

When I am going to register a new page in the site, before I choose the title type of the new page. Being that the site already had a page with front-page I can not show this option for him.

In dd ($ page) I have all the pages of that site, in case I wanted to check if any of them have type = front-page if yes, do not display this option, how to do?

    public function create()
    {
        $types = SiteContentTypeDictionary::all();

        unset($types[SiteContentTypeDictionary::REVISION]);

        // remover front-page se tiver front-page no site
        $request = app('request');

        $website = $request->route('website');
        $pages = $website->contents;

 
        $this->data['types'] = $types;

        return $this->makeCreate();
    }
06 Feb
4 months ago

romulo27 started a new conversation Remove And Add Fields In Js

I'm in a form, where I have a color checkbox, and when I click on using "site default" it hides the input field to insert, but in case I wanted to remove it and when I check the check it appears again, how to make that flow ?

    <div class="option-page">
    <div class="form-group row">
        {{ Form::label('metadata', 'Título', ['class' => 'col-sm-2 col-form-label']) }}
        <div class="col-sm-10">
            {{ Form::text('title', null, ['class' => 'form-control',  'placeholder' => 'Digite um Titulo','required' => true]) }}
        </div>
    </div>

    <div class="form-group row">
        {{ Form::label('metadata', 'Sub-título', ['class' => 'col-sm-2 col-form-label']) }}
        <div class="col-sm-10">
            {{ Form::text('subtitle', null, ['class' => 'form-control',  'placeholder' => 'Digite um Sub-Titulo']) }}
        </div>
    </div>
</div>

<div class="form-group row">
    <label for="metadata" class="col-sm-2 col-form-label">Cor de fundo:</label>
    <div class="col-sm-10">
        <input name="" type="checkbox" value="background" onclick="enableColorsBackground(this.checked)"> Usar Padrão do site
        <input type="color" name="background" id="background">
    </div>
</div>

<div class="form-group row">
    {{ Form::label('metadata', 'Cor do título:', ['class' => 'col-sm-2 col-form-label']) }}
    <div class="col-sm-6">
        <input name="" type="checkbox" value="color-title" onclick="enableColorsTitle(this.checked)"> Usar Padrão do site
        <input type="color" name="color-title" id="color-title">
    </div>
</div>

<div class="form-group row">
    {{ Form::label('metadata', 'Padrões da Galeria', ['class' => 'col-sm-2 col-form-label']) }}
</div>

<div class="form-group row">
    {{ Form::label('metadata', 'Cor de Fundo Padrão:', ['class' => 'col-sm-2 col-form-label']) }}
    <div class="col-sm-6">
        <input name="" type="checkbox" value="background_item" onclick="enableColorsBackgroundItem(this.checked)"> Usar Padrão do site
        <input type="color" name="background_item" id="background_item">
    </div>
</div>

<div class="form-group row">
    {{ Form::label('metadata', 'Alvo do Link Padrão:', ['class' => 'col-sm-2 col-form-label']) }}
    <div class="col-sm-10">
        {{ Form::select('target_item', ['self' => 'Menu Página', 'blank' => 'Nova Página', 'modal' => 'Modal'], null , ['class' => 'form-control']) }}
    </div>
</div>

{{-- Scripts --}}
<script>
    function enableColorsBackground(background) {
        document.getElementById('background').hidden = background;
    }

    function enableColorsTitle(title) {
        document.getElementById('color-title').hidden = title;
    }

    function enableColorsBackgroundItem(item) {
        document.getElementById('background_item').hidden = item;
    }

</script>
05 Feb
4 months ago

romulo27 started a new conversation Enable Form Fields With JS With Radio Button

I'm starting with Javascript and I have a small problem.

I have an HTML form where I have a radio field where I have two options, Text and Page. When I click on the Text option it loads an input field to insert the title, when I select the Page it shows me two fields an input with title and subtitle.

How would I do this logic?

<div class="form-group row">
    <label for="title-type" class="col-sm-2 col-form-label">Tipo Título:</label>
    <div class="col-sm-2">
        <input name="title-type" type="radio" value="text" id="title-type" onclick="typeRadioButton()"> Texto
    </div>
    <div class="col-sm-2">
        <input name="title-type" type="radio" value="page" id="title-type" onclick="typeRadioButton()"> Página
    </div>
</div>

<div class="form-group row">
    {{ Form::label('metadata', 'Título', ['class' => 'col-sm-2 col-form-label']) }}
    <div class="col-sm-10">
        {{ Form::text('title', null, ['class' => 'form-control',  'placeholder' => 'Digite um Titulo', 'required' => true]) }}
    </div>
</div>

<div class="form-group row">
    {{ Form::label('metadata', 'Sub-título', ['class' => 'col-sm-2 col-form-label']) }}
    <div class="col-sm-10">
        {{ Form::text('pagetitle', null, ['class' => 'form-control',  'placeholder' => 'Digite um Sub-Titulo', 'required' => true]) }}
    </div>
</div>

<div class="form-group row">
    {{ Form::label('metadata', 'Conteúdo', ['class' => 'col-sm-2 col-form-label']) }}
    <div class="col-sm-10">
        {{ Form::textarea('slot', null, ['class' => 'form-control', 'required' => true]) }}
    </div>
</div>

<div class="form-group row">
    {{ Form::label('metadata', 'Cor de fundo:', ['class' => 'col-sm-2 col-form-label']) }}
    <div class="col-sm-10">
        {{ Form::checkbox('Usar Padrão do site', '', false) }} Usar Padrão do site
        <input type="color" name="background ">
    </div>
</div>

<div class="form-group row">
    {{ Form::label('metadata', 'Cor do título:', ['class' => 'col-sm-2 col-form-label']) }}
    <div class="col-sm-10">
        {{ Form::checkbox('Usar Padrão do site', '', false) }} Usar Padrão do site
        <input type="color" name="color-title">
    </div>
</div>

<div class="form-group row">
    {{ Form::label('metadata', 'Cor do texto:', ['class' => 'col-sm-2 col-form-label']) }}
    <div class="col-sm-10">
        {{ Form::checkbox('Usar Padrão do site', '', false) }} Usar Padrão do site
        <input type="color" name="color-text">
    </div>
</div>


{{-- JQuert--}}
<script>
    function typeRadioButton() {
        var type = document.getElementsByName("title-type");

        if (type[0].checked) {
            alert('Text');

        } else if (type[1].checked) {
            alert('Page');
        }
    }

</script>
01 Feb
4 months ago

romulo27 left a reply on Passing Id To The Route

 Route::group([
            'as' => 'pages.',
            'prefix' => 'pages/{page}',
            'middleware' => 'managercontext:website_page'
        ], function() {

            Route::resource('components', 'Website\PageContentComponentsController', [
                'only' => ['show', 'create', 'store', 'edit', 'update', 'destroy']
            ]);
        });

romulo27 started a new conversation Passing Id To The Route

I have a route in the view to direct me to edit a component, but when I pass the id it does not work. What would be the problem?

<div class="list-group">
    @foreach( $components as $value)
            <div class="form-group row">
                <label class="col-sm-6 col-form-label">{{$value->order}} - {{ $value->component }}</label>
                <div class="col-sm-6">
                    <a href="#" class="fa fa-angle-double-up btn btn-primary btn-sm"></a>
                    <a href="#" class="fa fa-angle-double-down btn btn-primary btn-sm"></a>
                    <a href="{{ route('website.pages.components.edit',  [$website, $page, 'component' => $value->component]) }}"
                       class="btn btn-warning btn-sm">Editar</a>
                    <a href="" class="btn btn-danger btn-sm">Deletar</a>
                </div>
            </div>
        @endforeach

    <a class="btn btn-primary" href="{{ route('website.pages.components.create', [$site, $slug]) }}"> Adicionar
        Componente </a>
</div>
31 Jan
4 months ago

romulo27 left a reply on Call To A Member Function GetKey() On Null

@MANOJOW - My controller

<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\Site;
use App\Models\SiteContentComponent;
use App\Modules\ContextManager\Dictionary\ContextManagerGroupDictionary;
use Gblix\Controllers\CrudTraits\Create;
use Gblix\Controllers\CrudTraits\Read;
use Gblix\Controllers\CrudTraits\Retrieve;
use Gblix\Controllers\CrudTraits\Update;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\ModelRepositories\SiteContentComponentRepository as ModelRepository;
use App\DataTables\ThemeComponentsDataTable as ModelDataTable;

class PageContentComponentsController extends Controller {

    use Read, Retrieve, Create, Update;

    public function __construct(ModelRepository $repository) {

        $this->repository = $repository;
        $this->context = ContextManagerGroupDictionary::WEBSITE_PAGE;
        $this->resource = 'components';
        $this->routeKey = 'component';
        $this->modelNameAttribute = 'title';
        $this->titles = [
            'index' => 'Conteúdo do Site',
            'create' => 'Cadastrando Componente',
            'edit' => 'Editando Componente',
        ];
    }

    /**
     * Exibe a tela de registros da Model conforme DataTable da Model.
     *
     * @param Request $request
     * @param ModelDataTable $dataTable
     * @return \Illuminate\View\View
     */
    public function index(Request $request, ModelDataTable $dataTable)
    {
        return $this->makeIndex($dataTable);
    }

    public function create(Request $request, ModelDataTable $dataTable)
    {
        $components = $dataTable->query();

        $this->data['components'] = $components;

        return $this->makeCreate();
    }

    /**
     * @return string
     */
    protected function makeCreateFormView(): string {
        /* @var $request Request */
        $request = app('request');


        if($request->has('component')) {
            /* @var $website Site */
            $website = $request->route('website');
            $theme = $website->theme;

            $component = $request->get('component');
            // views de componentes
            return 'themes.' . $theme . '.website_components.' . $component;
        }

        return 'website.pages.components.create';
    }

    /**
     * @return string
     */
    protected function makeEditFormView(): string {
        /* @var $entry SiteContentComponent */
        $entry = $this->getCurrentEntry();

        $theme = $entry->contents->site->theme;
        $component = $entry->component;

        return 'themes.' . $theme . '.website_components.' . $component;
    }

    /**
     * Operações para serem realizada antes do create da Model.
     *
     * @param Request $request
     * @param $data
     * @return array
     */
    public function beforeStore(Request $request, $data) {
        //dd($data);
        $data['id'] = $request->route('pages')->getKey();

        return $data;
    }

    /**
     * Retorna a rota para a store.
     *
     * @param Request $request
     * @return array|string
     */
    protected function makeStoreRedirectRoute(Request $request) {

        /* @var $website Site */
        $website= $request->route('website');
        $page = $request->route('pages');

        $context = $this->context;

        $route = [ 'website.pages.edit', $page, $website];

        return $route;
    }

    protected function makeEditFormRoute(Request $request, Model $model) {

        /* @var $website Site */
        $website = $request->route('website');
        $pages = $request->route('pages');
        $components = $request->route('components');

        $context = $this->context;
        $resource = $this->resource;

        return [$context . '.' . $resource . '.update', $pages, $website, $components, $model];
    }


    protected function formFields(Model $model): array
    {
        $fields = [];

        return $fields;
    }
}

romulo27 started a new conversation Call To A Member Function GetKey() On Null

I am trying to save the form data, but I have this error. Call to a member function getKey () on null

I'am using Crud Trait

@section('breadcrumbs', Breadcrumbs::render($context . '.' . $resource . '.create'))
@php($website = request()->route('website'))
@php($page = request()->route('page'))

@section('base')
    <form method="post" action="{{ route('website.pages.components.store', [$website, $page]) }}">
        @csrf
        <div class="form-group row">
            {{ Form::label('metadata', 'Titulo:', ['class' => 'col-sm-2 col-form-label']) }}
            <div class="col-sm-10">
                <input name="" type="text" class="form-control" placeholder="Digite um titulo" required>
            </div>
        </div>

        <div class="offset-md-2">
            {{ Form::submit('Adicionar', ['class' => 'btn btn-success']) }}
        </div>
    </form>


@endsection
```






public function beforeStore(Request $request, $data) { //dd($data); $data['id'] = $request->route('pages')->getKey();

    return $data;
}


This line:  `$data['id'] = $request->route('pages')->getKey();`
30 Jan
4 months ago

romulo27 left a reply on Dynamic Routes In Laravel

http://suzuki.test/website/haojue/pages/sed-libero-ipsam-quia-nihil-dolo/components/create?component=page-simpleheader
```

romulo27 left a reply on Dynamic Routes In Laravel

It looks like the route, but when I click on the option it does not go to the view.

<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Modules\ContextManager\Dictionary\ContextManagerGroupDictionary;
use Gblix\Controllers\CrudTraits\Create;
use Gblix\Controllers\CrudTraits\Read;
use Gblix\Controllers\CrudTraits\Retrieve;
use Gblix\Controllers\CrudTraits\Update;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\ModelRepositories\SiteContentComponentRepository as ModelRepository;
use App\DataTables\ThemeComponentsDataTable as ModelDataTable;

class PageContentComponentsController extends Controller {

    use Read, Retrieve, Create, Update;

    public function __construct(ModelRepository $repository) {

        $this->repository = $repository;
        $this->context = ContextManagerGroupDictionary::WEBSITE_PAGE;
        $this->resource = 'components';
        $this->routeKey = 'component';
        $this->modelNameAttribute = 'title';
        $this->titles = [
            'index' => 'Conteúdo do Site',
            'create' => 'Cadastrando Componente',
            'edit' => 'Editando Componente',
        ];
    }

    /**
     * Exibe a tela de registros da Model conforme DataTable da Model.
     *
     * @param Request $request
     * @param ModelDataTable $dataTable
     * @return \Illuminate\View\View
     */
    public function index(Request $request, ModelDataTable $dataTable)
    {
        return $this->makeIndex($dataTable);
    }

    public function create(Request $request, ModelDataTable $dataTable)
    {
        $components = $dataTable->query();

        $this->data['components'] = $components;

        return $this->makeCreate();
    }

    /**
     * @return string
     */
    protected function makeCreateFormView(): string {

        return 'website.pages.components.create';
    }

    /**
     * @return string
     */
    protected function makeEditFormView(): string {

        return 'website.pages.components.edit';
    }

    protected function formFields(Model $model): array
    {
        $fields = [];

        return $fields;
    }
}

romulo27 left a reply on Dynamic Routes In Laravel

@TRAY2 - How do I get the view for this route?

romulo27 left a reply on Dynamic Routes In Laravel

<a href="{{ route('website.pages.components.create', [$website, $page, 'component' => $component->component]) }}" class="list-group-item list-group-item-action btn btn-outline-primary">{{ $component->title }}</a>

romulo27 started a new conversation Dynamic Routes In Laravel

I have to create a route to access a form from a certain component of a CMS. My question to myself does I pass the parameter in the url to enter this context? I'm loading these components from a configuration made in component.yaml

I have this route: website / haojue / pages / ea-enim-eligendi-provident-ratio / components / create

But I need this: website / haojue / pages / ea-enim-eligendi-provident-ratio / components / create? Component = page-simpleheader

List Components

@section('base')
    <div class="list-group">
        @foreach( $components as $component)
            <a href="" class="list-group-item list-group-item-action btn btn-outline-primary">{{ $component->title }} : {{ $component->component }}</a>
        @endforeach
    </div>
@endsection
```


Route
```
  Route::group([
            'as' => 'pages.',
            'prefix' => 'pages/{page}',
            'middleware' => 'managercontext:website_page'
        ], function() {

            Route::resource('components', 'Website\PageContentComponentsController', [
                'only' => ['show', 'create', 'store', 'edit', 'update', 'destroy']
            ]);
        });
```
25 Jan
4 months ago

romulo27 left a reply on How Do I Pass The Value Of The Token Inside The Transformer?

public function transform($user) { return [ 'id' => (int)$user->id, 'name' => $user->name, 'email' => $user->email, 'photo_url' => $user->photo_url, 'active' => $user->active, 'phone_number' => $user->phone_number, 'company_id' => $user->company_id, 'token' => $user->token, ]; }

22 Jan
5 months ago

romulo27 left a reply on Laravel @forelse

<em>{{ $prices->price ?? ' - ' }}</em> <br>

@if($prices && $prices->infos_home)
    @foreach($prices->infos_home as $info)
        <em>{{ $info }}</em> <br>
    @endforeach
@else
    <em> - </em>
@endif 

romulo27 started a new conversation Laravel @forelse

I have a problem with my view of laravel. I have a field that executes a loop, and if it has data in the field it list, but if it does not it only shows me nothing.

I used @forelse but it does not work, any help?

with $prices I can check whether or not it has the value, but in that fieldinfos_home does not. I used @forelse but it does not work, any help?

<em>{{ $prices->price ?? ' - ' }}</em> <br>

@forelse($prices->infos_home as $info)
    <em>{{ $info }}</em> <br>
@empty
    <em> - </em>
@endforelse



When I use @forelse I have the following error message.

message: "Method Illuminate\View\View::__toString() must not throw an exception, caught ErrorException: Trying to get property 'infos_home' of non-object (View: C:\wamp64\www\suzuki-cms-backoffice\resources\views\brand\motorcycle\variations\index\column-price.blade.php)"

romulo27 started a new conversation Listing Data From A Json Field

Guys I have a Json field, where to save the data. I wanted to display this in the view, how?

I'm using a dictionary for this.

@php($motorcycle = request()->route('motorcycle'))
@php($brand = request()->route('brand'))
@php($slug = $model->getRouteKey())
@php($prices = $model->price)
<ul class="list-inline">
        <em> {{ $prices->price }} </em><br>
    <li>
        @component('admin.default.table.action.edit')
            @slot('url', route('brand.motorcycle.variation.prices.create', [$brand, $motorcycle, $slug]))
            @slot('label', 'Gerenciar')
        @endcomponent
    </li>
</ul>





public function up() { Schema::create('motorcycle_variations_price', function (Blueprint $table) { $table->unsignedInteger('id'); $table->decimal('price', 10, 2)->nullable(); $table->json('infos_home'); $table->timestamps();

        $table->foreign('id')->references('id')->on('motorcycle_variations');
        $table->primary('id');

    });
}
class VariationInfoDictionary extends StaticDictionary {

    const FREIGHT_INCLUDED = '*Frete incluso';

    const FREIGHT_NOT_INCLUDED = '*Frete não incluso';

    const EXCHANGEABLE = 'Consulte-nos para condições de troca';

    const FREIGHT_COUNTRY = 'Enviamos para todo Brasil';

    const FREIGHT_CONDITIONAL = 'Consulte-nos para condições de frete';

    const SHIPS_HOME = 'Receba a moto em casa pronta para  uso';

    protected static $dictionary = [

        self::FREIGHT_INCLUDED => '*Frete incluso',
        self::FREIGHT_NOT_INCLUDED => '*Frete não incluso',
        self::EXCHANGEABLE => 'Consulte-nos para condições de troca',
        self::FREIGHT_COUNTRY => 'Enviamos para todo Brasil',
        self::FREIGHT_CONDITIONAL => 'Consulte-nos para condições de frete',
        self::SHIPS_HOME=> 'Receba a moto em casa pronta para  uso',
    ];
}

romulo27 left a reply on Laravel With Crud Traits

@RODRIGO.PEDRA - I do not think it was that simple, but I have the relationship between price and variation, but not between variation and price

 Schema::create('motorcycle_variations_price', function (Blueprint $table) {
            $table->unsignedInteger('id');
            $table->decimal('price', 10, 2);
            $table->json('infos_home');
            $table->timestamps();

            $table->foreign('id')->references('id')->on('motorcycle_variations');
            $table->primary('id');

        });




class MotorcycleVariationsPrice extends Model {


    protected $table = 'motorcycle_variations_price';

    protected $fillable = [
        'id',
        'price',
        'infos_home',
    ];

    protected $dates = [
        'created_at',
        'updated_at'
    ];

    protected $casts = [
        'infos_home' => 'array',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function variation() {
        return $this->belongsTo(MotorcycleVariations::class);
    }
}

romulo27 left a reply on Laravel With Crud Traits


class VariationsPriceController extends Controller {

    use Read, Retrieve, Create, Update, Delete;

    /**
     * VariationsPriceController constructor.
     * @param ModelRepository $repository
     */
    public function __construct(ModelRepository $repository) {
        $this->repository = $repository;
        $this->context = ContextManagerGroupDictionary::BRAND_MOTORCYCLE_VARIATION;
        $this->resource = 'prices';
        $this->modelNameAttribute = 'name';
        $this->titles = [
            'index' => 'Preços de Variação da Motocicleta',
            'create' => 'Cadastrando Preços',
            'edit' => 'Editando Preços',
        ];
    }

    /**
     * Exibe a tela de registros da Model conforme DataTable da Model
     *
     * @param Request $request
     * @param ModelDataTable $dataTable
     * @return \Illuminate\View\View
     */
    public function index(Request $request, ModelDataTable $dataTable) {

        /* @var $motorcycle Motorcycle */
        $motorcycle = $request->route('motorcycle');
        $brand = $request->route('brand');
        $variation = $request->route('variations');

        $dataTable->addScope(new MotorcycleVariationPriceContextScope(['variations' => $variation]));

        $options = [[
            'button' => 'Novo Preço',
            'url' => route('brand.motorcycle.prices.create', [$brand, $motorcycle, $variation->getRouteKey()])
        ]];

        $this->data['options'] = $options;

        return $this->makeIndex($dataTable);
    }

    /**
     * {@inheritdoc}
     *
     * @throws \Prettus\Repository\Exceptions\RepositoryException
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     *
     */
//    public function create() {
//
//        $this->makeCreate();
//        $this->makeUpdate();
//    }

    /**
     * Operações para serem realizada antes do create da Model.
     *
     * @param Request $request
     * @param $data
     * @return array
     */
    public function beforeStore(Request $request, $data) {

        $data['id'] = $request->route('variation')->getKey();

        return $data;
    }

    /**
     * Retorna a rota para a store.
     *
     * @param Request $request
     * @return array|string
     */
    protected function makeStoreRedirectRoute(Request $request) {

        /* @var $motorcycle Motorcycle */
        $motorcycle = $request->route('motorcycle');
        $brand = $request->route('brand');

        $context = $this->context;

        $route = [ 'brand.motorcycle.variations.index', $brand, $motorcycle];

        return $route;
    }

    /**
     * Retorna a rota para store
     *
     * @param Request $request
     *
     * @return array
     */
    protected function makeCreateFormRoute(Request $request) {

        /* @var $motorcycle Motorcycle */
        $motorcycle = $request->route('motorcycle');
        $brand = $request->route('brand');
        $variation = $request->route('variation');

        $context = $this->context;
        $resource = $this->resource;

        return [$context . '.' . $resource . '.store', $brand, $motorcycle, $variation];
    }

   /**
     * Retorna os campos responsáveis pelo cadastramento/edição do Model neste Controller.
     *
     * @param EloquentModel $model
     * @return array
     */
    protected function formFields(EloquentModel $model): array {
        $inputs = [];

        $inputs[] = [
            'name' => 'price',
            'label' => 'Preço da Variação',
        ];

        $inputs[] = [
            'name' => 'infos_home',
            'label' => 'Informações Adicionais',
            'type' => 'checkbox',
            'values' => [
                'freight_included' => VariationInfoDictionary::FREIGHT_INCLUDED,
                'freight_not_included' => VariationInfoDictionary::FREIGHT_NOT_INCLUDED,
                'freight_country' => VariationInfoDictionary::FREIGHT_COUNTRY,
                'freight_conditional' => VariationInfoDictionary::FREIGHT_CONDITIONAL,
                'exchangeable' => VariationInfoDictionary::EXCHANGEABLE,
                'ships_home' => VariationInfoDictionary::SHIPS_HOME,
            ]
        ];

       return $inputs;
    }
}

romulo27 started a new conversation Laravel With Crud Traits

Guys, I need some help. I have a Product and a template for it, the template of these products may just have a price attached to it. When I create a price for the model I need to check if it already has the price, if it has I redirect it to update. How to make?

16 Jan
5 months ago

romulo27 left a reply on I Need To Show Array Of An Array

the dd ($ menu) returns me all the data up to the submenus, but I wanted to grab each menu index and check if it has submenu in it, if it has, just list the title of it.