depsimon

Member Since 3 Years Ago

Mons

Freelance Web Developer at WebArtisan

Experience Points 45,955
Experience Level 10

4,045 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 463
Lessons
Completed
Best Reply Awards 4
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.

14 Dec
1 year ago

depsimon started a new conversation Notification-specific Configuration In Queue

Hey guys,

I'm using queues to send notifications to users when they received a new message. My users are separated in groups or teams and each group has its own mail config.

So I'm looking to apply these config (stored in the db) when the queue is triggered.

So far I've overwritten the __wakeup() method on the notification itself and it works, but I don't really know if this is a good practice or if it'll impact other queues or stuff..

Anyone has another solution?

// NewMessage Notification
class NewMessage extends Notification implements ShouldQueue
{
    use Queueable;

    public $message;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(Message $message)
    {
        $this->message = $message;
    }

    public function __wakeup() {
        parent::__wakeup();
        
        $this->setConfigForMessage();
    }

    ....
}
09 Jan
2 years ago

depsimon started a new conversation Synchronise Prestashop And Laravel Database

Hey guys,

So I've been working on this project for a while now. It's a simple Prestashop website where customers buy a number of questionnaires.

We send them an email with a link to fill in their questionnaires in the Laravel app. The Laravel app pulls data from the Prestashop API each hour (to get the latest orders and customer information). The app basically generates PDFs based on the content of the questionnaires.

I feel this could be optimized because at the moment I've to check every order, every customer, every address, etc.. and update if modified.

He asked me to start another project based on the first one, so I'd like to start clean if you guys think there is a better way to achieve this that would make it easier to follow Prestashop changes (at the moment I've to check every order, every customer, every address, etc..) and that would be as synchronized as possible.

Cheers

26 Dec
2 years ago

depsimon left a reply on Get Clients Who Have Birthdays In Next 7 Days

You solution doesn't take into account birthdays that are in less than 7 days but next year.

i.e.: today we're December 26th, you wouldn't get a user whose birthday is on January 1st.

-> http://stackoverflow.com/a/18748008/3178151

21 Oct
2 years ago

depsimon left a reply on How To Get Database Records Number Variations Over Time

Thanks. As you say I think it won't be a problem for now.

I've already seen it and I'm using a cool package that makes it easy to play with activities : spatie/laravel-activitylog

depsimon left a reply on How To Get Database Records Number Variations Over Time

Thanks for your reply @rosswilson252

I think this solution might work (the first one) but I have some concerns.

Is that not a problem to duplicate (basically making a new INSERT request) every time there's a change? I mean if 10 users are choosing their interests at the same moment and play with "check"/"uncheck". For that solution I'm thinking of using queues, though is it better to have 100 queues doing 1 INSERT query or doing the INSERT query while doing the operation?

If I go for this solution, I'd probably create a generic "activities" table to store all kind of activities. Like checking an interest, logging in, logging out, etc.. That table would soon store thousands and thousands of records and that scares me.

depsimon started a new conversation How To Get Database Records Number Variations Over Time

Hello everyone,

My Users can choose Interests and potentially other entities can choose interests too (such as Sessions/Speakers, ...).

I've 3 tables : users, interests (id, name), interestables (interest_id, interestable_id, interestable_type, timestamps)

Basically what I want is to know the interest "popularity" (= number of users that has chosen a given interest) at a given moment (daily or hourly).

At the moment when a User chooses an interest, I create a record in the interestables table that has the id of the interest, the id of the user and the timestamps. And when he is not interested anymore, I delete the same record. If a User chooses an interest and delete it after a while, I've no way of knowing it was even selected by this user at that moment because the record doesn't exist anymore.

If I add Soft Delete on the interestables I feel it'll add some unnecessary complexity to the code and if a user checks, unchecks then check again an interest I've still lost the fact it was even unchecked at a given moment.

So how you guys do it?

28 Sep
2 years ago

depsimon left a reply on Nesting Route On Resource Route

Just add your routes after the resource.

Route::resource('event', 'EventController');
Route::get('event/{event}/registration', ['uses' => 'Event\[email protected]'])->name('event.registration.create');
Route::post('event/{event}/registration', ['uses' => 'Event\[email protected]'])->name('event.registration.store');

This will give you something like this :

