cac

cac

Member Since 1 Year Ago

Uberlandia

Experience Points 2,590
Experience Level 1

2,410 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 9
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.

12 Jun
6 days ago

cac started a new conversation L5.2 Form Request With Comma Separated String

I need to validate a comma separated string. My rules are working as long as I work with array on the request but I've been required to use comma separated string array. I heard about some method called prepareForValidation() but it seems to be not available on L5.2.

here are my validation rules:

 public function rules()
    {
        return [
            'array1.*' => 'required|numeric|exists:table1,id',
            'array2.*' => 'required|string|exists:table2,column',
        ];
    }

How can I convert my comma separated string before the validation occurs?

11 Jun
1 week ago

cac left a reply on L5.2 [ReflectionException] Class 'ClassName' Does Not Exist

@TISUCHI - Man I must be blind because I didnt see what you did there. It all look the same to me...

10 Jun
1 week ago

cac started a new conversation L5.2 [ReflectionException] Class 'ClassName' Does Not Exist

Guys I’m getting the following error when I try to run php artisan route:list. Theoretically there is no mistakes on the naming convention.

[ReflectionException] Class 'ClassName' does not exist

I created a controller from the CLI and I am pretty sure it exists

Here's what I tried so far:

  1. composer dump-autoload
  2. composer install
  3. php artisan config:cache
  4. php artisan config:clear

Here's my autoload from composer:

"autoload": {
        "classmap": [
            "database",
            "app/Http/Controllers",
            "app/Models",
            "app/Console/Commands"
        ],
        "psr-0": {
            "scdda": "app/"
        },
        "psr-4": {
            "App\": "app/"
        }
    }

Here is the route:

Route::resource('workingLineOpportunities','WorkingLineOpportunitiesController',['only'=>['index','delete']]);

and here's my newly created controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class MyNewController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
11 Apr
2 months ago

cac left a reply on Vuejs Component Simply Not Loading

@SERGIU17 - Thank you man. That is an important step that seems to be missing in the laravel documentation.

cac started a new conversation Vuejs Component Simply Not Loading

I am trying to experiment vue js on a new fresh laravel installation and it simply does not work even though I follow the documentation.

I did ran the following commands: npm install npm run watch

Everything compiles perfectly but and there are no errors on the console

app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

Vue.component('app', require('./components/App.vue'));

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app'
});

Webpack.mix.js

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

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

App.vue

<template>
    <div class="app-component">
        <p>App Component</p>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>

<style scoped>

</style>

Welcome.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel</title>

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

    <!-- Styles -->
    <style>
        html, body {
            background-color: #fff;
            color: #636b6f;
            font-family: 'Nunito', sans-serif;
            font-weight: 200;
            height: 100vh;
            margin: 0;
        }

        .full-height {
            height: 100vh;
        }

        .flex-center {
            align-items: center;
            display: flex;
            justify-content: center;
        }

        .position-ref {
            position: relative;
        }

        .top-right {
            position: absolute;
            right: 10px;
            top: 18px;
        }

        .content {
            text-align: center;
        }

        .title {
            font-size: 84px;
        }

        .links > a {
            color: #636b6f;
            padding: 0 25px;
            font-size: 13px;
            font-weight: 600;
            letter-spacing: .1rem;
            text-decoration: none;
            text-transform: uppercase;
        }

        .m-b-md {
            margin-bottom: 30px;
        }
    </style>
</head>
<body>
<div id="app">
    <app></app>
    
</div>

</body>
</html>

21 Mar
2 months ago

cac started a new conversation [HELP] Querying With Groupby

Models and relationship ModelA ModelB

ModelA belongs to ModelB ModelB has many ModelA

Controller

$arrayModelA = ModelA::where('some_fk',$id)->get();
$groupedModelA = arrayModelA->groupBy('model_b_id')

Result [ model_b_id => ModelAarray[] model_b_id => ModelAarray[] ]

Desired result

