andfelzapata

andfelzapata

Member Since 3 Years Ago

Pereira

Web Developer at The Safety Supply Company

Experience Points 21,390
Experience Level 5

3,610 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 260
Lessons
Completed
Best Reply Awards 1
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.

21 Dec
2 years ago

andfelzapata left a reply on Vuetable - Data Table Simplify!

@ratiw Very nice plugin, excellent my friend. I have a question...

Say I have a field definition like the following:

{
 name: 'created_at',
title: 'Date Created',
}

I want to transform the date using momentJS

Is there a way to mutate the fields, kind of computed properties:

{
 name: function(data) {return moment(data).format('LLLL')},
 title: 'Date Created',
}

How can I accomplish this ? Any ideas ? or Perhaps with a life cycle hook, to filter all the data ?

Thanks.

18 Nov
2 years ago

andfelzapata left a reply on Laravel Echo Listening Is Not Receiving Data

@khaledSMQ that worked with a slight change.

There's no need for the document.onreadystatechange. I updated part to my node server code, and added the channel as second argument. On the front end I had to specify the event namespace in the Echo constructor.

andfelzapata left a reply on Laravel Echo Listening Is Not Receiving Data

Awesome @khaledSMQ, I'm going to try it out later today. Thanks =)

17 Nov
2 years ago

andfelzapata left a reply on Laravel Echo Listening Is Not Receiving Data

I think I'm going to give up one Echo for now. I've read the source and found something that doesn't add up when attaching the channel and event to the socket.io instance. With more reading about Echo and socket.io itself things might get clearer but I think we might be weak in websocket concepts.

This is the test code I have with Echo and regular 'on' event:

const echo = new Echo({
    broadcaster: 'socket.io',
    connector: 'socket.io',
    host: `${process.env.APP_URL}:${process.env.NOTIFICACIONES_SOCKET_PORT}`,
});

echo.channel('channel-notificaciones')
    .listen('.App.Events.Notificaciones.BecaCargada', function(data) {
        console.log(data);
    });

console.log({echo});

var socket = io(`${process.env.APP_URL}:${process.env.NOTIFICACIONES_SOCKET_PORT}`);

socket.on(`channel-notificaciones:App\\Events\\Notificaciones\\BecaCargada`, function (data) {
    console.log(data);
}).on('channel-notificaciones:App\\Events\\Notificaciones\\AccionCambioEstado', function (data) {
    console.log(data);
});

console.log({socket});

When echo instance receives the channel and the event name, either by passing the full class name with namespaces '.App.Events.Notificaciones.BecaCargada' or by passing a namespace to the echo constructor and passing just the class name to the liste event.

In the code above I'm printing to console both the echo instance and the socket.io. After inspecting those objects a little I found out something that might be the issue, but I'm not sure.

The listeners attached to the 'io' socket events work. Thy log the payload from the sever with no problems.

