trin

Member Since 10 Months Ago

Experience Points
19,740
Total
Experience

260 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
5
Lessons
Completed
Best Reply Awards
26
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.

  • Community Pillar

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

Level 4
19,740 XP
Apr
09
4 weeks ago
Activity icon

Replied to Hot Reload When Login Using Vuejs

ok, what u do in login? how other components understand, that the user is authorized? u use vuex?

Activity icon

Replied to Hot Reload When Login Using Vuejs

if u use vuex or other global states, u can write isAuth property to component. if isAuth changed, component will be updated. and u can use

vm.$forceUpdate();

but it not recommended )

Apr
07
1 month ago
Activity icon

Awarded Best Reply on How Get Object Of Dropped Item In Drag-and-drop Example?

in your code u setData on dragstart and write element id

x-on:dragstart.self="
                    dragging = true;
                    event.dataTransfer.effectAllowed='move';
                    event.dataTransfer.setData('text/plain', event.target.id);
                "

its mean, u can get this data from event:

toListingDropped: function (event) {
            ...
            console.log('toListingDropped event.srcElement.id::')
            console.log(event.dataTransfer.getData('text/plain'))

of couse u can write any data on dragstart element, like:

// on li.dragstart
x-on:dragstart.self="
	...
	event.dataTransfer.setData('user', JSON.stringify(nextUser));
"

// get data `user` from event
toListingDropped: function (event) {
	...
	console.log('drop user', JSON.parse(event.dataTransfer.getData('user')))

drop user {id: 3, name: "Your Item #3"}
Activity icon

Replied to How Get Object Of Dropped Item In Drag-and-drop Example?

in your code u setData on dragstart and write element id

x-on:dragstart.self="
                    dragging = true;
                    event.dataTransfer.effectAllowed='move';
                    event.dataTransfer.setData('text/plain', event.target.id);
                "

its mean, u can get this data from event:

toListingDropped: function (event) {
            ...
            console.log('toListingDropped event.srcElement.id::')
            console.log(event.dataTransfer.getData('text/plain'))

of couse u can write any data on dragstart element, like:

// on li.dragstart
x-on:dragstart.self="
	...
	event.dataTransfer.setData('user', JSON.stringify(nextUser));
"

// get data `user` from event
toListingDropped: function (event) {
	...
	console.log('drop user', JSON.parse(event.dataTransfer.getData('user')))

drop user {id: 3, name: "Your Item #3"}
Apr
03
1 month ago
Activity icon

Replied to How To Fire An API Call Faster Than The Time/speed Of Cron Jobs?

nodejs is js. u need create project

# mkdir ololo
# cd ololo
# npm install mysql

and simple index.js in ololo dir

import mysql form 'mysql'

const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
})

connection.connect()

setInterval(doJob, 500)

const doJob = () => {
	console.log('do job', new Date())
	connection.query('SELECT 1 + 1 AS solution', (error, results, fields) => {
  		if (error) throw error;
  		console.log('The solution is: ', results[0].solution);
	});
}

your script make mysql connection and execute doJob function every 500 ms

Activity icon

Replied to How To Fire An API Call Faster Than The Time/speed Of Cron Jobs?

minimal cron interval — 1 minute, not 1 second. for your case i recommended use nodejs, because it event-based lang and run demon with intervals — simple case for him

Apr
01
1 month ago
Activity icon

Replied to Vue 3 Form Components Recommendations?

u right, antd created for desktop app, but most component mobile-friendly. i use react, not vue and for react exist mobile version antd: https://mobile.ant.design.

usually for mobile i use RN, not web-based app, native. and for ui-kit i use react-native-elements or native-base. for web-based app i use antd or spectre.css. but spectre is no longer updated, which makes me cry at times

Activity icon

Replied to Javascript Loop Dont Increment Last Item Value

<p id="demo1"></p>
<p id="demo2"></p>
<script>
let text1 = ''
let text2 = ''
const month = 12
const amount = 100
const step = 5

let number1
let number2

for (let i = 0; i < month; i++) {
  number1 = amount + (step * i)
  number2 = ((number1*0.11/365)*31)
  
  text1 += number1 + '<br />'
  text2 += number2 + '<br />'
}

text1 += number1 + '<br />'
text2 += number2 + '<br />'
  
document.getElementById("demo1").innerHTML = text1
document.getElementById("demo2").innerHTML = text2
</script>

🤷‍♂️

Activity icon

Replied to Javascript Loop Dont Increment Last Item Value

very stranger code ) if u need for by months, use for by months, dont make life difficult for yourself

<p id="demo1"></p>
<p id="demo2"></p>
<script>
let text1 = ''
let text2 = ''
const month = 12
const amount = 100
const step = 5

for (let i = 0; i < month; i++) {
  const number1 = amount + (step * i)
  const number2 = ((number1*0.11/365)*31)
  
  text1 += number1 + '<br />'
  text2 += number2 + '<br />'
}
  
document.getElementById("demo1").innerHTML = text1
document.getElementById("demo2").innerHTML = text2
</script>
100
105
110
115
120
125
130
135
140
145
150
155

0.9342465753424658
0.9809589041095892
1.0276712328767124
1.0743835616438355
1.121095890410959
1.167808219178082
1.2145205479452055
1.2612328767123286
1.307945205479452
1.3546575342465752
1.4013698630136986
1.448082191780822
Mar
31
1 month ago
Activity icon

Replied to Javascript Coding Interview/test Tips

js event-based language. most backend-based app it is only request-response lifecycle. js app have permanent lifecycle, one load and work forever. js based app load one time and live forever with ajax/websocket request to api backend. js app can and must live without backend, i mean js app generate all html code, templates etc without php or other backend, backend only for api.

u need to understand Promise model, await/async models etc.

u need to understand and use es6. for support all browsers, u need to learn and understand babel.

u need to understand packages, npm or yarn. its like composer, needed libs installed by npm install lodash or yarn add lodash.

after understand packages, u need to understand webpack/gulp to make bundle from your app.

and, of course, u need to understand react-based frameworks, like react, vue, angular etc. most modern js app based on react frameworks.

as a result, if u want understand js app, u need:

  1. understand and love event-based app with permanent livecycle without reload page.
  2. understand es6 and Promise model, for support all browsers use babel
  3. understand packages and webpack philosophy
  4. understand and love react-based frameworks

sounds like harder, but it easy, if u use js everyday. and of course, you hardly need to know all this at once. and you are unlikely to immediately make the perfect dream app. but everything is moving towards the fact that a modern application is j, and the backend simply gives data to api.

once again that you need to google: es6, promise, npm/yarn, webpack/gulp, react/vue

Activity icon

Replied to Javascript Help

use devconsole next time )