[ SomeModelBObject => ModelACollection[] SomeOtherModelBObject => ModelACollection[] ]

My grouped query is working fine grouping it by the model_b_id. The problem is that it doesn't bring the modelB object instead it groups simply by the field id. I need to have the entire object.

How can I achieve this?

01 Mar
3 months ago

cac left a reply on Jquery Ajax Dependent Select

I'm sorry guys! My bad! I implemented the function on the wrong controller. It took my a while to realize it LOL. Guess I was too tired

28 Feb
3 months ago

cac started a new conversation Jquery Ajax Dependent Select

I am trying to update the options of a select when some other select suffer the change event. Here is what I wrote. I dont understand why I am getting error 500. Can anyone please help me?

view:

<div class="form-group row">
                            <label for="occupation_area_id"
                                   class="col-4 col-form-label text-md-right">{{ __('labels.Occupation Area') }}
                                *</label>
                            <div class="col-6">
                                <select required
                                        class="form-control{{ $errors->has('occupation_area_id') ? ' is-invalid' : '' }}"
                                        name="occupation_area_id"
                                        id="occupation_area_id">
                                    <option value="" selected>{{__('labels.Select')}}</option>
                                    @foreach($occupationAreas as $occupationArea)
                                        <option value="{{$occupationArea->id}}">{{$occupationArea->name}}</option>
                                    @endforeach
                                </select>
                                @if ($errors->has('occupation_area_id'))
                                    <span class="invalid-feedback" role="alert">
                                <strong>{{ $errors->first('occupation_area_id') }}</strong>
                             </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="specialty_id"
                                   class="col-4 col-form-label text-md-right">{{ __('labels.Specialties') }}
                                *</label>
                            <div class="col-6">
                                <select required
                                        multiple="multiple"
                                        class="form-control
                                        form-control{{ $errors->has('specialty_id') ? ' is-invalid' : '' }}"
                                        name="specialty_id"
                                        id="specialty_id">
                                    <option value="" selected>{{__('labels.Select')}}</option>

                                </select>
                                @if ($errors->has('specialty_id'))
                                    <span class="invalid-feedback" role="alert">
                                <strong>{{ $errors->first('specialty_id') }}</strong>
                             </span>
                                @endif
                            </div>
                        </div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        $('#occupation_area_id').on('change', function () {
            var occupationAreaId = $(this).val();
            console.log(occupationAreaId);
            if (occupationAreaId) {
                $.ajax({
                    type: 'POST',
                    url: '{{route('ajax.occupation-area-skills')}}',
                    data: JSON.stringify({
                        _token: '<?php echo csrf_token() ?>',
                        id: occupationAreaId
                    }),
                    contentType: 'application/json; charset=utf-8',
                    success: function (result, status, xhr) {
                        console.log(result);

                    }
                });
            } else {
                $('#specialty_id').html('<option value="">Select Occupation Area</option>');
            }
        });
    });
</script>

Backend

public function specialties(Request $r)
    {
        $data = $this->skillRepository->allByOccupationAreaId($r->get('id'));
        return $data ? response()->json($data, 200) : response()->json(['data' => 'Not Found'], 404);

    }

Routes

//Ajax
Route::middleware(['auth'])->group(function () {
    Route::name('ajax.')->group(function () {
        Route::post('ajax/specialty/', 'Ajax\[email protected]')->name('occupation-area-skills');
    });

});
09 Feb
4 months ago

cac started a new conversation Creating A Whitelabel Area In A Project

Has anyone ever whitelabeled a system with laravel?

I have a SaaS which I maintain my clients and my users using it. They both have the same login in the plataform but with different views based on their roles.

Now I need to allow my users to login into my client’s public page. But this needs to be whitelabel therefore cannot be the same login. I am stuck on how to create this totally new and separated login/area on the same project.

Example: /{clientename}/login /{clientname}/dashboard etc..

I came from .NET where I could just create an area inside a project which was sort of a new project inside an existing one.