The echo instance holds a reference to a socket.io instance in a property called connector. (Echo's source code is really good by the way, very easy to follow). Every socket.io instance has a list of callbacks, which are the vents attached to the channels.

Any event attached to a socket.io instance by doing:

socket.on(`channel-notificaciones:App\\Events\\Notificaciones\\BecaCargada`, function (data) {
    console.log(data);
}).on('channel-notificaciones:App\\Events\\Notificaciones\\AccionCambioEstado', function (data) {
    console.log(data);
});

Will result in an array of callbacks to responde to data coming from the server. In this case, with the socket.io plain instance, contains two callbacks:

$channel-notificaciones:App\Events\Notificaciones\AccionCambioEstado

and

$channel-notificaciones:App\Events\Notificaciones\BecaCargada

And that matches the channel and event I get from the server for each type of event.

Now, inspecting the callbacks property on the socket.io instance inside the connector property of echo, it's very different. It only has the event name and not the channel:event signature, just 'App\Events\Notificaciones\BecaCargada' for this example.

Again, there might be something missing that we're not seeing at the moment, but I tried passing arguments and different orders and also passing the full channel:event string as argument to echo's listen method but no luck niether. I'm going to try again tomorrow see If I can get it to work, if not I'm going to try out the larave-echo-server I mentioned earlier. If that doesn't work, then I'l just listen for events using plain socket.io 'on' events.

Hopes this helps.

andfelzapata left a reply on Laravel Echo Listening Is Not Receiving Data

Testing plain io code works:

var socket = io(`${process.env.APP_URL}:${process.env.NOTIFICACIONES_SOCKET_PORT}`);

socket.on(`channel-notificaciones:App\\Events\\Notificaciones\\BecaCargada`, function (data) {
    console.log(data);
});

andfelzapata left a reply on Laravel Echo Listening Is Not Receiving Data

@geraldarcega from the docs you can read there is a Socket.io Server, haven't tried it though. I went and used a node server setup I had used in the past without Echo and in previous versions of Laravel.

andfelzapata left a reply on Laravel Echo Listening Is Not Receiving Data

I think a good idea would be to read Echo's source code. I'm planning on doing that soon. I'll update anything I find.

15 Nov
2 years ago

andfelzapata left a reply on Laravel Echo Listening Is Not Receiving Data

Hi @khaledSMQ, i get the whole channel with event, namespace included.

andfelzapata left a reply on Laravel Echo Listening Is Not Receiving Data

The events from the server are getting to the browser with no problem. I think the problem is with:

echo.channel('channel-notificaciones')
    .listen('BecaCargada', (e) => {
        console.log(e);
});

That piece of code is not doing anything, however, messages from the server to the browser are working, the browser is receiving data.

If I open dev tools and inspect the socket's frames, is see the incoming data.

andfelzapata left a reply on Laravel + Socket.io + Redis With Laravel-echo

Hi @Chathula

I'm a problem with this setup as well, the only difference is that I do get data back from the server but is not displaying in the console.

I can see your missing something here, as @rdelorier suggested. You do have to include the channel name in the emit method.

This is what you have right now:

redis.on('message', function (channel, message) {
    console.log(channel, message);
    message = JSON.parse(message);
    io.emit(message.event, message.data);
});

Try this instead:

redis.on('message', function (channel, message) {
    console.log(channel, message);
    message = JSON.parse(message);
    const emmitChannel = `${channel}:${message.event}`;
    io.emit(emmitChannel, message.data);
});

That is how you should emmit the event.

If your using chrome's dev tools, go to the network tab, click on the las socket connection request and inspect the frames tab. When you emmit event now, you should see them in that frames tab.

Checkout a similar question I posted: https://laracasts.com/discuss/channels/javascript/laravel-echo-listening-is-not-receiving-data

It works up to the point that socket connection on the browser is receiving the vent data. I'm just having trouble adding the listen event on the echo instance.

andfelzapata left a reply on Laravel Echo Listening Is Not Receiving Data

Thanks @khaledSMQ, I'm going to try that out later today.

andfelzapata started a new conversation Laravel Echo Listening Is Not Receiving Data

Hey everyone !

I'm building a real time notification feature for an app I'm working on. I' using Laravel 5.3, Node, Laravel Echo, Redis, and socket.io.

I have my events setup, node server listening on port 8888, redis pubsub is connection with node working. Everything on the backend is working.

One of my events:

class BecaCargada implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $usuario;

    public $mensaje;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Usuario $usuario, $mensaje)
    {
        $this->usuario = $usuario;
        $this->mensaje = $mensaje;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('channel-notificaciones');
    }
}

When I generate this event it gets fired and publishes on the change successfully, I can see that on redis-cli and also on the nodeJS code thats subscribed and listening to the same channel.

The is the nodeJS code that listens on the same channel:

require ('dotenv').config();

const server = require('http').Server();

const io = require('socket.io')(server);

const Redis = require('ioredis');

const redis = new Redis();

redis.subscribe('channel-notificaciones');

redis.on('message', function (channel, message) {
    const notificacion = JSON.parse(message);
    const emmitChannel = `${channel}:${notificacion.event}`;
    console.log(`Canal: ${emmitChannel}`);
    io.emit(emmitChannel, notificacion.data);
});

