MartinZeltin

MartinZeltin

Member Since 1 Year Ago

Experience Points
23,700
Total
Experience

1,300 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
151
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 5
23,700 XP
May
14
2 weeks ago
Activity icon

Replied to How To Get Only One KeyBy Value Instead?

@nakov Perfect, that's exactly what I was looking for! Thank you!

Activity icon

Started a new Conversation How To Get Only One KeyBy Value Instead?

I have this settings table where I have key and value columns

+----+----------+-------------+
| id | key      | value       |
+----+----------+-------------+
| 1  | logo_img | my-logo.jpg |
| 2  | version  | 1.1         |
+----+----------+-------------+

and I would like to get the results like this.

"settings": {
  "logo_img": "my-logo.jpg",
  "version": 1.1,
}

But instead I get the results like this if I use keyBy()

$settings = Settings::all()->keyBy('key');

Results:

"settings": {
  "logo_img": {
    "id": 1,
    "key": "logo_img",
    "value": "my-logo.jpg"
  },

  "version": {
    "id": 2,
    "key": "version",
    "value": "1.1"
  }
}

In the end I would like to refer to settings like this $settings->logo_img instead of $settings->logo_img->value

Not sure how to do this

Apr
21
1 month ago
Activity icon

Replied to How To Have Multiple Domains For COOKIE Session?

@tippin Thank you, overriding config at runtime is brilliant! I will give this a try.

Activity icon

Started a new Conversation How To Have Multiple Domains For COOKIE Session?

My application can be accessed using 2 different domain names www.4evergaming.com and www.best4games.com

Here is how my routes file looks like

Route::pattern('domain', '(www.4evergaming.com|www.best4games.com)');
Route::domain('{domain}')->group(function ()
{
	// Routes here...
})

But in my config/session.php I can only have one domain...

'domain' => '.4evergaming.com',

I need to set session cookies for both domains but how can I do this?

Apr
08
1 month ago
Activity icon

Replied to Someone Told Me That A Laravel App Is Difficult To Maintain, Is It True?

@tray2 I agree that a lot of it depends on the developer. Do you think it could be an issue if the code base gets very large?

Activity icon

Started a new Conversation Someone Told Me That A Laravel App Is Difficult To Maintain, Is It True?

A friend of mine (business man, not a programmer) told me that Laravel applications are difficult to maintain. Specifically their codebase as it gets very large. That's why he prefers to use Symphony framework instead.

What do you think about this? Is it true? What are your thoughts on this?

Mar
03
2 months ago
Activity icon

Started a new Conversation How To Separate Node.js App Into 2 Different Files?

I have a simple Node.js app. But I would like to extract one part of it into another file but I don't know how to do this.

Here is my app

const fs = require('fs')
const https = require('https')
const express = require('express')

const app = express()

const server = https.createServer({
    cert: fs.readFileSync('/etc/letsencrypt/live/www.4evergaming.com/cert.pem'),
    key: fs.readFileSync('/etc/letsencrypt/live/www.4evergaming.com/privkey.pem'),
}, app)


server.listen(443)

I would like to put this part into a file certificate.js and include it in my main app.js file

certificate.js

const server = https.createServer({
    cert: fs.readFileSync('/etc/letsencrypt/live/www.4evergaming.com/cert.pem'),
    key: fs.readFileSync('/etc/letsencrypt/live/www.4evergaming.com/privkey.pem'),
}, app)

I would appreciate some help on this...

Jan
28
4 months ago
Activity icon

Replied to Getting Strange Things When Using Where() With Join() - Adds = '' At The End Of Join

@sinnbeck thanks, you're right, plus I needed to use DB::raw() to avoid backticks.

Activity icon

Started a new Conversation Getting Strange Things When Using Where() With Join() - Adds = '' At The End Of Join

I am getting this strange query from my join subquery (notice the = '' at the end)

inner join
...
as `joined` on `date(joined`.`created_at) = date(cash_register_order_total_history`.`created_at)` = '' order by date_of_month

Why does Laravel add the strange = '' at the end? I'm getting a syntax error because of it.

Here is my query

$join2 = \App\Models\CashRegisterOrderTotalHistory::from('cash_register_order_total_history as history')
        ->select('order_sum as last_order_sum', 'created_at')
        ->where('created_at', function($query) {
            $query->selectRaw('max(created_at) from cash_register_order_total_history history2 where date(history2.created_at) = date(history.created_at)');
        });