Is there a way to achieve this on laravel?

Any tips?

01 Jan
5 months ago

cac started a new conversation How Can I Filter By Relationship?

I have a model called Company which may have many Vacancy models. And this Vacancy has one PipeVacancy. So my question is how can I filter the query to bring me only the Vacancies that already have a PipeVacancy. I was think maybe I could achieve this with scoped queries but I had no idea how to write that piece of code. What I want with this is to avoid that inner @if.

                 @foreach($company->vacancies as $vacancy)
                                    @if($vacancy->pipeVacancy)
                                        <li>
                                            <div class="row">
                                                <div class="col-md-8">
                                                    {{$vacancy->title}}
                                                </div>
                                                <div class="col-md-4">
                                                    <a href="{{route('myroute',$vacancy->id)}}">
                                                        <button class="btn btn-sm btn-success"
                                                                type="button">{{__('labels.Apply')}}
                                                        </button>
                                                    </a>
                                                </div>
                                            </div>
                                        </li>
                                    @endif
                                @endforeach

Any tips?

31 Dec
5 months ago

cac left a reply on Grouping Routes

I got it! This route right here was overriding my first resource index route:

Route::get('/', 'Manager\[email protected]')->name('benefit.index');

That happened because of the "/", I simply changed it like this:

Route::get('benefit', 'Manager\[email protected]')->name('benefit.index');

And it worked!

cac left a reply on Grouping Routes

@DIGITALIZED - Yes I did and it's missing the manager.index route and I simply can't see my mistake here. It is the only route missing

cac started a new conversation Grouping Routes

I have this group of routes where my resource route is missing the index route and I can't figure it out. Has anyone seen this problem?

Route::middleware(['manager'])->group(function () {
        Route::resource('manager', 'Manager\ManagerController');
        Route::prefix('manager')->group(function () {
            Route::name('manager.')->group(function () {
                Route::get('home', 'Manager\HomeController')->name('home');

                Route::resource('vacancy', 'Manager\VacancyController');
                //Benefits
                Route::get('/', 'Manager\[email protected]')->name('benefit.index');
                Route::post('vacancy/{vacancy}/benefit', 'Manager\[email protected]')->name('benefit.store');
                Route::get('vacancy/{vacancy}/benefit', 'Manager\[email protected]')->name('benefit.create');
                Route::get('{benefit}/edit', 'Manager\[email protected]')->name('benefit.edit');
                Route::get('benefit/{benefit}', 'Manager\[email protected]')->name('benefit.show');
                Route::put('benefit/{benefit}', 'Manager\[email protected]')->name('benefit.update');
                Route::delete('vacancy/{vacancy}/benefit/{benefit}', 'Manager\[email protected]')->name('benefit.destroy');
                //Pipes
                Route::resource('pipe', 'Manager\PipeController');
                Route::resource('pipe-stage', 'Manager\PipeStageController');
            });
        });
    });

What am I missing?

21 Dec
5 months ago

cac left a reply on How To Check If A Record Belongs To A User?

@WILK_RANDALL - That is what I did. But I was wondering if there was something I could co using eloquent, like:

´´´ $post->user->has(Auth::user()) ´´´

cac started a new conversation How To Check If A Record Belongs To A User?

Let's say my User can make blog posts. I have now retrieved a blog post and I want check if the given blog post belongs to the authenticated user so it can be edited. I was able to accomplish that but it doesn't seem the best way to do it.

27 Nov
6 months ago

cac left a reply on Do You Prefer Helper Functions Over Facades/DI?

I really like to use as much default functions as possible. So I'd generally do in the first way. Also I like to use form validation request because it prevents unnecessary data processing if the form is not valid.

https://laravel.com/docs/5.7/validation#form-request-validation

cac left a reply on How To Validate A Laravel Form Using JQuery Ajax

I often find the form request validation the best way to do it. This way laravel will validate the request before it hits the action thus preventing unnecessary data processing and possible errors. And it is very easy to use