server.listen({
    host: process.env.NOTIFICACIONES_SOCKET_HOST,
    port: process.env.NOTIFICACIONES_SOCKET_PORT
});

And for my js code I only have this right now:

import Echo from "laravel-echo";

window._ = require('lodash');

window.io = require("socket.io-client");

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */
const echo = window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: `${process.env.APP_URL}:${process.env.NOTIFICACIONES_SOCKET_PORT}`
});


echo.channel('channel-notificaciones')
    .listen('BecaCargada', (e) => {
        console.log(e);
});

After running gulp and refreshing, I open another tab and trigger the event. If I open dev tools and look at the frames tab in the socket connection I can see the incoming events clearly, channel:EventName, payload.

But nothing shows on the console from the console.log(e) code. I've inspected the echo variable and everything seems ok, the namespace, the channel.

Any thoughts on what could be wrong ?

Thanks and happy coding =)

26 Sep
2 years ago

andfelzapata started a new conversation Testing Laravel Event Hanlder With PhpSpec

Hey guys, I'm trying to get into the workfow of using phpSpec to desing my classes. I have stumbled on testing a handle method on one of my event handlers.

My spec:

use App\Models\Payments\Account;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

use App\Order;
use App\Models\Payments\Payment;
use App\Services\Payments\PaymentService;
use App\Events\Payments\AccountPayment;

class RecordPaymentTransactionSpec extends ObjectBehavior
{
    function let(PaymentService $paymentService)
    {
        $this->beConstructedWith($paymentService);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('App\Handlers\Events\Payments\RecordPaymentTransaction');
    }

    function it_should_record_payment_transaction(AccountPayment $event)
    {
        $this->paymentService->recordPayment($event)->shouldBeCalled();
    }
}

And this my implementation:

class RecordPaymentTransaction {

    public $paymentService;

    /**
     * Create the event handler.
     *
     * RecordPaymentTransaction constructor.
     * @param PaymentService $paymentService
     */
    public function __construct(PaymentService $paymentService)
    {
        $this->paymentService = $paymentService;
    }

    /**
     * Handle the event.
     *
     * @param  AccountPayment  $event
     * @return void
     */
    public function handle(AccountPayment $event)
    {
        $this->paymentService->recordPayment($event);
    }

}

However, I keep getting this error:

 - it should record payment transaction
      no beCalled([array:0]) matcher found for null.

Cannot see what I'm doing wrong here, help please.

23 Sep
2 years ago

andfelzapata left a reply on API Testing With Guzzle And Behat

Hi @MichaelGrossklos, where did you get with this. I'm just starting and I having trouble in the database side. In my feature context I can persist records, but for some reason there not available during the test inside my application.

andfelzapata started a new conversation Functional Test API Using Behat.

Hey guys I'm having problems starting with behat to make functional test for an existing application. I was able to set up everything, initially installing mink, the mink extension and the behat-laravel package. I started with a simple feature to test some functionalities of the login page.

This is the context I currently have:

class FeatureContext extends MinkContext implements Context
{
    use DatabaseTransactions;
    
    protected $user;

    protected $client;

    protected $response;

    protected $baseUri = 'http://supplycompany.app';

    /**
     * Initializes context.
     *
     * Every scenario gets its own context instance.
     * You can also pass arbitrary arguments to the
     * context constructor through behat.yml.
     */
    public function __construct()
    {
        $this->client = new Client(['base_uri' => $this->baseUri]);
    }

    /**
     * @Given there is an active user
     */
    public function thereIsAnActiveUser()
    {
        $this->user = Factory::create('office', ['username' => 'jonsnow',  'active' => 1]);
        PHPUnit::assertEquals($this->user->active, 1);
    }

    /**
     * @When the user attempts login
     */
    public function theUserAttemptsLogin()
    {
        $this->response = $this->client->request('POST', '/dashboard/login', ['form_params' => [

            'username' => 'jonsnow', 'password' => '1q2w3e4r']

        ]);
    }