+--------+-----------+----------------------------+---------------------------+----------------------------------------------------------+------------+
| Domain | Method    | URI                        | Name                      | Action                                                   | Middleware |
+--------+-----------+----------------------------+---------------------------+----------------------------------------------------------+------------+
|        | GET|HEAD  | event                      | event.index               | App\Http\Controllers\[email protected]               | web        |
|        | POST      | event                      | event.store               | App\Http\Controllers\[email protected]               | web        |
|        | GET|HEAD  | event/create               | event.create              | App\Http\Controllers\[email protected]              | web        |
|        | GET|HEAD  | event/{event}              | event.show                | App\Http\Controllers\[email protected]                | web        |
|        | PUT|PATCH | event/{event}              | event.update              | App\Http\Controllers\[email protected]              | web        |
|        | DELETE    | event/{event}              | event.destroy             | App\Http\Controllers\[email protected]             | web        |
|        | GET|HEAD  | event/{event}/edit         | event.edit                | App\Http\Controllers\[email protected]                | web        |
|        | GET|HEAD  | event/{event}/registration | event.registration.create | App\Http\Controllers\Event\[email protected] | web        |
|        | POST      | event/{event}/registration | event.registration.store  | App\Http\Controllers\Event\[email protected]  | web        |
+--------+-----------+----------------------------+---------------------------+----------------------------------------------------------+------------+

depsimon left a reply on Using Cache's Forever() Function And Passing It A Parameter Gives Serialization Of 'Closure' Is Not Allowed

Cache::forever() does not work with closures. Just use remember() with 0 minutes, it'll do the same.

10 Aug
2 years ago

depsimon left a reply on Laravel 5.2 Redirect Intended

It should already be the case. Check the Illuminate\Foundation\Auth\AuthenticatesUsers trait.

// Illuminate\Foundation\Auth\AuthenticatesUsers


  /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  bool  $throttles
     * @return \Illuminate\Http\Response
     */
    protected function handleUserWasAuthenticated(Request $request, $throttles)
    {
        if ($throttles) {
            $this->clearLoginAttempts($request);
        }

        if (method_exists($this, 'authenticated')) {
            return $this->authenticated($request, Auth::guard($this->getGuard())->user());
        }

        return redirect()->intended($this->redirectPath());
    }

As you can see you can create an authenticated() method in your controller to do it yourself.

depsimon left a reply on Tables And Relations

Where and how are defined your rules?

  • Project A and Project B can have both the same categories but not have the same subcategories.
  • Project B and Project C can have both the same categories and subcategories but not have the same lines in their subcategories.

I think I'd go this way :

  • projects (id, reference)
  • categories (id, name, parent_id) - Categories, subcategories and lines. Use parent_id to define if it's a category (parent), sub category (children) or lines (grand children).
  • project_category (project_id, category_id) - Which project has which categories/subcategories/lines.

Then you handle your rules in your code.

depsimon left a reply on How To Pass All Arrays Into FormArray Maatwebsite-laravel-excel

@Hamelraj of course you can.

// Add the headers
$sheetArray[] = array('JOB NO','INVOICE NO','CUSTOMER','VAT(OUT PUT)','ACTUAL VAT');

// Add the spaces
$sheetArray[] = array(); // Add an empty row
$sheetArray[] = array(); // Add an empty row

// Add the results
// ...

depsimon left a reply on How To Pass All Arrays Into FormArray Maatwebsite-laravel-excel

Hi @Hamelraj,

here's what you can do.

// Array that will be used to generate the sheet
$sheetArray = array();

// Add the headers
$sheetArray[] = array('JOB NO','INVOICE NO','CUSTOMER','VAT(OUT PUT)','ACTUAL VAT');

// Add the results
foreach($jobs  as $row){
    $client = $row->company->name;
    if($row->company->name != "PSL"){
        $client = $row->job->customer_name;
    }
    $sheetArray[] = array($row->job_no,$row->invoice_no,$client,number_format(($row->amount)*15/115,2,'.',','));
}

// Generating the sheet from the array
$sheet->fromArray($sheetArray);
03 Aug
2 years ago

depsimon left a reply on Processing Big API Response

Maybe you can copy the response in a file locally and process the response as you want in background.

25 May
2 years ago