https://laravel.com/docs/5.7/validation#form-request-validation

26 Nov
6 months ago

cac left a reply on Relationship Convention For A Particular Case

@D9705996 - I am concerned that both FK pointing to the same column in the same table might be trouble. What you think? But thank you anyway, you already pointed me to right path.

cac started a new conversation Relationship Convention For A Particular Case

Usually I review laravel's official documentation for relationship conventions but this time I didn't see any that fits my scenario. Can anyone please help me?

I have a USERS table and a REFERRALS table in which a user can refer another user (one to many). So the REFERRALS table would be like this:

|REFERRALS | |------------------------| |id | |user_id(referee) | |user_id(referred)|

What would be the convention or the most elegant way to implement this? Is there a way that I don't need to do any customization to the relationship? How would I write the relationship methods on the model in this case?

21 Nov
6 months ago

cac left a reply on Compiling Assets

@D9705996 - @d9705996 thank you. But lemme ask you one more thing. Not doing this is a security breach or is it only good practice to do so? Because I have never compiled assets before and I'm worried that JS can easily be modified to harm the application.

cac started a new conversation Compiling Assets

I'm mostly backend developer and very weak on the frontend. Recently I wanted to learn frontend best practices in laravel and I ran into the compilling assets page in the official documentation.

i didn't quite understand the process and what it means or why I have to do it. I usually always open a script tag on my views and write all my JS functions but I was worried it isn't a good practice concerning security.

Also in the official documentation it explains about the MIX:

    mix.less('resources/less/app.less', 'public/css')
   .less('resources/less/admin.less', 'public/css');

I understand what those lines do but it is not clear to me where I should write that.

Can anyone please be so kind as to elaborate on the this topic in a easier way? Often I find the laravel DOCS very easy to understand but not this time.

22 Oct
7 months ago

cac left a reply on Blade File Not Rendering <script></script> L5.7

@Cronix other than the script not working( although this used to work not so long ago), no. I will try to remove my topic

cac left a reply on Blade File Not Rendering <script></script> L5.7

@Snapey Sorry, in the view source I see my script tag yes

cac left a reply on Blade File Not Rendering <script></script> L5.7

@Snapey Yes I see everything but the script tag

cac left a reply on Blade File Not Rendering <script></script> L5.7

@Cronix yes, they dont show up when I look at the source on the browser as if I never coded it

cac left a reply on Blade File Not Rendering <script></script> L5.7

@Cronix I just did and still does not render the script tag

cac started a new conversation Blade File Not Rendering <script></script> L5.7

I have a script tag (pure javascript) appended to the end of my html and it is not rendering the script tag. I used to simply open a script tag in older versions of laravel but now in this version it is not working. Does anyone have a clue?