    /**
     * @Then the user should be logged in
     */
    public function theUserShouldBeLoggedIn()
    {
        echo $this->response->getBody();
    }

Initially I started testing that page with mink, but since it used javascript, for my current needs it didn't work. So I started using guzzle to make request but this hasn't worked because there is an issue with the environments. For starters I havent been able to change the APP_ENV . I have it set inside my .env as 'development' but if I try to get it with App::environment() or env('APP_ENV') I get local. Which I suspected it was from the Homestead.yml file, removed that line, reloaded, provisioned and still get 'local'. The thing is that my current feature is failing because I cant find the created user inside the AuthController. The user does get persisted to the database but from some dd() statements I did, but is not available in my controller, if I try to return the user from the controller, hardcoding the credentials I get null. I suspected this had something to do with the environment. So I started printing the environments inside the context class and returned from the controller to guzzle request. Tried echoing APP_KEY and they were different.

Given that background. I'm looking for some technique to make functional tests for my application using behat without mink, things like hitting controllers and testing them most of the time. I saw a post that used laravel's testing framework within behat to do this, I haven't tried it yet.

Is there a way to make the testing work with guzzle, regarding the applicaiton environments ? Or is the laravel test framework better ? Or ! Is there another way to accomplish this.

Note: I want to continue using behat.

01 Sep
2 years ago

andfelzapata started a new conversation Testing React Components With Laravel Testing API

I want to test submitting a form.

If I have this form:

<form action="/register" method="POST">
    {{ csrf_field() }}

    <div>
        Name: <input type="text" name="name">
    </div>

    <div>
        <input type="checkbox" value="yes" name="terms"> Accept Terms
    </div>

    <div>
        <input type="submit" value="Register">
    </div>
</form>

And I test:

    public function testLoginSuccess()
    {
        $this->visit('/')
            ->submitForm('Register');
    }

Test passes. But if I try to test something similar, a form created with React I get:

  1. HomePageTest::testLoginSuccess InvalidArgumentException: Could not find a form that has submit button [Login].

How could I go about this ? How can I test this ?

Sorry for my ignorance, I'm new to testing.

Also, what kind of testing would this be ?? Acceptance ?

11 Aug
2 years ago

andfelzapata left a reply on Vue Learning Curve

@gregrobson I read about V2 and thought about going with that version from the start, looking forward to build some things with Vue, thank you for you reply !! =)

andfelzapata left a reply on Vue Learning Curve

Cool! Thanks =)

andfelzapata started a new conversation Vue Learning Curve

How's the learning the Vue learning curve for an experiences web developer ? How long can it take to learn to build medium size applications ?

01 Dec
3 years ago

andfelzapata started a new conversation Consume Laravel Service From Existing CodeIgniter App.

Hey guy,

I have the following issue:

I have an existing web app built with CodeIgniter, it works well. There are new features to be developed, some of them have to do with emails and notifications. I I have worked with Laravel, and its my framework of choice for new apps.

So, what I'm thinking is ... Maybe I could set a service with Laravel, that handle's email queues and notifications, maybe set up events, but how can a consume the service from CodeIgniter ?? That is the issue.

Additionally, is this an good approach ? Could it be done ? Any suggestions ?

Thanks. =)

09 Nov
3 years ago

andfelzapata started a new conversation Manage Queue Jobs In Shared Hosting.

Hi !!

I need advice on what to do with queued jobs in shared hosting. I have an application installed with hostgator shared hosting. I have to send a lot of emails, so I set up a database queue. Right now I have this piece of code inside my Console/Kernel.php class:

// Process pending jobs.
        $schedule->command('queue:restart')
            ->everyFiveMinutes();

        $schedule->command('queue:work --daemon')
            ->everyTenMinutes()
            ->sendOutputTo(storage_path() . '/logs/queue-jobs.log');

This fails a lot of times, I thought of installing supervisor but I have now clue right now on how to accomplish this in shared hosting. Perhaps there's another way to check the queue, bring the listener up if it goes down, etc.

Any help is very appreciated =) thanks !!

andfelzapata left a reply on Queue Solution For Shared Hosting

I need help with this too please !!