Activity icon

Awarded Best Reply on Javascript Help

$(document).ready(...

not

$(document).read(
Activity icon

Replied to Javascript Help

$(document).ready(...

not

$(document).read(
Activity icon

Replied to Disable Keyboard Keys

like says @martinbean, u need accept tab key too, for navigation with keyboard for next/prev inputs. Tab keyCode is 9

https://keycode.info/

Activity icon

Replied to % Of Populated Model Fields

if u need calculate only for display data in front, i recommended use front for this task. u use client time, not your servers. if u need get statistics by percent users completion, u need calculate it on back, of course. i would make a method in the model, which calculate not null fields, for example. foreach for fieilds in model and relations (like photo/avatar), then calculate his weight in percent.

Activity icon

Awarded Best Reply on Disable Keyboard Keys

u need event keydown on input

const input = document.querySelector('input')
input.addEventListener('keydown', inputFilter)

and inputFilter function, who stop event, if keyCode not in array [37,38,39,40,8]. 37-40 for arrow, 8 for backspace.

const inputFilter = event => {
  if ([37,38,39,40,8].includes(event.keyCode)) { // if keyCode in array, just return
    return
  }
  event.preventDefault() // if keyCode not in array -- stop execution event
}

https://codepen.io/trin4ik/pen/wvgozgd

Mar
30
1 month ago
Activity icon

Replied to Disable Keyboard Keys

yes, i think need allow tab keys

Activity icon

Replied to Disable Keyboard Keys

u need event keydown on input

const input = document.querySelector('input')
input.addEventListener('keydown', inputFilter)

and inputFilter function, who stop event, if keyCode not in array [37,38,39,40,8]. 37-40 for arrow, 8 for backspace.

const inputFilter = event => {
  if ([37,38,39,40,8].includes(event.keyCode)) { // if keyCode in array, just return
    return
  }
  event.preventDefault() // if keyCode not in array -- stop execution event
}

https://codepen.io/trin4ik/pen/wvgozgd

Mar
28
1 month ago
Activity icon

Awarded Best Reply on Javascript QuerySelector Question

u need to call showDateNo, like showDateNo()

document.querySelector('#jssearchdate').addEventListener('click', function (event) {
    showDateNo();
}, false);

or with es6

document.querySelector('#jssearchdate').addEventListener('click', event => {
    showDateNo();
}, false);
Activity icon

Replied to Javascript QuerySelector Question

u need to call showDateNo, like showDateNo()

document.querySelector('#jssearchdate').addEventListener('click', function (event) {
    showDateNo();
}, false);

or with es6

document.querySelector('#jssearchdate').addEventListener('click', event => {
    showDateNo();
}, false);
Mar
19
1 month ago
Activity icon

Replied to Ssh To A Specific Server

ok, seems it send to error, run

<?php
$proc = proc_open("ssh [email protected] 'ls -la'",
array(
	array("pipe", "r"),
	array("pipe", "w"),
	array("pipe", "w")
	),
$pipes);
echo stream_get_contents($pipes[2]);

to read error

Activity icon

Replied to Ssh To A Specific Server

yes, with proc_open

<?php
$proc = proc_open("ssh [email protected] 'ls -la'",
array(
	array("pipe", "r"),
	array("pipe", "w"),
	array("pipe", "w")
	),
$pipes);
echo stream_get_contents($pipes[1]);
Activity icon

Replied to Ssh To A Specific Server

ssh [email protected] 'ls -la', where user and host -- your $server->ssh_user and $server->ip

if this also works, then the problem is not in the permissions

Activity icon

Replied to Ssh To A Specific Server

)))) ok, now execute ssh -V