@extends('layouts.app')
@section('content')
    @if(session('msg'))
        <div class="alert alert-danger">
            <p>{{session('msg')}}</p>
        </div>
    @endif
    @if($cars)

        <div class="row">
            <input id="term" name="term" autofocus placeholder="Buscar" type="text" class="form-control">

        </div>
        <br>
        <div class="row">
            <table id="table" class="table table-sm  table-condensed table-hover">
                <caption>List de Carros</caption>
                <thead class="thead-dark">
                <tr>
                    <th>#</th>
                    <th>Modelo</th>
                    <th>Quantidade</th>
                    <th>Marca</th>
                    <th>Preço</th>
                    @if(Auth::user()->isAdmin())
                        <th>Ações</th>
                    @endif

                </tr>
                </thead>
                <tbody>
                @foreach($cars as $car)
                    <tr>
                        <td>{{$car->id}}</td>
                        <td>{{ $car->model }}</td>
                        <td>{{ $car->quantity }}</td>
                        <td>{{ $car->brand->name }}</td>
                        <td>R$ {{ $car->price }}</td>
                        @if(Auth::user()->isAdmin())
                            <td>
                                <a href="{{route('cars.edit',$car->id)}}">
                                    <button class="btn btn-sm btn-primary" type="button">Editar</button>
                                </a>
                                <form method="POST" action="{{route('cars.destroy',$car->id)}}">
                                    @method('DELETE')
                                    @csrf
                                    <button class="btn btn-sm btn-danger" type="submit">Deletar</button>
                                </form>
                            </td>
                        @endif
                    </tr>
                @endforeach
                </tbody>
            </table>
        </div>
        <script>
            function filterTable(event) {
                debugger;
                var filter = event.target.value.toUpperCase();
                var rows = document.querySelector("#table tbody").rows;
                for (var i = 0; i < rows.length; i++) {
                    var firstCol = rows[i].cells[0].textContent.toUpperCase();
                    var secondCol = rows[i].cells[1].textContent.toUpperCase();
                    var thirdCol = rows[i].cells[4].textContent.toUpperCase();
                    if (firstCol.indexOf(filter) > -1 || secondCol.indexOf(filter) > -1 || thirdCol.indexOf(filter) > -1) {
                        rows[i].style.display = "";
                    } else {
                        rows[i].style.display = "none";
                    }
                }
            }

            document.querySelector("#term").addEventListener('keyup', filterTable, false);
        </script>
    @else
        <div class="text-center">
            <p>Nenhum registro encontrado</p>
        </div>
    @endif

@endsection


02 Sep
9 months ago

cac left a reply on What Is The Best Way To Implement Self Reference? Laravel 5.5.4

@Snapey when I thought of that I was about to implement it myself and I would run the loop while the parent_id != id. But thanks to @lionslair I didn't need to do all that. Do you know any javascript library for displaying a tree in a graphical way?

cac left a reply on What Is The Best Way To Implement Self Reference? Laravel 5.5.4

hey @lionslair it worked out perfectly! Thanks for the great tip. Now I need some new tip. Well I need to show this tree in a nice and graphical understanding way on the view. The person who will use this has no clue what a tree is. Do you know any javascript library for this?

cac left a reply on What Is The Best Way To Implement Self Reference? Laravel 5.5.4

@lionslair it is not for menus or categories it is more likely to a comment table. I took a quick look at the link you provided and I think it will do it. Although it says on updating nodes it will be expensive in my case there won't be many updates and the tree has a max size of 3 levels. Thanks for the tip

01 Sep
9 months ago

cac started a new conversation What Is The Best Way To Implement Self Reference? Laravel 5.5.4

I reached a point where I have to implement self reference in an entity of my database. Firstly I tried referencing a parent_id column as a FK but that didn't work quite well when I stored a new record assigning parent_id = id on the database as the new record id doesn't exist before it is saved once.

Then I simply added the column as a nullable integer and then I saved a new record after that I retrieved it and assigned the parent_id to the same value of the id (this is how I am going to identify the root) after which I finally saved it again.

I wonder if this is the best solution in a long run. I am afraid I might not be able to set relationship to automatically retrieve its children or have some sort of difficulties in the future.

Can anyone make me suggestions?

11 Jun
1 year ago

cac left a reply on Laravel 5.2.29 GetOriginal() Not Working

@stardesign041@gmail.com just do this:

$someObject->getOriginal('fieldname');
21 Apr
1 year ago

cac left a reply on Laravel 5.5 Guzzle 6.3 PUT And POST Request To API

I found out I was building the request wrongly. Here is how to build it correctly:

public function store(Request $r){
//POST REQUEST
       unset($r['_method']);
            unset($r['_token']);
            $endpoint = url('/') . '/api/persons';
            $options = [
                'headers' => [
            'Content-Type' => 'application/json',
                        'Accept' => 'application/json'],
                'json' => [
                'field1' => $r->field1,
                       'field2' => $r->field2,],
                 ];

            $client = new Client();
            $client->post($endpoint, $options);
            return redirect()->action('[email protected]');
}

 public function update(Request $r)
    {//PUT REQUEST
        
            unset($r['_method']);
            unset($r['_token']);
            $endpoint = url('/') . '/api/persons/' . $r->id;
             $options = [
                'headers' => [
            'Content-Type' => 'application/json',
                        'Accept' => 'application/json'],
                'json' => [
                'field1' => $r->field1,
                       'field2' => $r->field2,],
                 ];

            $client = new Client();
            $client->put($endpoint, $options);

            return redirect()->action('[email protected]');


    }
20 Apr
1 year ago

cac started a new conversation Laravel 5.3 Guzzle 6.3 PUT And POST Request To API

I am having a hard time making those 2 request. I built and api and everything is working fine on POSTMAN. All endpoints are behaving as expected. But on my client I can't seem to build those two requests properly. Here is my api code:

API CONTROLLER

<?php

namespace App\Http\Controllers;

use App\Http\Requests\StorePerson;
use App\Http\Requests\UpdatePerson;
use App\Http\Resources\PersonResource;
use App\Person;
use Repositories\PersonRepository as ICrud;
use Symfony\Component\HttpFoundation\Response;

class ApiPersonController extends Controller
{
    protected $persons; //Repository

    public function __construct(ICrud $p)
    {
        $this->persons = $p;
    }

    public function index()
    {
        try {
            return json_encode($this->persons->all());
        } catch (\Exception $e) {

            return response(null, Response::HTTP_INTERNAL_SERVER_ERROR);

        }

    }

    public function store(StorePerson $request)
    {
        try {
            $return = $this->persons->store($request);
            if (isset($return)) {
                return response(['data' => $return], Response::HTTP_CREATED);
            } else {
                return response(null, Response::HTTP_BAD_REQUEST);
            }
        } catch (\Exception $e) {
            return response(null, Response::HTTP_INTERNAL_SERVER_ERROR);

        }


    }
 public function update(UpdatePerson $request, Person $person)
    {
        try {
            $return = $this->persons->update($request, $person);
            if (isset($return)) {
                return response(['data' => $return], Response::HTTP_CREATED);
            } else {
                return response(null, Response::HTTP_BAD_REQUEST);
            }
        } catch (\Exception $e) {
            return response(null, Response::HTTP_INTERNAL_SERVER_ERROR);
        }


    }
}

REPOSITORY

<?php

namespace Repositories;

use App\Http\Resources\PersonCollection;
use App\Http\Resources\PersonResource;
use App\Person;
use Interfaces\iCrud; //adicionei caminho da pasta interface no composer.json e dei comando <composer dump-autoload> no cmd


class PersonRepository implements iCrud
{

    public function all()
    {
        return PersonCollection::collection(Person::all());
    }

    public function store($r)
    {
        $person = new Person();
        $person->name = $r->nome;
        $person->ssn = $r->cpf;
        $person->gender = $r->genero;
        $person->address = $r->endereco;
        $person->birthday = $r->nascimento;
        $person->save();
        return new PersonResource($person);
    }

    public function update($r, $object)
    {


        $r['name'] = $r->nome;
        $r['ssn'] = $r->cpf;
        $r['gender'] = $r->genero;
        $r['address'] = $r->endereco;
        $r['birthday'] = $r->nascimento;
        unset($r['nome']);
        unset($r['cpf']);
        unset($r['genero']);
        unset($r['endereco']);
        unset($r['nascimento']);
        $object->fill($r->all());
        $object->save();

        return new PersonResource($object);
    }
}

CLIENT CONTROLLER

<?php

namespace App\Http\Controllers;


use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Http\Request;

class ClientPersonController extends Controller
{
    public function index()
    {
        $client = new Client();
        $res = $client->get(route('persons.index'));
        //echo $res->getBody();
        $persons = json_decode($res->getBody()->getContents());


        return view('persons.index', compact('persons'));
    }

   
    public function create()
    {
        return view('persons.create');
    }