Right now I have this in my Console/Kernel.php class:

''' // Process pending jobs. $schedule->command('queue:restart') ->everyFiveMinutes();

    $schedule->command('queue:work --daemon')
        ->everyTenMinutes()
        ->sendOutputTo(storage_path() . '/logs/queue-jobs.log');

'''

But it seems it doesn't always work =(, is there no way to install supervisor ? I have hostgator shared hosting.

13 Oct
3 years ago

andfelzapata started a new conversation Problems Dispatching Jobs Sequentially

Say I have this piece of code:

->everyMinute()
->sendOutputTo(storage_path() . '/logs/queue-jobs.log');

And at one time of execution I have 3 items in my jobs table, do they all get dispatched in that same call ? Or does queue:work do one at a time ? If so, how can I dispatch all jobs sequentially in one call ?

07 Oct
3 years ago

andfelzapata left a reply on Send Notifications In Background.

Hi @ConsoleTVs , The user is an admin, the system just's notifies him that the assignment to the "agent" was done. The sms and email are sent the "agent".

andfelzapata started a new conversation Send Notifications In Background.

Hi Guys !!

My problem is the following:

I have a piece of code that does an update on the database, after that it has to send a sms notification and an email. Here's the code:

''' /** * Assign lead to agent. * * @param $id * @param $agent * * @return mixed */ public function leadAssignAgent($id, $agent) { $lead = Lead::where('id', $id) ->update(['user_id' => $agent]);

    if($lead) {

        $agent = User::findOrFail($agent);

        $assignedLead = Lead::with('source')->findOrFail($id);

        $this->agentNotifySms($assignedLead, $agent);

        EmailNotification::leadAssignment($agent, $assignedLead);

        return Lead::findOrFail($id);

    }

    return response(array('error' => 'Server Error.'), 500)
        ->header('Content-Type', 'application/json');
}'''

How could I optimize this, in such way, that the record gets updated, and after that the user gets the notification in the front-end and the sms and email continue execution in background ? Right now, the user gets notified that everything went ok after persisting and sending sms and email responses. I hope a made things clear enough, thanks !!

02 Sep
3 years ago

andfelzapata started a new conversation Php Imap_search() FROM Criteria Using Email Address Doesn't Work In Outlook

I know this isn't Laravel related exactly but I am building a project with Laravel, and one of my classes is a wrapper for an imap interaction using php imap. Since this is a such an excellent forum, well, here it goes.

I'm building a class that connects to an IMAP server. In my development environment I tried connecting to Gmail successfully, getting emails like this:

$emails = imap($this->connection, "FROM \"$source->email\" ");

The line above works as expected, it returns an array with the emails that matched the criteria, it works perfectly. e.g if $source->email = myemail@example.com, it will return only emails from that address.

However, when testing with the client's account in outlook I get an empty array using the same criteria. Even if the email address is static id doesn't work:

$emails = imap_search($this->connection, 'FROM "myemail@example.com"');

But doing the following does not return an empty array:

$emails = imap_search($this->connection, 'ALL');

The goal of the class is to extract some data from the emails, these emails are grouped by email addresses. Each group displays the content in a different pattern, so I have to distinguish all of them in order to instantiate the proper class that can extract the data from that group.

Any ideas on how to debug this ? or what might be the problem ?

Thanks.

01 Sep
3 years ago

andfelzapata started a new conversation How To Organize File Structure And Loading Of Backend Service Class.

I have to write a class that will be used to read emails via scheduler and write some stuff to a data base after that. I'm having trouble thinking of a way to organice this inside the app structure and a convenient way to load it within the scheduler.

29 Aug
3 years ago

andfelzapata left a reply on Laravel API Authenticate Incoming Ajax Request From Backbone Front-end.

@juandmegon Since the browser interacts via ajax with the sever for every request, I want to protect the routes. Right now I can view any url without being authenticated.

28 Aug
3 years ago

andfelzapata left a reply on Passing Data To A Partial For Multiple Pages

I had trouble escaping the blade code in the Partial part, it should be {{ $phone }}.