$results = \App\Models\CashRegisterOrderTotalHistory::selectRaw('
    date(cash_register_order_total_history.created_at) as date_of_month,
    weekday(cash_register_order_total_history.created_at) + 1 as day_of_week,
    sum(order_sum) as total_order_sum,
    sum(items.total_beef_used) as total_beef_used,
    max(cash_register_order_total_history.created_at) as lastorderdate,
    max(joined.last_order_sum) as last_order_sum
')->joinSub($join2, 'joined', function ($join) {
   $join->on('date(joined.created_at) = date(cash_register_order_total_history.created_at)');
})->groupBy('date_of_month')
  ->toSql();
Activity icon

Started a new Conversation How To Convert This Query To Eloquent ORM?

I have this query but I'm not sure how I would go about converting it into an eloquent ORM so I don't have to use raw sq.

select 
    date(o.created_at) as date_of_month,
    sum(order_sum) as total_order_sum,
    sum(i.total_energy_used) as total_energy_used,
    max(o.created_at) as lastorderdate,
    max(s.last_order_sum) as last_order_sum
from
    orders o
join (
    select
        order_id,
        sum(energy_used) total_energy_used
    from
        order_items i
    group by
        order_id
) i on o.id = i.order_id
join (
    select
        order_sum as last_order_sum,
        created_at
    from
        orders o
    where
        created_at = (
            select max(created_at) from orders o1 where date(o1.created_at) = date(o.created_at)
        )
    ) s on date(s.created_at) = date(o.created_at) 
group by
    date(o.created_at);

Here is a fiddle: http://sqlfiddle.com/#!9/bf799d/22

Activity icon

Started a new Conversation Can't Get The Last Order Sum For Each Day When Using Group By And Joins

I have two tables orders and order_items. I need to group the results by days.

But I also need to get for each day:

  • the sum of order_items.energy_used for all orders created that day
  • the sum of orders.order_sum for all orders created that day
  • the last created_at and order_sum that correspond to the latest order created on that day

I am able to get everything except the last sum of order_sum for each day.

Any help would be much appreciated

Here is my orders table

+----+-----------+---------+---------------------+
| id | order_sum | user_id | created_at          |
+----+-----------+---------+---------------------+
| 1  | 25.13     | 7       | 2020-01-25 09:13:00 |
| 2  | 10.00     | 7       | 2020-01-25 15:23:00 |
| 3  | 14.00     | 5       | 2020-01-26 10:14:00 |
| 4  | 50.00     | 5       | 2020-01-26 19:14:00 |
| 5  | 35.00     | 1       | 2020-01-27 11:13:00 |
+----+-----------+---------+---------------------+

And here is my order_items table

+----+----------+-------------+---------------------+
| id | order_id | energy_used | created_at          |
+----+----------+-------------+---------------------+
| 1  | 1        | 65          | 2020-01-25 09:13:00 |
| 2  | 1        | 12          | 2020-01-25 09:13:00 |
| 3  | 1        | 12          | 2020-01-25 09:13:00 |
| 4  | 2        | 70          | 2020-01-25 15:23:00 |
| 5  | 2        | 5           | 2020-01-25 15:23:00 |
| 6  | 3        | 0           | 2020-01-26 10:14:00 |
| 7  | 4        | 1           | 2020-01-26 19:14:00 |
| 8  | 5        | 5           | 2020-01-27 11:13:00 |
+----+----------+-------------+---------------------+

And this is the desired result that I am trying to achieve

+---------------+-----------------+-------------------+---------------------+----------------+
| date_of_month | total_order_sum | total_energy_used | last_order_date     | last_order_sum |
+---------------+-----------------+-------------------+---------------------+----------------+
| 2020-01-25    | 35.13           | 164               | 2020-01-25 15:23:00 | 10.00          |
| 2020-01-26    | 64.00           | 1                 | 2020-01-26 19:14:00 | 50.00          |
| 2020-01-27    | 35.00           | 5                 | 2020-01-27 11:13:00 | 35.00          |
+---------------+-----------------+-------------------+---------------------+----------------+

With this query I can get everything except the last order_sum of each day

select 
    date(o.created_at) date_of_month,
    sum(i.total_energy_used),
    max(o.created_at),
    sum(order_sum) as total_order_sum