depsimon left a reply on Laravel Eloquent Three Tables Query

Oh right, then I suppose that a simple belongsToMany should do the trick here.

// User.php

public function tasks()
{
    return $this->belongsToMany(Task::class, 'workers');
}

depsimon left a reply on Laravel Eloquent Three Tables Query

You could create a hasManyThrough relation in your User model.

It would look like this I guess.

// User.php

public function tasks()
{
    return $this->hasManyThrough(Task::class, Worker::class);
}

Then you would use something like auth()->user()->tasks.

24 May
2 years ago

depsimon left a reply on How Does Spark Support One Time Payements

About the wallet system I guess that you could create a balance column in the users table and add/remove virtual money when the user is being charged (with Cashier or Spark) or when the user purchases something.

11 Mar
3 years ago

depsimon left a reply on Mysqld Is Taking Too Much CPU

Okay thanks all for your answers. Taylor suggested that I create a new server with MariaDB.

09 Mar
3 years ago

depsimon left a reply on Mysqld Is Taking Too Much CPU

@AlexRo I'll read about MariaDB. How did you proceed to make the switch?

I've a pretty recent Forge server (1st of February) but I didn't see anything related to MariaDB yet. Do you recommend some documentation?

Also I intend to use specific functions of MySQL such as st_distance and json, will that be compatible with MariaDB?

Thanks for your answer

08 Mar
3 years ago

depsimon left a reply on Mysqld Is Taking Too Much CPU

I ran mysqltuner, maybe this'll help. Here're the results.

7m 55s after reboot: (~12% Memory)