Activity icon

Replied to Ssh To A Specific Server

try to execute simple command with proc_open, like

<?php
$proc = proc_open("whoami",
array(
	array("pipe", "r"),
	array("pipe", "w"),
	array("pipe", "w")
	),
$pipes);
echo stream_get_contents($pipes[1]);
Activity icon

Replied to Ssh To A Specific Server

look here https://serverfault.com/questions/157272/allow-apache-to-run-a-command-as-a-different-user

try to modify /etc/sudoers

$ php -r 'system("whoami");'
trin # <-- user, who can ssh

$ which ssh
/usr/bin/ssh # <-- ssh

$ sudo echo "www-data ALL=(trin) NOPASSWD: /usr/bin/ssh" >> /etc/sudoers # <-- allow www-data user execute ssh

or somethink like that. at least so in Linux

Activity icon

Replied to Ssh To A Specific Server

https://symfony.com/doc/current/components/process.html#configuring-process-options

Symfony uses the PHP proc_open function to run the processes. You can configure the options passed to the other_options argument of proc_open() using the setOptions() method:

mb proc_open disabled in fpm ini? check disable_functions in php.ini

Mar
16
1 month ago
Activity icon

Replied to GlobalVueStyles

im not use mix, but look here

i think somethink like this:

mix.js('resources/js/app.js', 'public/js')
    .vue()
    .sass('resources/sass/main.scss', 'public/css', {
		sassOptions: {
			additionalData: `@import "./resources/sass/utils/_variables.scss";`
		}
	})
    .options({
		extractVueStyles: true,
    })
    .version()
Activity icon

Replied to Package Recommendation For Vue 2.6 - Check Dirty State In Forms

offtopic. i moved from vuex/redux to mobx, including because of this problem

Activity icon

Replied to Custom Validation Error Formating

f*ck, am late )) yes, it is one of way

Activity icon

Replied to Custom Validation Error Formating

FormRequest way, its create Requests/ApiRequest.php with code like

<?php

namespace App\Http\Requests;

use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Foundation\Http\FormRequest;

class ApiRequest extends FormRequest
{
    protected function failedValidation(Validator $validator)
    {
        $error = (new ValidationException($validator))->errors();
		$message = (new ValidationException($validator))->getMessage();
        throw new HttpResponseException(
            response()->json(
                [
					'reports' => [
						'type' => 'fail',
						'message' => $message,
						'validation' => ... /* your map code for error */
					]
                ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
        );
    }
}

Activity icon

Replied to Custom Validation Error Formating

just discussed this (https://laracasts.com/discuss/channels/laravel/request-class-for-api), u can override Exceptions/Handler.php, or extends FormRequest and create u own structure

Activity icon

Replied to Request Class For API

controversial statement. what if i send Accept: image/png? )) in my case, i need not only json response, but with structure, like:

// good response
{
	"success": true,
	"data": ...
}

// bad response
{
	"success": false,
	"error": ...
}

and if i create backend api with laravel (no need web response), im not care about Accept, all responses are json. as I understand, i have two ways to realize it