andfelzapata left a reply on Passing Data To A Partial For Multiple Pages

What is the home route ? When you visit example.dev/numbers what's supposed to happen ? I understand what you are trying to do, but I'm a bit confused. Your code indicates that yo have a main page, with nested partials but at appears as your calling the data at the wrong time. Since your homepage is the entry point, the data should be passed when the controller renders the homepage. Let mi illustrate:

Route:

Route::get('/phones', 'NumberController@numbers');
```
Controller:
```
namespace Phone\Http\Controllers;

use Phone\Http\Requests;
use Illuminate\Http\Request;

class NumberController extends Controller
{
    public function numbers()
    {
        $generatedNumbers = array(
            $number1 = 393993,
            $number1 = 383888,
            $number1 = 393433,
            $number1 = 393433,
            $number1 = 789798,
            $number1 = 393433,
            $number1 = 798797,
            $number1 = 393433,
            $number1 = 79879,
            $number1 = 393433,
        ); //This will eventually come form a database.

        return view('homepage')->with('generatedNumbers', $generatedNumbers);
    }
}

```
Home Page:
```
<div class="phone-numbers">

    @foreach($generatedNumbers as $phone)

        @include('partials.phone-box')

    @endforeach

</div>
```
Partial:
```
<div class="phone-number">
    <h4>Number:</h4>

    <h3><span class="number hilite hilite-primary">
        {{ $phone }}
    </span></h3>
    <h4>SETUP: <span class="hilite hilite-primary">FREE</span>
        <span></span><a class="btn btn-primary btn-add" href="#">
            <i class="fa fa-shopping-cart fa-1x"></i> add</a></h4>