    public function store(Request $r)
    {
        unset($r['_method']);
        unset($r['_token']);
        $endpoint = url('/') . '/api/persons/';
        dd($endpoint);
        $headers = ['Content-Type' => 'application/x-www-form-urlencoded',
            'Accept' => 'application/json'];
        $body = json_encode($r->all());
        $options = [$headers, $body];
        $client = new Client();
        dd($client->post($endpoint, $options));
    }

 
    public function edit(Request $r)
    {

        $client = new Client();
        $res = $client->get($r->href);
        $person = json_decode($res->getBody()->getContents());

        return view('persons.edit', compact('person'));
    }

    public function update(Request $r)
    {
        unset($r['_method']);
        unset($r['_token']);
        $endpoint = url('/') . '/api/persons/' . $r->id;
        $body = json_encode($r->all());
        $client = new Client();
        $res = $client->put($endpoint, ['body' => json_encode($r->all())]);    
        return redirect()->action('[email protected]');


    }

    public function destroy(Request $r)
    {

        $client = new \GuzzleHttp\Client();
        $client->delete($r->href);

        return redirect()->action('[email protected]');

    }
}

Any thoughts on this?

19 Apr
1 year ago

cac left a reply on How Can I Optimize This Code? LARAVEL 5.6

Thank you @Cronix . This was a good solution

cac started a new conversation Laravel 5.5 Consuming Own Api (no Authetication Needed)

I just built a very simple api just for learning and everything is working fine. Now I have no idea how I can consume it on the front end. May I build the front end in the same project or does it need to be a new project? I'd prefer same project. Also how do I use my endpoints on my forms? Could you provide some sample code for me on the forms?

cac left a reply on Forcing A Unique Rule To Ignore A Field Other Than ID

Guys I made it. I solved it by doing this:

'ssn' => 'required|string|max:11|unique:people,ssn,' . substr($this->getRequestUri(), -1)

It has always to be the id of the record even though you want to skip other field. By doing what I did I was able to retrieve the record id directly from the endpoint. Thank you @rin4ik and @Vilfago for your help.

cac left a reply on Forcing A Unique Rule To Ignore A Field Other Than ID

@rin4ik I am building an api that doesnt require authentication. That won't work. I need the Id from the endpoint:

http://localhost/api/persons/2

I need to get that number 2. I tried with:

 'ssn' => 'required|string|max:11|unique:people,ssn,' . $this->request->get('id')

I also tried like this:
 'ssn' => 'required|string|max:11|unique:people,ssn,' . $this->request->query('id')

cac left a reply on Forcing A Unique Rule To Ignore A Field Other Than ID

@rin4ik I believe so. In that case I need the id from the url inside my custom http request. Do you know how can I achieve that?

class UpdatePerson extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'nome' => 'required|max:191|string',
            'cpf' => 'required|string|max:11|unique:people,ssn,' . $this->request->get('person'),
            'nascimento' => 'required|date',
            'endereco' => 'nullable|string|max:191',
            'genero' => 'required|string|max:191'
        ];
    }
}<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UpdatePerson extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
           'name' => 'required|max:191|string',
            'ssn' => 'required|string|max:11|unique:people,ssn,' . $getIdFromUrl,
            'birthday' => 'required|date',
            'address' => 'nullable|string|max:191',
            'gender' => 'required|string|max:191'
        ];
    }
}


cac started a new conversation Forcing A Unique Rule To Ignore A Field Other Than ID

Hi guys. I need help doing a validation. I am using a custom http request. these are the rules:

 $rules = [
            'name' => 'required|max:191|string',
            'ssn' => 'required|string|max:11|unique:people,ssn,' . $this->request->get('ssn'),
            'birthday' => 'required|date',
            'address' => 'nullable|string|max:191',
            'gender => 'required|string|max:191'
        ];

But it still give me the message that the ssn has already been taken. Any thoughts on this?

10 Apr
1 year ago