  • extends FormRequest, as i said
  • extends Exceptions/Handle.phpto override render like (for example)
public function render($request, $exception)
    {
        if ($exception instanceof ModelNotFoundException) {
            return response()->json([
                'success' => false,
                'error' => 'not found id in model',
                'exception' => $exception
            ], Response::HTTP_NOT_FOUND);
        }
        return parent::render($request, $exception);
    }

but as I understood, second way more globally and if i use some external module with web interface (telescope etc) it is bad idea.

if i wrong, tell me please best way to response all my requests with json on my structure. hmmm... I'll think about it

Activity icon

Replied to Request Class For API

yes

<?php
namespace App\Http\Requests;

use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Foundation\Http\FormRequest;
Activity icon

Awarded Best Reply on Request Class For API

i created extend for FormRequest

class ApiRequest extends FormRequest
{
    protected function failedValidation(Validator $validator)
    {
        $error = (new ValidationException($validator))->errors();
        throw new HttpResponseException(
            response()->json(
                [
                    'success' => false,
                    'error' => $error
                ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
        );

        parent::failedValidation($validator);
    }
}

and extended other Request files like

class OrderCreateRequest extends ApiRequest
Activity icon

Replied to General Error: 29 File Not Found

stupid question, but what host your database? same server?

Activity icon

Replied to Request Class For API

welcome )

Activity icon

Replied to Simplify Code

u can use scopes https://laravel.com/docs/8.x/eloquent#local-scopes

in Electricity_Transaction model adds like

public function scopeMonth($month = date('m'), $year = date('Y'))
{
	return $query->whereMonth('created_at', $month)->whereYear('created_at', $year);
}
public function scopeRegion($region = 'Jakarta')
{
	return $query->where('regional','LIKE','%' . region . '%');
}

and in your controller like

public function DataElectricalJson()
{
return response()->json([
	'january_electrical_jkt' => Electricity_Transaction::month(1)->region('Jakarta')->sum('nominal') ?? 0,
	'febuary_electrical_jkt' => Electricity_Transaction::month(2)->region('Jakarta')->sum('nominal') ?? 0,
	'maret_electrical_jkt' => Electricity_Transaction::month(3)->region('Jakarta')->sum('nominal') ?? 0,
            ...
]); 
}
Activity icon

Replied to General Error: 29 File Not Found

in terminal exec

ls -la /home/workspace/Documents/projects/laravel-site/storage/csvs/

and post here

Activity icon

Replied to Request Class For API

i created extend for FormRequest

class ApiRequest extends FormRequest
{
    protected function failedValidation(Validator $validator)
    {
        $error = (new ValidationException($validator))->errors();
        throw new HttpResponseException(
            response()->json(
                [
                    'success' => false,
                    'error' => $error
                ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
        );

        parent::failedValidation($validator);
    }
}

and extended other Request files like

class OrderCreateRequest extends ApiRequest
Activity icon

Replied to General Error: 29 File Not Found

mysql user cant read from folder /home/workspace/Documents/projects/laravel-site/storage/csvs/, change permission to folder/file or move file to /tmp, for example

Activity icon

Replied to Best Place For Modification Of Input Data?

i think it not BEST practice ) but i use it too ))

Activity icon

Replied to Laravel API With JWT

of couse. normal module: https://github.com/tymondesigns/jwt-auth

or u can write u own implementation jwt module. i use tymondesigns/jwt-auth, but i don't always like it and I'm thinking about making my own implementation. for example, sometimes you want to customize unsinged data in a token so that you can manipulate it down to php, at the nginx level. but in general this is a great module

Mar
15
1 month ago
Activity icon

Replied to Using Set Timeout For Jetstream Banner.blade.php

i realy not good in blade components, but think this is solution

<div class="absolute z-10 right-3 rounded bottom-3 w-1/4"
     x-data="{{ json_encode(['show' => true, 'style' => $style, 'message' => $message]) }}"
     :class="{ 'bg-indigo-500': style == 'success', 'bg-red-700': style == 'danger' }"
     style="display: none;"
     x-show="show && message"
     x-init="
                document.addEventListener('banner-message', event => {
                    style = event.detail.style;
                    message = event.detail.message;
                    show = true;
					setTimeout(() => show = false, 2000)
                     });
                     "
Activity icon

Replied to Forms & API Requests (Laravel&Vue&Inertia.js)

offtopic.

u use arrow functions

...
then(({ data }) => {
	if (data.success) {
...

and es5 style

window.addEventListener(
	'message',
	function (event) {
		if (event.data.success == true) {
			this.successPayment()
		}
	}.bind(this)
)

in one place. it is not are bug or error, but not true. u can always use es6 style

window.addEventListener(
	'message',
	event => {
		if (event.data.success == true) {
			this.successPayment()
		}
	}
)

less code, no need to bind this etc

https://gist.github.com/JacobBennett/7b32b4914311c0ac0f28a1fdc411b9a7

Activity icon

Replied to Laracasts Discuss Push Notification 0.35 (chrome & Firefox Extension)

big update guys, added scanner for new topics. in experimental mode. one time in 60 secs scanning /discuss for new topics and push notification to u, if u subscribe on category.