</div>
```

andfelzapata left a reply on Populating Select Menu From Model In User Registeration Form

@jsartisan That's not to @mezie Try something like this:

I your controller:

$schools =  School::all();  
return view('your-view', ['schools' => $schools] );

or 

return view('your-view')->with('schools', $schools);

Then inside your view:

<select class="form-control select-status" id="status" name="status">
    <option value=""></option>

    @foreach ($schools as $school)

            <option leadStatus-id = "{{ $school->id }}" > {{ $school->name }} </option>

       @endforeach

</select>                                   

andfelzapata left a reply on L4 Login Problems

Did you try turning debugging on ? Do that and then in chrome dev tools, in the network tab look for the POST login in red that indicates the problem, click on it. Then check in the Preview, Response tabs for the actual error. The code 303 has something to do with redirections, look up HTTP STATUS CODES.

andfelzapata started a new conversation Laravel API Authenticate Incoming Ajax Request From Backbone Front-end.

What might be a good way to authenticate ajax requests coming from backbone front-end.

andfelzapata left a reply on L4 Login Problems

Inside your root directory type php artisan route:list, you'll get something like this:

|        | POST                           | dashboard/lead                                            | dashboard.lead.store   | App\Http\Controllers\LeadController@store                        |            |
|        | GET|HEAD                       | dashboard/lead/by-day                                     |                        | App\Http\Controllers\LeadController@getLeadsByDay                |            |
|        | GET|HEAD                       | dashboard/lead/by-month                                   |                        | App\Http\Controllers\LeadController@getLeadsByMonth              |            |
|        | GET|HEAD                       | dashboard/lead/by-week                                    |                        | App\Http\Controllers\LeadController@getLeadsByWeek               |            |
|        | GET|HEAD                       | dashboard/lead/create                                     | dashboard.lead.create  | App\Http\Controllers\LeadController@create                       |            |
|        | PUT                            | dashboard/lead/{lead}                                     | dashboard.lead.update  | App\Http\Controllers\LeadController@update                       |            |
|        | PATCH                          | dashboard/lead/{lead}                                     |                        | App\Http\Controllers\LeadController@update                       |            |
|        | GET|HEAD                       | dashboard/lead/{lead}                                     | dashboard.lead.show    | App\Http\Controllers\LeadController@show                         |            |
|        | DELETE                         | dashboard/lead/{lead}                                     | dashboard.lead.destroy | App\Http\Controllers\LeadController@destroy                      |            |
|        | GET|HEAD                       | dashboard/lead/{lead}/edit                                | dashboard.lead.edit    | App\Http\Controllers\LeadController@edit                         |            |

It shows the method, the uri the browser requested and in action it shows the controller and method name that listens for that request and try turning debug mode on to see what the error is.

27 Aug
3 years ago

andfelzapata left a reply on Validate Multiple Model Query Result Before Sending View To Browser.

@uxweb Yes, everything in the front end is ajax request, te views are partials. I'm trying to set up notifications for everything that might go wrong. So I want to return status codes for everything, that's what I'm aiming for.

andfelzapata started a new conversation Validate Multiple Model Query Result Before Sending View To Browser.

I have the following piece of code:

public function getLeads() 
    {
        
        $agents = User::usersActive();

        $teams = Team::all();

        $leadStatuses = LeadStatus::all();

        $sources = Source::all();

        $totalLeads = Lead::totalLeads();

        $leads = $this->lead->getAPaginatedLeads();

        if($agents && $teams && $leadStatuses && $sources && $totalLeads && $leads) {

            return view('dashboard.leads.leads', 

                ['leadStatuses' => $leadStatuses,

                 'totalLeads' => $totalLeads,
             
                 'sources' => $sources,

                 'agents' => $agents,

                 'teams' => $teams,

                 'leads' => $leads ]

            );

        }

        $message = 'Whoops!, There seems to be a problem with the server, <br> 
                    please try again or contact support if problem persists.';

        return response(array('msg' => $message ), 500) 
              ->header('Content-Type', 'application/json');

    }

I want to be able to validate each model query inside the if, and if any those returns false return an error to be handled in the front-end accordingly. However, I'm not pretty sure this is the best or correct way to accomplish it.

24 Aug
3 years ago

andfelzapata left a reply on Eloquent Model Static Function Inside Blade View.

@bestmomo Sorry I wasn't clear, the point of LeadStatus::statusName is to get the status name given the id.

andfelzapata left a reply on Eloquent Model Static Function Inside Blade View.

In my controller I'm returning various data sets:

public function getLeads() 
    {
        
        $agents = User::usersActive();

        $teams = Team::all();

        $leadStatuses = LeadStatus::all();

        $sources = Source::all();

        $totalLeads = Lead::totalLeads();

        $leads = $this->lead->getAllLeads();

        return view('dashboard.leads', 

            ['leadStatuses' => $leadStatuses,

             'totalLeads' => $totalLeads,
             
             'sources' => $sources,

             'agents' => $agents,

             'teams' => $teams,

             'leads' => $leads ]

        );

    }

$this->lead is a repo, which has the following method:

public function getAllLeads()
    {
        return Lead::orderBy('created_at', 'desc')->paginate(25);
    }

andfelzapata started a new conversation Eloquent Model Static Function Inside Blade View.

Is there a clean way to use a model static method inside a view. Suppose I have the following method:

 public static function statusName($id)
    {
        return LeadStatus::where('id', 1)->select('name')->first();
    }

´´´
And in a view, I have this: 

´´´
<div class="col-sm-1"> {{ $lead->status_id }} </div>
´´´

I want to use the method I described inside the view, like this: 

´´´
{{ LeadStatus::statusName($lead->status_id) }}
´´´
How can I accomplish this without adding php tags: 

´´´
<?php

use App\Models\LeadStatus;

?>

´´´

andfelzapata started a new conversation Creating Records With Model::create Method And Foreign Keys.

I'm having trouble storing foreign keys using the Model::create method. In the repository I have store method with the following code:

return Lead::create([
            'address'    => $input['address'],
            'city'       => $input['city'],
            'email'      => $input['email'],
            'first_name' => $input['first_name'],
            'last_name'  => $input['last_name'],
            'notes'      => $input['notes'],
            'phone'      => $input['phone'],
            'source_id'  => 1,
            'state_id'   => 1,
            'zip'        => $input['zip']
        ]);

However, when I look in the database, the inserted row is missing the source_id and state_id, which are database constrained foreign keys. I can't find what I'm doing wrong, it should be straight forward. Couldn't I just to Lead::create(input()); ?

20 Aug
3 years ago

andfelzapata left a reply on Creating REST API With More Actions Other Than Usual CRUD.

@taijuten and looks pretty too. I'm gonna try that.

19 Aug
3 years ago

andfelzapata left a reply on Creating REST API With More Actions Other Than Usual CRUD.

@Francismori7 You mean something like this:

Route::get('lead/by-day','LeadController@getLeadsByDay');
Route::get('lead/by-week','LeadController@getLeadsByWeek');
Route::get('lead/by-month','LeadController@getLeadsByMonth');

Route::resource('lead', 'LeadController');

andfelzapata started a new conversation Creating REST API With More Actions Other Than Usual CRUD.

Say I have a resource with with the usual @store, @index, @create, @destroy, @show and @update, but I want more actions in the same restful way. (e.g @reportByDay, @reportByWeek, @reportByMonth, @reportByState). Any thoughts on how to accomplish this ?

11 Aug
3 years ago

andfelzapata left a reply on AuthController $redirectPath, $loginPath Overwrite.

Hi @Snapey, I just solved it, silly thing it was.

  1. I forgot to change a route name in my jQuery code.

  2. After logging in correctly I was redirect to /home, it came from the RedirectIfAuthenticated class. I changed line 38 in that class, from "return redirect('/home')" to "return redirect('/dashboard')". Don't know if this is the proper way though.

andfelzapata started a new conversation AuthController $redirectPath, $loginPath Overwrite.

I'm trying to implement a login using ajax. When I use the wrong credentials I get redirected to /login, with correct credentials I get redirected to /home even though I used added protected $redirectPath = '/dashboard' and protected $loginPath = '/'; to my AuthController.php file. Either way my browser shows me the "NotFoundHttpException in RouteCollection.php line 143:" message because /login and /home aren't specified in my routes.php file.

Here's my AuthController:

namespace App\Http\Controllers\Auth;

use App\User; use Validator; use Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller { /* |-------------------------------------------------------------------------- | Registration & Login Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users, as well as the | authentication of existing users. By default, this controller uses | a simple trait to add these behaviors. Why don't you explore it? | */

use AuthenticatesAndRegistersUsers, ThrottlesLogins;


protected $redirectPath = '/dashboard';

protected $loginPath = '/';

/**
 * Create a new authentication controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest', ['except' => 'getLogout']);
}

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|confirmed|min:6',
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return User
 */
protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
}

public function authenticate($credentials)
{   
    $authenticate = ( Auth::attempt($credentials) ) ? true : false;

    return $authenticate;
}

/**
 * [getLogin description]
 * @return \Illuminate\Http\Response Html document
 */
public function getLogin() {
    return view('auth.login');
}

/**
 * Handle an ajax login request to the application
 * 
 * @param \Illuminate\Http\Request $request
 * @param \Illuminate\Http\Response
 */ 
public function postLogin(Request $request)
{
    $this->validate($request, [
        'username' => 'required', 'password' => 'required',
    ]);// Returns response with validation errors if any, and 422 Status Code (Unprocessable Entity)

    $credentials = $request->only('username', 'password');

    if ($this->authenticate($credentials))
    {
        return response(array('msg' => 'Login Successfull'), 200) // 200 Status Code: Standard response for successful HTTP request
          ->header('Content-Type', 'application/json');
    }

    return response(array('msg' => $this->getFailedLoginMessage()), 401) // 400 Status Code: Forbidden, needs authentication
      ->header('Content-Type', 'application/json');

}

/**
 * Logs user out of app
 * @return \Illuminate\Http\Response 
 */
public function getLogout() {
    Auth::logout();
}

/**
 * Returns registration form view
 * @return \Illuminate\Http\Response
 */
public function getRegister() {
    return view('auth.register');
}

/**
 * Registers users
 * @return \Illuminate\Http\Response
 */
public function postRegister() {
    return response('Registration Succesful!', 200) 
          ->header('Content-Type', 'application/json');
}

}