cac started a new conversation How Can I Optimize This Code? LARAVEL 5.6

Before I let the user fill a form I must verify a few things before. I did a very simple verification but it doesn't seem quite right to me. I feel like there might be a better way to do it. First I thought of doing a bunch of if/else for each variable but it seemed very amateur. So I came up with this: ´´´ public function create() { $payment_options = PaymentOption::all(); $employees = Employee::all(); $batches = Batch::all(); $tanks = Tank::all(); $buyers = Buyer::all();

    if (count($payment_options) < 1 || count($employees) < 1 ||
        count($batches) < 1 || count($tanks) < 1 || count($buyers) < 1) {
        $msg = 'Please make sure you have at least on of: payment options, 
        employees, batches, tanks and buyers';

        return view('home', compact('msg'));
    }

    return view('sales.create', ['payment_options' => $payment_options,
        'employees' => $employees, 'batches' => $batches, 'tanks' => $tanks,
        'buyers' => $buyers]);

}

´´´ The problem of my solution is that it doesn't show the user which variable failed the verification. How can I achieve that in an elegant manner?

22 Mar
1 year ago

cac left a reply on [LARAVEL 5.2.29] How To Remove Master Page Layout From Bootstrap's Modal

Nevermind! I found my mistake. I put a route on it and there for it returned a view inside it.

cac started a new conversation [LARAVEL 5.2.29] How To Remove Master Page Layout From Bootstrap's Modal

I am trying to use bootstrap's modal feature but it keeps rendering my master page layout in it. I want it yo be blank but loads the entire page layout inside it.

bootstrap 3.3.6

How can I set it to blank?

18 Mar
1 year ago

cac left a reply on Laravel 5.2.29 GetOriginal() Not Working

@Snapey holyshit it worked! Thank you dude.

So here is the fix:

<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Trip extends Model
{
    protected $appends = ['created_at_english_format'];

    
    //ACCESSOR
    public function getCreatedAtAttribute($date)
    {
        return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d/m/Y H:i:s');
    }
    public function getCreatedAtEnglishFormatAttribute()
    {
//the name of the field on the object will be created_at_english_format
        return $this->getOriginal('created_at');
    }


}

cac left a reply on Laravel .dev

You need to set a virtual host. That will depend on which server you are using.

cac left a reply on Laravel 5.2.29 GetOriginal() Not Working

On the view I am trying to get the month of the date. But apparently JS can only understand the m-d-Y format. My data is saved in the DB in the m-d-Y format also. But I use ACCESSORS to format it as d-m-Y. Therefore the dates are automatically going to the view in the d-m-Y format and JS is crashing on that format.


var rawActualData = {!! json_encode($data->toArray()) !!};
            var data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];           
            var date = null;
            
            for (var k = 0; k < rawActualData.length; k++) {
                console.log(rawActualData[k].created_at);

                date = new Date(rawActualData[k].created_at);
                var month = date.toLocaleDateString('en', {month: "numeric"}); //tried to convert it to english but didnt work
                data[month]++;
            }

cac left a reply on Laravel 5.2.29 GetOriginal() Not Working

I dont want to save it to the database. I just want to use the original value of the field on a javascript function.

cac left a reply on Eloquent Subquery

you could simply make raw sql:

DB::select('select * from campaign where campaing.current < campaign.max');*/

or


cac started a new conversation Laravel 5.2.29 GetOriginal() Not Working

This is not working and I have no idea why. It doesn't change to the original value instead it remains the as set in the accessors.

 foreach ($data as $d){
            $t = $d->getOriginal('created_at'); // this works fine
            $d->created_at = $t; //this makes no change to $d->created_at
        }

Any suggestions?

17 Mar
1 year ago

cac left a reply on Laravel Date Parsing From Datetime-local And Freeform Date Request Data

Today I spent many hours trying to find a workaround of that problem. Luckly I found your post. More people should see this. But I still can't convert it to 24h format. Do you know how to do that?