-------- General Statistics --------------------------------------------------
[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 5.7.11
[OK] Operating on 64-bit architecture

-------- Storage Engine Statistics -------------------------------------------
[--] Status: +Archive -BDB -Federated +InnoDB -ISAM -NDBCluster
mysql: [Warning] Using a password on the command line interface can be insecure.
mysql: [Warning] Using a password on the command line interface can be insecure.
[--] Data in InnoDB tables: 2M (Tables: 105)
[--] Data in PERFORMANCE_SCHEMA tables: 0B (Tables: 87)
[OK] Total fragmented tables: 0

-------- Security Recommendations  -------------------------------------------
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1054 (42S22) at line 1: Unknown column 'password' in 'where clause'
[OK] All database users have passwords assigned
mysql: [Warning] Using a password on the command line interface can be insecure.

-------- Performance Metrics -------------------------------------------------
[--] Up for: 7m 55s (356 q [0.749 qps], 42 conn, TX: 308K, RX: 36K)
[--] Reads / Writes: 84% / 16%
[--] Total buffers: 172.0M global + 1.1M per thread (151 max threads)
[OK] Maximum possible memory usage: 341.9M (17% of installed RAM)
[OK] Slow queries: 0% (0/356)
[OK] Highest usage of available connections: 3% (6/151)
[OK] Key buffer size / total MyISAM indexes: 8.0M/41.0K
[!!] Key buffer hit rate: 50.0% (6 cached / 3 reads)
[OK] Query cache efficiency: 54.3% (76 cached / 140 selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (0 temp sorts / 25 sorts)
[OK] Temporary tables created on disk: 0% (0 on disk / 19 total)
[OK] Thread cache hit rate: 85% (6 created / 42 connections)
[OK] Table cache hit rate: 54% (104 open / 191 opened)
[OK] Open file limit used: 1% (12/1K)
[OK] Table locks acquired immediately: 100% (103 immediate / 103 locks)
[OK] InnoDB data size / buffer pool: 2.5M/128.0M

-------- Recommendations -----------------------------------------------------
General recommendations:
    MySQL started within last 24 hours - recommendations may be inaccurate

14m 15s after reboot : (~ 43% Memory)

-------- General Statistics --------------------------------------------------
[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 5.7.11
[OK] Operating on 64-bit architecture

-------- Storage Engine Statistics -------------------------------------------
[--] Status: +Archive -BDB -Federated +InnoDB -ISAM -NDBCluster
mysql: [Warning] Using a password on the command line interface can be insecure.
mysql: [Warning] Using a password on the command line interface can be insecure.
[--] Data in InnoDB tables: 2M (Tables: 105)
[--] Data in PERFORMANCE_SCHEMA tables: 0B (Tables: 87)
[OK] Total fragmented tables: 0

-------- Security Recommendations  -------------------------------------------
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1054 (42S22) at line 1: Unknown column 'password' in 'where clause'
[OK] All database users have passwords assigned
mysql: [Warning] Using a password on the command line interface can be insecure.

-------- Performance Metrics -------------------------------------------------
[--] Up for: 14m 15s (455 q [0.532 qps], 80 conn, TX: 412K, RX: 48K)
[--] Reads / Writes: 90% / 10%
[--] Total buffers: 172.0M global + 1.1M per thread (151 max threads)
[OK] Maximum possible memory usage: 341.9M (17% of installed RAM)
[OK] Slow queries: 0% (0/455)
[OK] Highest usage of available connections: 3% (6/151)
[OK] Key buffer size / total MyISAM indexes: 8.0M/41.0K
[!!] Key buffer hit rate: 74.0% (150 cached / 39 reads)
[OK] Query cache efficiency: 41.1% (76 cached / 185 selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (0 temp sorts / 34 sorts)
[OK] Temporary tables created on disk: 3% (63 on disk / 1K total)
[OK] Thread cache hit rate: 92% (6 created / 80 connections)
[!!] Table cache hit rate: 9% (271 open / 2K opened)
[OK] Open file limit used: 1% (12/1K)
[OK] Table locks acquired immediately: 100% (181 immediate / 181 locks)
[!!] Connections aborted: 7%
[OK] InnoDB data size / buffer pool: 2.5M/128.0M

-------- Recommendations -----------------------------------------------------
General recommendations:
    MySQL started within last 24 hours - recommendations may be inaccurate
    Increase table_cache gradually to avoid file descriptor limits
    Your applications are not closing MySQL connections properly
Variables to adjust:
    table_cache (> 431)

Then it stabilizes to ~43%.

depsimon left a reply on Mysqld Is Taking Too Much CPU

I enabled the logs and here's the result after a few minutes (/var/lib/mysql/{hostname}.log) : http://pastebin.com/LCfX18W0

Here's the result of the /var/log/syslog for the same period of time : http://pastebin.com/2yTMtm5a

As you can see, there is a cron executed every minute that does not run any slow query.

And finally the {hostname}-slow.log shows only this :

/usr/sbin/mysqld, Version: 5.7.11 (MySQL Community Server (GPL)). started with:
Tcp port: 3306  Unix socket: /var/run/mysqld/mysqld.sock
Time                 Id Command    Argument

Maybe I should restart the server to see what happens in the logs ?

depsimon left a reply on Mysqld Is Taking Too Much CPU

The show processlist command returns this :

mysql> show processlist;
+-----+-----------------+-----------+---------------------+---------+------+----------+------------------+
| Id  | User            | Host      | db                  | Command | Time | State    | Info             |
+-----+-----------------+-----------+---------------------+---------+------+----------+------------------+
|  90 | clubin_comeback | localhost | clubin_comeback     | Sleep   |  830 |          | NULL             |
|  96 | proevents       | localhost | proevents_proevents | Sleep   |  652 |          | NULL             |
|  99 | phpninja        | localhost | phpninja_proevents  | Sleep   |  660 |          | NULL             |
| 112 | forge           | localhost | NULL                | Query   |    0 | starting | show processlist |
+-----+-----------------+-----------+---------------------+---------+------+----------+------------------+
4 rows in set (0.00 sec)

And the top command returns this for mysqld :

3484 mysql 20 0 2223528 875888 9800 S 0.7 42.7 0:04.33 mysqld

I'll look into logging queries, it might be a good thing.

depsimon started a new conversation Mysqld Is Taking Too Much CPU

Today I connected on my Forge server (hosted on Digital Ocean) and noticed that the mysqld process was taking too much CPU and Memory. Both were around 50%.

After rebooting my droplet, the CPU % keeps low (< 1%) but the Memory goes back to ~50%. How can I check what makes it this high?

My Droplet is : 2GB Memory, 2 Core Processor. Forge is installed with PHP7 and Mysql 5.7.11.

I've one scheduled task running every minute, the artisan schedule:runand some daemons but nothing too expensive I think.

17 Feb
3 years ago

depsimon left a reply on Homestead Up - The Specified Host Network Collides With A Non-hostonly Network!

Here's another solution that does not require you to edit any file other than Homestead.yml.

Open VirtualBox, Go to Preferences > Network. Open the "Host-only Networks" and double click on the correct entry (mine is called vboxnet0). Open the DHCP Server tab and look for the "Lower Address Bound" and "Upper Address Bound". In my case it's 192.168.56.101 and 192.168.56.254.

Now you just have to use an IP between these bounds like 192.168.57.102 and use this IP in your Homestead.yml and try to vagrant up again.

Source & Video (in Spanish) : https://www.youtube.com/watch?v=XWushiLBgbw

02 Feb
3 years ago

depsimon left a reply on Mail Fails After Activating Let's Encrypt

After a few readings it might be Gmail-specific, I tried with mailgun and it works fine.

01 Feb
3 years ago

depsimon started a new conversation Mail Fails After Activating Let's Encrypt

Hi,

I just installed a Let's Encrypt certificate on my application and after testing the results, I noticed the Mail feature was broken. I suspect this has something to do with the https, does anyone have an idea?

It's sending me this Swift_TransportException after 30 secs with the following message :

Swift_TransportException {
  #message: "Connection could not be established with host smtp.gmail.com [Connection timed out #110]"
  #code: 0
  #file: "/home/forge/luc-k.com/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php"
  #line: 265
}

Here's my mail configuration :

"driver" => "smtp",
 "host" => "smtp.gmail.com",
 "port" => "587",
 "from" => [
   "address" => "***",
   "name" => "***",
 ],
 "encryption" => "tls",
 "username" => "***",
 "password" => "***",
 "sendmail" => "/usr/sbin/sendmail -bs",
 "pretend" => false,

Note that the same configuration works fine in Homestead and worked fine before the migration to a new server.

After installing the certificate, I did nothing specific. Maybe there was something to do?

31 Jan
3 years ago
21 Jan
3 years ago

depsimon left a reply on Vue.js Call Component Method From Vue Instance

Great that's exactly what I needed, thank you both @Sagaio @KingsGambit

depsimon left a reply on Vue.js Call Component Method From Vue Instance

I can't seem to figure out how to do this.

In my component I added :

    events: {
        'pagination-counter-refresh': function() {
            this.update();
        }
    }
```

And in my Vue instance I replaced the updateCounters method by this :
```
     updateCounters: function() {
            this.$dispatch('pagination-counter-refresh');
    },
```

But the update method is not triggered...

20 Jan
3 years ago

depsimon started a new conversation Vue.js Call Component Method From Vue Instance

Hi, I'm pretty new to Vue.js and I'm struggling with this particular issue.

I made a counter components that get its value from the server. This component has an update() method that I call once in the ready section of my component.

In my Vue instance I'd like to call this same update() method from time to time, when I need to reload the counters.

For now all I could do is loop through this.$children and check if the $options.name was the counter component's and if it was the case, finally call the update() method.

I'm sure there is a more vue-way to achieve this, isn't it ?

Here's my code.

<pagination-counter source="{{ url('/pages/draft') }}"></pagination-counter>
var PaginationCounter = Vue.extend({
    props: ['source'],
    template: '<span class="label label-default pull-right">{{ count }}</span>',
    data: function() {
        return {
            count: 0
        };
    },
    ready: function() {
        this.update();
    },
    methods: {
        update: function() {
            this.$http.get(this.source, function(response) {
                this.count = response.total;
            });
        }
    }
});

Vue.component('pagination-counter', PaginationCounter);
var paginationApp = new Vue({
    el: "#pagination-app",
    data: {
        // 
    },
    ready: function() {
        //
    },
    methods: {
        fetchPage: function(page) {
            this.$http.get(page).then(function(response) {
                this.updateCounters();
            }, function(response) {
                // handle error
            });
        },
        updateCounters: function() {
            for (var i = 0; i < this.$children.length; i++) {
                if (this.$children[i].$options.name == 'pagination-counter') {
                    this.$children[i].update();
                }
            }
        }
    }
});
19 Jan
3 years ago

depsimon started a new conversation Vue And Laravel Pagination

Hey guys,

I have these Pages that I can manage in my back-end. So I made a template with the paginated Pages using Laravel Pagination. It all worked fine, but I wanted to manage that view with Vue.js

Here's how I implemented this, the difficulty was to rebuild the pagination links. In my case I wanted it like this : "< 1 2 ... 4 5 6 ... 9 10 >" (pretty much like the default pagination in laravel 5.2, but instead of having 3 links on each side of the current page I set it up to 1)

My Controller :

// PagesController.php

use App\Models\Pagination\PaginationPresenter;

public function index(Request $request)
{
    $pages = Page:paginate(10);

    if ($request->wantsJson()) {
        $pagination = $pages->toArray();
        $pagination['paginationHtml'] = (new PaginationPresenter($pages))->render()->toHtml();

        return response()->json($pagination);
    } else {
        return view('admin.pages.index')->with(compact('pages'));
    }
}

My view (admin/pages/index.blade.php

<div id="pagination-app">
{!! (new App\Models\Presenters\PaginationPresenter($pages))->render() !!}

<table class="table table-hover">
    <thead>
        <tr>
            <th>Title</th>
            <th>Status</th>
            <th>Last Edit</th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="page in pagination.data">
            <td><a href="#">@{{ page.title }}</a></td>
            <td>@{{ page.status }}</td>
            <td>@{{ page.updated_at }}</td>
        </tr>
    </tbody>
</table>
</div>

<!-- later in the view -->
<script>
    var paginationApp = new Vue({
        el: "#pagination-app",
        data: {
            pagination: {!! $pages->toJson() !!},
        },
        methods: {
            fetchPage: function(page) {
                this.$http.get(page).then(function(response) {
                    this.pagination = response.data;
                    this.updatePagination();
                }, function(response) {
                    // handle error
                });
            },
            updatePagination: function() {
                var $element = $(this.pagination.paginationHtml);
                this.$compile($element.get(0));
                $(this.$el).find('.pagination').replaceWith($element);
            }
        }
    });
</script>

And my custom Pagination Presenter

// app/Models/Presenters/PaginationPresenter.php

protected function getAvailablePageWrapper($url, $page, $rel = null)
{
    $rel = is_null($rel) ? '' : ' rel="'.$rel.'"';

    return '<li><a href="#" @click="fetchPage(\''. $url .'\')"'.$rel.'>'.$page.'</a></li>';
}

It all works as I want, but it bugs me that I have to add the paginationHtml to the pagination in my controller. Is there something I could do better ?

17 Dec
3 years ago

depsimon left a reply on Best Way To Handle REST API Errors Thrown From Controller Or Exception

@crishellco That seems like an acceptable solution to me. Thanks !

depsimon left a reply on API And Back-end In The Same Application

Yeah I think I'll do that, though I'd feel a little guilty. But the first version was too much of a pain in the ass to maintain.. I feel it will be much clearer having all at the same place with an appropriate structure.

Thanks for your opinion :)

13 Dec
3 years ago

depsimon left a reply on Create "credit/prepaid" System

I recommend using a balance field in your user as well as a balance field in your transactions. This way you'll know the balance of a user at any given time.

Also this might come handy if there was any issue with a transaction.

Plus, using operations like $this->incoming() - $this->outgoing() is less cost-effective than updating users.balance once every time a transaction is stored.

12 Dec
3 years ago

depsimon left a reply on How Make My Own Crud Route

Basically you make your routes as usual (using resource routes or classic get/post/put/delete routes) and in your controllers you always respond in the same schema.

public function index()
{
    $data = ['foo' => 'bar'];
        
    return response()->json([
        'success' => true,
        'data' => $data
    ]);
}

In my case I used a Trait for my controllers.

<?php

namespace App\Http\Controllers\Api;

use App\Traits\ApiResponseTrait;

class Controller extends BaseController
{
    use ApiResponseTrait;
}
<?php

namespace App\Http\Controllers\Api

use App\User;

class UsersController extends Controller
{
    public function index()
    {
        $users = User::all();

        return $this->respond(true, $users);
    }
}
<?php 

namespace App\Traits;

trait ApiResponseTrait
{
    
    protected respond($success, $data)
    {
        return response()->json($success, compact('data'));
    }

}
11 Dec
3 years ago

depsimon started a new conversation API And Back-end In The Same Application

Hi everyone,

I was wondering what could be the best way to build my project which includes:

  • an API
  • 2 back-ends
    • one for administrators
    • another for customers
  • a website that will eventually use data from the database
  • mobile applications that will use the API

I already built a first version which had separated everything. (API is an application, each back-end is an application, the website is an application too) Also, every application uses the API to exchange data with the database.

That made me wonder if that was necessary. That's hard to maintain, and anytime I need a new specific request (ex: statistics for an event with filters) I end up creating a new endpoint in my API. This doesn't feel right. Why not have everything on the same application like I have already seen, separating sections with Controllers like this :

  • Http/Controllers/Api
  • Http/Controllers/Administration
  • Http/Controllers/Manager
  • Http/Controllers/Website

That would allow me to :

  • not struggle with the authentication in my own applications (only mobile applications would need that)
  • not struggle with custom requests, I could use Models from my applications directly or event DB if really necessary.
  • The API would be really clean as it should only expose some data for my mobile apps.

So guys, if you have a miracle solution I would be glad to hear it :D But seriously, would that be bad to have everything in the same application ?

depsimon left a reply on [Help] Eloquent "$with" Property Trouble

Maybe this is because Vcard is extending Contact.

depsimon left a reply on Authenticate User With External Api And On Success Set Session

You need to bind a seller to a user. Then you should be able to log using :

Auth::login(Seller::find(sellerid)->user_id);
06 Aug
3 years ago

depsimon started a new conversation Homestead - Same Project, Several Instances

Hello everyone,

I'm having a bit of a struggle here. I've this project that is the backend of an application.

This backend is to be deployed on multiple websites, let's say (admin.app.com, manager.app.com, etc..). So in my project I've conditions like

if (env('APP_TYPE') == 'ADMIN') { 
    // Admin Specific Code
}

I'm trying now to develop locally with Homestead but I don't know how to have separate .env files for my "sites" as they all link to the same project.

My Homestead.yaml has this sites configuration :

sites:
    - map: super.app.local
      to: /home/vagrant/Sites/app-repo/public
    - map: manager.app.local
      to: /home/vagrant/Sites/app-repo/public

Do you guys have an idea ?

28 Jul
3 years ago

depsimon left a reply on Sudo (or How To Access The Logs)

This should be done via your server provider.

In my case it's DigitalOcean and they provide a "Reset Root Password" feature, if your host doesn't have a feature like this you probably want to contact them directly.

15 Jul
3 years ago

depsimon left a reply on Action Parameters Names Doesn't Match Route Parameters Names

Thanks for your answers. I'll go with the two controllers then.

depsimon left a reply on Action Parameters Names Doesn't Match Route Parameters Names

Oh okay..

Do you have any suggestions @pmall ?

Maybe I should use 2 Controllers like User\WalletController.php and Club\WalletController.php. What do u think ?

depsimon started a new conversation Action Parameters Names Doesn't Match Route Parameters Names

Hi there,

I'd like to use a Controller method from multiple routes.

So for instance I have these two routes : /clubs/{club_id}/wallets/{wallet_id} that displays a club's wallet with information about the wallet's owner (an user) /users/{user_id}/wallets/{wallet_id} that displays an user's wallet with information about the wallet's club

The content of my controller method is the following.

    // WalletController.php
    public function show($club_id = null, $user_id = null, $id = null)
    {
        if ($user_id == null) {
            $clubResponse         = $this->apiGetOrFail('club/' . $club_id);
            $walletResponse       = $this->apiGetOrFail('club/' . $club_id . '/wallet/' . $id . '?include=user');
            $transactionsResponse = $this->apiGetOrFail('wallet/' . $id . '/transaction?page=' . $this->request->input('page', 1));

            return view( 'wallet.show')->with([
                'club'         => $clubResponse,
                'wallet'       => $walletResponse,
                'transactions' => $transactionsResponse,
            ]);
        } else {
            $clubResponse         = $this->apiGetOrFail('user/' . $user_id);
            $walletResponse       = $this->apiGetOrFail('user/' . $user_id . '/wallet/' . $id . '?include=club');
            $transactionsResponse = $this->apiGetOrFail('wallet/' . $id . '/transaction?page=' . $this->request->input('page', 1));

            return view( 'user.wallet.show')->with([
                'user'         => $userResponse,
                'wallet'       => $walletResponse,
                'transactions' => $transactionsResponse,
            ]);
        }
    }

But this doesn't work like I want.

Currently :

  • clubs/1/wallets/1 gives the following : $club_id = 1; $user_id = 1; $id = null
  • users/1/wallets/1 gives the following : $club_id = 1; $user_id = 1; $id = null

What I want :

  • clubs/1/wallets/1 gives the following : $club_id = 1; $user_id = 1; $id = null
  • users/1/wallets/1 gives the following : $club_id = null; $user_id = 1; $id = 1

Isn't that possible using the route parameters names ?

23 Jun
3 years ago

depsimon left a reply on How To Use The Same Blade For 2 Operations - Inserting A Empty Record/updating The Existing Record

You can use the same blade view for your forms. When I need to to the same I do this :

// routes.php
Route::get('book', 'BookController@create');
Route::get('book/{id}', 'BookController@edit');
// BookController.php
public function create()
{
    return view('form');
}

public function edit($id)
{
    $resource = Resource::find($id);

    return view('form', compact('resource'));
}
// form.blade.php
<h2>{{ isset($resource) ? 'Edit a Book' : 'Create a new Book' }}</h2>

<form action="{{ isset($resource) ? '/book/' . $resource->id : '/book' }}" method="post">
    <label>Title</label>
    <input type="text" name="title" value="{{ old('title', isset($resource) ? $resource->title : '') }}" />

    <label>Description</label>
    <textarea name="description">{{ old('description', isset($resource) ? $resource->description : '') }}</textarea>

    <button type="submit">{{ isset($resource) ? 'Update' : 'Create' }}</button>
</form>

depsimon started a new conversation Passing Form Data + File To An API

Hello everyone,

I've a L5 application that renders a form where the user can fill inputs and upload an image. This form is then sent to a Lumen API I built to persist the data.

I can easily send the classic inputs by catching them with Request::all(), but how can I pass the file as well ?

Here is my current code on the Laravel app, I'm using Guzzle to send my requests.

// EventController.php
public function store()
{
    // Some validation

    // Transform the data to give what the API expects
    $data = [
        'title'      => $this->request->input('title', ''),
        'content'    => $this->request->input('content', ''),
        'start_date' => $this->request->input('start_date'),
        'end_date'   => $this->request->input('end_date')
    ];
    $response = $this->client()->post('event', ['body' => $data]);
     // Handle the result
}
18 Jun
3 years ago

depsimon left a reply on Lumen 5.1

I didn't find any instructions either..

17 Jun
3 years ago

depsimon left a reply on Laravel 5 Auth Cross Domain Issue

I'm interested in a solution to this problem too...

I'm wondering if it does not need nginx config or something ?

16 Jun
3 years ago

depsimon left a reply on Changements In Refreshed Lessons

Whatever the reason behind an update, I think it's better if it's logged and visible on the lesson's page.

depsimon started a new conversation Changements In Refreshed Lessons

Hello everyone,

It would be great to have a little more details on the changements in a lesson when it's refreshed.

That way we could quickly know if we should watch the new version or not. (I don't want to waste my time if it's just a typo or something...)

15 Jun
3 years ago

depsimon left a reply on Creating An Eloquent Model For Stored Files

I suggest you persist your attachments data such as file name, extension, size, etc..

Then you would have a classic Eloquent model that you'll attach to your posts and/or users I guess.

11 Jun
3 years ago

depsimon left a reply on Laravel As An API Visual Interface

Hi @luceos, actually my problem is not in the API-side. The authentication works fine.

I'm just wondering what would be the best solution to consume the API with a Laravel application which doesn't store any data in a database.

Let's say my authentication is done, my API sends me back an access token to the Laravel app. My first call would be to get the authenticated user's data (/me for instance) to display a nice menu with his name (ie. Hello John Doe).

But then the user browses the interface and goes from page to page. Here is a real example flow:

  • Admin sign in. Authentication succeeds and Admin is redirected to the dashboard.
  • On the dashboard, admin has a nice table with the latests Users, Books and Comments. (calls to /user, /books, and comments).
  • etc..

How do I keep the data of my user through his visit ? Do I store it in the session when he's authenticated ? Do I call /me at each page view ? Is there another solution ?