from orders o
inner join (
    select order_id, sum(energy_used) total_energy_used
    from order_items i
    group by order_id
) i on o.id = i.order_id
group by date(o.created_at)
Jan
27
4 months ago
Activity icon

Started a new Conversation Column Not Found In 'group Statement' When Using Pagination

It looks like when Laravel generates the necessary data for pagination, it overrides the SELECT part of my statement. That means I lose all my selects and aliases and it can't find it in the group clause anymore... :( What can I do?

$orders = Orders::selectRaw('
    date(created_at) as date_of_month,
    weekday(created_at) + 1 as day_of_week,
    sum(order_sum) as order_sum
')->groupBy('date_of_month')
  ->paginate();

And then I get this error:

    message: "SQLSTATE[42S22]:
    Column not found:
    1054 Unknown column 'date_of_month' in 'group statement'  (SQL: select count(*) as aggregate from `orders` group by `date_of_month`)
    exception: "Illuminate\Database\QueryException"
Jan
21
4 months ago
Activity icon

Replied to How To Capture An Input Device And Prevent It's Default Behavior

@snapey There were no any drivers that came with the reader. From what I have read, usually USB RFID readers come with HID drivers or the included drivers will create a “Virtual Serial Port” just like those ‘old’ RS232/DB9 ports. Then you can either send a READ command or just open the port and listen on it.

So I guess that means I need to write my own driver for it...

Activity icon

Started a new Conversation How To Capture An Input Device And Prevent It's Default Behavior

I have an RFID tag reader. But it works like a HID device (like a keyboard). It sends keystrokes to the computer when a tag is scanned. When I open notepad and scan a tag - it types the ID one digit at a time. Is there a way to create a program to listen to this device (or this port) and capture (intercept) all input. So that the keystrokes wouldn't appear on my system but I could assign my own events when the device sends and input. I don't want it to show up on Notepad.

I realize that the implementation can differ depending on the OS and programming language used. Ideally, I would like to make this work on both Windows and Linux. I would prefer to use something like Node.js but I suppose C could also be good.

I would appreciate any hints or pointing me in the right direction.

enter image description here

Jan
15
4 months ago
Activity icon

Replied to How To Add A A Property To My Collection?

@sti3bas thanks, it looks ugly but it works...

Activity icon

Started a new Conversation How To Add A A Property To My Collection?

I have tried using put() method but it didn't work....

I have this collection and I want to add a new property for user with id 73 but how could I do this?

This is my collection

$collection->where('user_id', 73)->put('age', 35);
dump($collection->toArray());

Array
(
    [0] => Array
        (
            [user_id] => 73
            [score] => 3623
        )

    [1] => Array
        (
            [user_id] => 114
            [score] => 4204
        )

    [2] => Array
        (
            [user_id] => 46
            [score] => 1347.6
        )

    [3] => Array
        (
            [user_id] => 7
            [score] => 3841
        )

)

I wanted the result to look like this..

Array
(
    [0] => Array
        (
            [user_id] => 73
            [score] => 3623
            [age] => 35
        )

    [1] => Array
        (
            [user_id] => 114
            [score] => 4204
        )

    [2] => Array
        (
            [user_id] => 46
            [score] => 1347.6
        )

    [3] => Array
        (
            [user_id] => 7
            [score] => 3841
        )

)
Jan
14
4 months ago
Activity icon

Commented on A Project Requires An Owner

The a_user_can_create_a_project() test will fail unless you use a factory.

Add this at the top

$attributes = factory('App\Project')->raw();
Dec
22
5 months ago
Activity icon

Started a new Conversation How To Remove Docker Volumes For Production And COPY Instead?

I have a simple Laravel application with Nginx, PHP and MySQL each in its own container. It works great in my development environment but for production I need to remove bind volumes and copy the contents to the image itself instead. But how do I do this?

The rule is that a production container should be immutable

Do I need a seperate docker-compose-prod.yml file? How can I remove volues for production? How can I copy my source code and configuration to the image when deploying for production?

Here is my docker-compose.yml file

version: '3'

networks:
  laranet:

services:
  nginx:
    image: nginx:stable-alpine
    
    container_name: nginxcontainer
    
    ports:
      - "80:80"

    volumes:
      - ./src:/var/www/html
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf

    depends_on:
      - php
      - mysql

    networks:
      - laranet

  mysql:
    image: mysql:5.7.22

    container_name: mysqlcontainer

    ports:
      - "3306:3306"

    volumes:
      - ./mysql:/var/lib/mysql

    networks:
      - laranet

  php:
    build:
      context: .
      dockerfile: php/Dockerfile
    
    container_name: phpcontainer

    volumes:
      - ./src:/var/www/html

    ports:
      - "9000:9000"

    networks:
      - laranet

and here is my php/Dockerfile

FROM php:7.2-fpm-alpine

RUN docker-php-ext-install pdo pdo_mysql
RUN chown -R www-data:www-data /var/www
RUN chmod 755 /var/www
Dec
21
5 months ago
Activity icon

Replied to I Don't Understand Why I Need To Mount Docker Volumes For Both Nginx And PHP

@bugsysha How do you deploy it to another server without COPY?

Activity icon

Replied to I Don't Understand Why I Need To Mount Docker Volumes For Both Nginx And PHP

Thank you for the help, @bugsysha. I'm a little confused. How could I make this for production instead of mounting volumes for local development?

For example, is this correct?

nginx:
   COPY . /var/www/html

php:
   COPY . /var/www/html
Activity icon

Started a new Conversation I Don't Understand Why I Need To Mount Docker Volumes For Both Nginx And PHP

I have a simple Laravel application with Nginx, PHP and MySQL each in its own container. What I don't understand is:

  1. why do I need to mount volumes for both my Nginx and also PHP? Isn't PHP only a programming language not a server?

  2. Also, for production do I need to COPY my src to /var/www/html but do I need to do it for both Nginx and PHP? Or only for Nginx?

Here is my docker-compose-dev.yml file

version: '3'

networks:
  laravel:

services:
  nginx:
    image: nginx:stable-alpine
    
    container_name: nginxcontainer
    
    ports:
      - "8088:80"

    volumes:
      - ./src:/var/www/html
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf

    depends_on:
      - php
      - mysql

    networks:
      - laravel

  mysql:
    image: mysql:5.7.22

    container_name: mysqlcontainer

    restart: unless-stopped

    tty: true

    ports:
      - "4306:3306"

    volumes:
      - ./mysql:/var/lib/mysql

    environment:
      MYSQL_DATABASE: homestead
      MYSQL_USER: homestead
      MYSQL_PASSWORD: secret
      MYSQL_ROOT_PASSWORD: secret
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql

    networks:
      - laravel

  php:
    build:
      context: .
      dockerfile: php/Dockerfile-dev
    
    container_name: phpcontainer

    volumes:
      - ./src:/var/www/html

    ports:
      - "9000:9000"

    networks:
      - laravel

and here is my php/Docker-dev file

FROM php:7.2-fpm-alpine

RUN docker-php-ext-install pdo pdo_mysql
RUN chown -R www-data:www-data /var/www
RUN chmod 755 /var/www
Activity icon

Replied to Docker

+1 also on a Docker series! Please?

Dec
09
5 months ago
Activity icon

Awarded Best Reply on Can't Upload A File From Node.js To My Route, Getting Empty Request

@nakov Thank you for all your help!

I finally got it to work after thoroughly reading the documentation for the node.js form-data library. I was passing in the wrong headers, I needed to first get the headers from my formData object and then pass them on to axios like this:

function uploadScreenshot()
{
    let formData = new FormData()
    let stream   = fs.createReadStream(path.join(__dirname, 'screenshot.jpg'))

    formData.append('screenshot-file', stream)

    let formHeaders = formData.getHeaders()

    axios.post('https://www.myapp.com/api/upload-screenshot', formData, {
        headers: {
            ...formHeaders,
        },
    }).catch(error => {
        console.log(error)
    })
}
Activity icon

Replied to Can't Upload A File From Node.js To My Route, Getting Empty Request

@nakov Thank you for all your help!

I finally got it to work after thoroughly reading the documentation for the node.js form-data library. I was passing in the wrong headers, I needed to first get the headers from my formData object and then pass them on to axios like this:

function uploadScreenshot()
{
    let formData = new FormData()
    let stream   = fs.createReadStream(path.join(__dirname, 'screenshot.jpg'))

    formData.append('screenshot-file', stream)

    let formHeaders = formData.getHeaders()

    axios.post('https://www.myapp.com/api/upload-screenshot', formData, {
        headers: {
            ...formHeaders,
        },
    }).catch(error => {
        console.log(error)
    })
}
Activity icon

Replied to Can't Upload A File From Node.js To My Route, Getting Empty Request

@nakov The second one returns an empty array [] when doing $request->all()

But the first one submits the hello and asdf

Activity icon

Replied to Can't Upload A File From Node.js To My Route, Getting Empty Request

@nakov now I'm getting this error

UnhandledPromiseRejectionWarning: ReferenceError: FormData is not defined
Activity icon

Replied to Can't Upload A File From Node.js To My Route, Getting Empty Request

@nakov , that example is using a form upload but I have a local file on my system that I'm trying to upload.

Here is the result of console.log(fs.createReadStream(path.join(__dirname, 'screenshot.jpg')))

ReadStream {
  readable: true,
  _events: [Object: null prototype] { end: [Function] },
  _eventsCount: 1,
  path: 'C:\Users\Martins\Desktop\Programming\node-screenshot\screenshot.jpg',
}

So this seems to work.

But what was strange that this didn't work. I just got an empty [] from $request->all()

let formData = new FormData()
formData.append('test', 'variable')
axios.post(
  `https://www.myapp.com/api/upload-screenshot`,
  formData,
  { headers: { 'content-type': 'multipart/form-data' } }
)
Activity icon

Replied to Can't Upload A File From Node.js To My Route, Getting Empty Request

However doing a simple post request, it does arrive at the server. So something must be wrong with my formData...

axios.post(`https://www.myapp.com/api/upload-screenshot`, {
   hello: 'asdf'
})
Activity icon

Started a new Conversation Can't Upload A File From Node.js To My Route, Getting Empty Request

I am trying to upload a local file using NodeJs (the file is in the same directory as app.js) to my remote Laravel server but I'm getting null. For some reason the file doesn't seem to get to the server. I'm not sure what I'm doing wrong..

Here is my node app folder structure

node_app/
├── node_modules/
├── app.js
├── screenshot.jpg
├── package.json

Here is my app.js

const fs = require('fs')
const path = require('path')
const axios = require('axios')
const FormData = require('form-data')
const screenshot = require('screenshot-desktop')

let formData = new FormData()
formData.append('screenshot-file', fs.createReadStream(path.join(__dirname, 'screenshot.jpg')))

axios.post(
  `https://www.myapp.com/api/upload-screenshot`,
  formData,
  { headers: { 'content-type': 'multipart/form-data' } }
)

And here is my endpoint controller

class ScreenshotController extends Controller
{
    public function upload(Request $request)
    {
        // $file is null :(
        $file = $request->file('screenshot-file');

        $filename = 'screenshot.jpg';
        $file->move(storage_path('/uploads/screenshots/'), $filename);

        return $filename;
    }
}

Error: 'Call to a member function move() on null'

When the request arrives at my controller, there doesn't seem to be a 'screenshot-file' file submitted as it is showing null.

Also using dump($request->all()); it returns an empty array [] which means nothing has been submitted.

Dec
01
5 months ago
Activity icon

Replied to How To Use Websockets Without Echo And Laravel-websockets

I suppose I could send a request to my Node.js server from my Laravel app, but is that a good idea?

Nov
30
5 months ago
Activity icon

Started a new Conversation How To Use Websockets Without Echo And Laravel-websockets

I am trying to implement websockets in my Laravel application. I tried to use the beyondcode/laravel-websockets PHP package with Laravel Echo but it was too difficult and complicated. When I tried to broadcast an event it didn't work.

So I turned to Node.js and with native HTTP ws API. It is very simple to use but I can't use it from inside of my Laravel application to broadcast a message. I want to keep it very simple, what are my options?

Here is how I set it up using Node.js (very simple)

Node.js

const WebSocket = require('ws')
const server = new WebSocket.Server({ port: 6001 })

server.on('connection', ws => {
    setInterval(() => {
        ws.send('Random data: ' + Math.random())
    }, 2000)
})

client/index.html

<script>
    const connection = new WebSocket(`ws://${window.location.hostname}:6001`)

    connection.addEventListener('message', event => {
        console.log(event.data)
    })
</script>

It works but how can I integrate it into Laravel? Without making it too complicated.