andyandy

Member Since 7 Months Ago

Experience Points
12,070
Total
Experience

2,930 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
55
Lessons
Completed
Best Reply Awards
1
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 3
12,070 XP
Jan
14
1 week ago
Activity icon

Started a new Conversation How To Reinsert A Record Into A Table?

I want each of selected records reinsert into table as a new row (so they get highest ID + current created_at) and delete old row.

$records = Record::where('board_id', 2)->......blah blah......->get();

        foreach ($records as $record) {
           
	$newRecord = New Record();
	//???
            
        }

Jan
05
2 weeks ago
Activity icon

Replied to FPDF Sizing Of The Image - Anybody Knows How To?

If anybody finds this thread later, set all this stuff before setting image size:

                $pdf->setPrintHeader(false);
                $pdf->SetPrintFooter(false);
                $pdf->SetMargins(0, 0, 0);
                $pdf->SetAutoPageBreak(false, 0);
Activity icon

Started a new Conversation FPDF Sizing Of The Image - Anybody Knows How To?

I want to take JPG image and convert it to PDF. There are two scenarios:

  1. take single JPG, fill 100% of the width of the PDF
  2. take 2 images, size them to 297mm x 100mm (=half of A4), place them on the same page

I have this code using FPDF.

$pdf = new FPDF();
$pdf->setPrintHeader(false);
$pdf->AddPage();
$img_link = 'http://www.......';

$pdf->Image($link, 0, 0, 0,0);

$pdf->Output($_SERVER['DOCUMENT_ROOT'] . 'public/upload/test.pdf', "F");

I can find manual and even examples. http://www.fpdf.org/en/doc/image.htm But I have absolutely no idea what are they trying to say by that or how any of these units are suppose to work. I woukld be very grateful for the help with this.

Dec
23
1 month ago
Activity icon

Replied to The GET Method Is Not Supported For This Route. Supported Methods: POST.

If you want use that URL as to save data from form, route has to be Route:post, your form needs to have method="post" and you can't visit this URL in browser, only submit a form to this page.

Activity icon

Replied to The GET Method Is Not Supported For This Route. Supported Methods: POST.

Which URL are you trying to access? Just change that line from Route:POST to Route:GET

Dec
21
1 month ago
Activity icon

Replied to Eloquent - Generate Dynamical Number Of OrWhere Conditions

Thank you guys, second solution is better for my current situation.

Activity icon

Started a new Conversation Eloquent - Generate Dynamical Number Of OrWhere Conditions

I have string keyA;keyB;keyC (unknown number of elements) which we will explode(). I want do WHERE %LIKE% against table products / column name.

  • I can't use whereIn(), because then I can't use %LIKE%

  • I don't know how to use orWhere when there is dynamical number of KEYs each execution

Dec
18
1 month ago
Activity icon

Replied to Trying To Save Bigger XML File To Database, But Hitting Time Limit

Saving it every 1000 loops to database was actually an answer! @tray2

Solution of @rodrigo.pedra was not possible here because of the hosting setup.

Thank you guys.

Activity icon

Started a new Conversation Trying To Save Bigger XML File To Database, But Hitting Time Limit

I have 165 MB file with 110,000 entries. I want save of each entry to MySQL.

Showing them is doable:

//this will take 28 seconds

	$xml = simplexml_load_file('file.xml');
        foreach ($xml->primary as $product) {
            echo $product->name. '<br>';
        }

But as soon as I try to save them it fails:

//MAXIMUM EXECUTION TIME OF 120 SECONDS EXCEEDED


  $xml = simplexml_load_file('file.xml');
       	$parsedData = [];
        foreach ($xml->primary as $product) {
            $parsedData[] = [
                'name' => $product->name
            ];
        }

        Table::truncate();
        Table::insert($parsedData);



Activity icon

Replied to Eloquent - Insert If Not Exists

@rodrigo.pedra

  • 10.4.8-MariaDB
  • 5.5.62-0+deb8u1

Do I? I don't in both cases, right?

Activity icon

Replied to Eloquent - Insert If Not Exists

If not possible by Eloquent alone, could it be achieved by setting PRODUCT and VARIANT unique combination in DB, then inserting all the values and let it somehow "soft fail" when trying to insert already existing combination?

Activity icon

Replied to Eloquent - Insert If Not Exists

@neilstee

Yes, but by putting it inside foreach you went from my original 1 query to 1800 queries?

Dec
17
1 month ago
Activity icon

Started a new Conversation Eloquent - Insert If Not Exists

I need change in this - if combination of product_name and variant_name in the database exists don't insert it again.

foreach ($XML as $item) {
    $data[] = [
        'product' => $item->product_name,
        'variant' => $item->variant_name
    ];
}

PossibleCombinationsOfProductAndVariant::insert($data);
Dec
16
1 month ago
Activity icon

Started a new Conversation How To Structure Table/eloquent So It Is Effective?

I need to keep track of all PRODUCTS and it's possible VARIANTS. And update it when doing XML import.

Should I have 1 table or two tables to make it easier?

//1 table

1|tshirt|size M
2|tshirt|size XL
3|tshirt|size XXXL
4|jeans|size M

//2 tables
1|tshirt
2|jeans


1|1|size M
2|1|size XL
3|1|size XXXL
4|2|size M

How would I go about effectively saving it?

//BAD WAY TO DO IT

$xml =simplexml_load_file('XXX');
$list = $xml->order;
for ($i = 0; $i < count($list); $i++) {


	//this will result in 8000 queries to DB during XML import
	if(SavedProduct::where('product', $list[$i]->product)->first()){
		//save it to table
	}
	if(SavedVariant::where('product', $list[$i]->product)->where('variant', $list[$i]->variant)->first()){
		//save it to table
	}


}

Dec
14
1 month ago
Activity icon

Started a new Conversation GroupBy() On Two Columns And COUNT

I want group products with the same NAME and VARIANT and get COUNT of each group.

I understand I can count like this:

$user_info = DB::table('usermetas')
                 ->select('browser', DB::raw('count(*) as total'))
                 ->groupBy('browser')
                 ->get();

And I can group by two values like this:

$routes = DB::table('route')
    ->groupBy(['column_1', 'column_2'])
    ->get();

But I'm not sure how do I group by 2 values and get a count at the same time.

Dec
11
1 month ago
Activity icon

Replied to Get Collection From DB, Update Items In Collection And Save Back To DB (but Vanilla PHP)

@sinnbeck I just need secondary table connected by order_id, that will hold last STATUS and COMPLETED_DATE.

After truncate and insert new data into DB I will check what have changed.

Right?

Activity icon

Replied to Get Collection From DB, Update Items In Collection And Save Back To DB (but Vanilla PHP)

@sinnbeck

I was just thinking about something similar.

Only problem is the last point.

Activity icon

Replied to Get Collection From DB, Update Items In Collection And Save Back To DB (but Vanilla PHP)

I could run this, process whole XML and save it at the end with single query:

$xml = simplexml_load_file('basic.xml');
$list = $xml->order;

for ($i = 0; $i < count($list); $i++) {
	$order = $order . "('$ID', '$order_id', '$order_vs'....................
}

mysqli_query($mysqli, "TRUNCATE TABLE `orders`");
$queryOrders = "INSERT INTO orders (`id`, `order_id...............) VALUES " . $order;
mysqli_query($mysqli, "$queryOrders") or die($mysqli->error);


Which satisfies:

  • insert new into DB
  • delete old from DB

But doesn't:

  • if order_status in XML changes from NEW to COMPLETED save in DB date_completed
Activity icon

Replied to Get Collection From DB, Update Items In Collection And Save Back To DB (but Vanilla PHP)

@sinnbeck What if I used Laravel eloquent. Would my situation be easier with Product::get();

Activity icon

Started a new Conversation Get Collection From DB, Update Items In Collection And Save Back To DB (but Vanilla PHP)

I'm processing XML and updating MySQL (vanilla PHP).

I would like to do it in 2 MySQL queries (GET ALL DATA -> (edit whole set) -> SAVE ALL DATA BACK)

$allData = mysqli_query($mysqli, "select * from orders'");

$xml = simplexml_load_file('basic.xml');
$list = $xml->order;
//loop XML
for ($i = 0; $i < count($list); $i++) {
	//find order inside $allData by record_id
	//if status changed, update in $allData
	//if doesn't exists, insert new row in $allData
}

//delete from DB rows that weren't found in XML
//save $allData back to database

In Laravel words get collection from DB, update stuff inside and then save it back to DB.

Can you get me started?

Dec
08
1 month ago
Activity icon

Replied to Changing Timezone In Laravel 5.5.50

Till this moment I was using at the beginning of my scripts this (which solved misconfigured timezone in Laravel):

date_default_timezone_set("Europe/Prague");

Maybe I could put this in some Middleware? Would it work?

Activity icon

Replied to Changing Timezone In Laravel 5.5.50

It's a VPS managed by a hosting provider. I have no idea, I was given this project after 3 years of development by somebody else. Just need to change timezone.

Activity icon

Started a new Conversation Changing Timezone In Laravel 5.5.50

I've changed timezone in config/app.php:

'timezone' => 'Europe/Prague',

It works on localhost but when uploaded on server, it doesn't take effect. So I made this script:

public function test()
    {
        Artisan::call('cache:clear');
        dd(Carbon::now());
    }

Which again works on localhost. But on server puts to laravel.log following error:

[2020-12-08 06:03:33] production.ERROR: putenv() has been disabled for security reasons {"userId":8,"email":"[email protected]","exception":"[object] (ErrorException(code: 0): putenv() has been disabled for security reasons at /home/domains/expedice.xxxx/web/public/vendor/symfony/console/Application.php:111)
[stacktrace]

I don't have SSH access to this server.

Dec
05
1 month ago
Activity icon

Started a new Conversation Don't Wait For PHP Function To Finish Execution

AJAX calls a script which could return answer almost immediately, but it hangs for 700-500ms (depends) on updating relevant statistics etc. Could I just trigger function with these statistics and not wait for execution to finish and answer AJAX right away?

I would do it as queue job. But it's manager VPS without SSH. I can't install a supervisor to make queue jobs work as I usually do.

Dec
02
1 month ago
Activity icon

Replied to Empty Eloquent Functions Are Causing Problems?

@michaloravec @chaudigv

Yes, but how am I going to write that whereHas() part?

I will still end up with the same syntax, that filters by relationship even when empty.

Activity icon

Replied to Empty Eloquent Functions Are Causing Problems?

I pinpointed problem to this part:


})->whereHas('deliveryDate', function ($query) {
            if (request()->input('textSecondary') == 'OLDER_THAN_SELECTED_DATE') {
                return $query->where('calculated', '<', '0');
            }

When OLDER_THAN_SELECTED_DATE is not presented I don't want to filter by deliveryDate. But even an empty whereHas() is filtering only results that have this relationship.

If there is no OLDER_THAN_SELECTED_DATE I don't require this relationship.

How to edit it?

Activity icon

Started a new Conversation Empty Eloquent Functions Are Causing Problems?

I have this Eloquent. I'm suspecting that it is causing problems (probably when non of the conditions in function is met). Is there really a problem somewhere?

It is possible that during a execution non of condition is met (all requests are empty).

$search = Product::with('deliveryDate')->where('sent', 0)->where(function ($query) {
            if (request()->input('chckBx1')) {
                $query->orwhere('order_id', 'like', '%' . request()->input('text') . '%');
            }
            if (request()->input('chckBx2')) {
                $query->orWhere('customer_name', 'like', '%' . request()->input('text') . '%');
            }
            if (request()->input('chckBx3')) {
                $query->orWhere('own_remark', 'like', '%' . request()->input('text') . '%');
            }
            if (request()->input('chckBx4')) {
                $query->orWhere('remark', 'like', '%' . request()->input('text') . '%');
            }
            if (request()->input('chckBx5')) {
                $query->orWhere('name', 'like', '%' . request()->input('text') . '%');
            }
            if (request()->input('chckBx6')) {
                $query->orWhere('variant', 'like', '%' . request()->input('text') . '%');
            }
            if (request()->input('chckBx7')) {
                $query->orWhere('product_code', 'like', '%' . request()->input('text') . '%');
            }
        })->where(function ($query) {
            if (request()->input('chckBxA')) {
                $query->orwherecolumn('quantity', '!=', 'completed');
            }
            if (request()->input('chckBxB')) {
                $query->orWherecolumn('quantity', '=', 'completed');
            }
        })->where(function ($query) {
            //button search
            if (request()->input('textSecondary') == 'OWN_REMARK_NONORDER') {
                $query->where('own_remark', 'like', '%objednat%');
            }
        })->whereHas('deliveryDate', function ($query) {
            if (request()->input('textSecondary') == 'OLDER_THAN_SELECTED_DATE') {
                return $query->where('calculated', '<', '0');
            }
        })->orderBy('name', 'ASC')->orderBy('variant', 'ASC')->get();
Nov
30
1 month ago
Activity icon

Replied to A Single Page Is Loading Slower Than Others On The Server

@automica

OK, I will load only History and HistoryActions later on demand.

Activity icon

Replied to A Single Page Is Loading Slower Than Others On The Server

@automica

What about something like this?


        $history = History::orderBy('id', 'desc')->paginate(50);
        $historyActions = HistoryAction::whereIn('history_id', $history->pluck('id'))->get();
        $users = User::get();


Activity icon

Replied to A Single Page Is Loading Slower Than Others On The Server

@automica But that won't return all the HistoryActions for 50 selected Histories, right? Which will be a problem.

I don't understand it, if I removed ->has('historyAction') now it runs quickly. I thought that has() is just a filter?

Why does filter kills entire query? And eager loading doesn't, I would expect problem from this, not a filter?

Activity icon

Replied to A Single Page Is Loading Slower Than Others On The Server

@automica

History: 3385

HistoryAction: 13526

User: 12

Activity icon

Replied to A Single Page Is Loading Slower Than Others On The Server

@automica OK, I found problematic line. This takes 9 seconds.

$history = History::with('historyAction', 'historyAction.user')->has('historyAction')->orderBy('id', 'desc')->paginate(50);
public function historyAction()
    {
        return $this->hasMany('App\HistoryAction');
    }
    public function user()
    {
        return $this->belongsTo('App\User');
    }

Activity icon

Replied to A Single Page Is Loading Slower Than Others On The Server

@automica I'll will try debugbar.

Like I said, I measured controller + blade and problem isn't there.

Activity icon

Started a new Conversation A Single Page Is Loading Slower Than Others On The Server

Websites runs good. But there is a single page, that is loading for 10 seconds.

I measured execution time in controller (from start of function to return of view) which is 0.08 seconds. I measured execution time of blade template, which is 0.04 seconds. I checked for any composers with this view, but I didn't find anything.

On my localhost it runs good. Problem is on server only.

Currently files are uploaded via FTP file by file by hand (mistake possible). But I strongly believe scripts on server/localhost are in sync.

Any idea what to check next?

Nov
27
1 month ago
Activity icon

Replied to Simple Math Problem For Somebody More Clever Than Me...

@rodrigo.pedra

Your solution looks cleaner. I'm going to use yours.

Thank you.

Activity icon

Awarded Best Reply on Simple Math Problem For Somebody More Clever Than Me...

    var cekajici_historic = data.arrowBox1[1].split(',');
    var cekajici_historic_largest = 0;
    var cekajici_historic_lowest = 9999;
    //get largest/lowest historic bar
    for (i = 0; i <= 24; i++) {
        cekajici_historic[i] > cekajici_historic_largest ? cekajici_historic_largest = cekajici_historic[i] : null;
        cekajici_historic[i] < cekajici_historic_lowest ? cekajici_historic_lowest = cekajici_historic[i] : null;
    }
    //draw chart bars
    oldMax = cekajici_historic_largest;
    oldMin = cekajici_historic_lowest;
    newMax = 100;
    newMin = 30;
    oldRange = (oldMax - oldMin);
    newRange = (newMax - newMin);
    document.getElementById('cekajiciChart').innerHTML = '';
    for (i = 0; i <= 24; i++) {
        convertedValue = (((cekajici_historic[i] - oldMin) * newRange) / oldRange) + newMin;
        document.getElementById('cekajiciChart').innerHTML += '<div class="bar"><div class="value" style="height: ' + convertedValue + 'px;"></div></div>';
    }
Activity icon

Replied to Simple Math Problem For Somebody More Clever Than Me...

    var cekajici_historic = data.arrowBox1[1].split(',');
    var cekajici_historic_largest = 0;
    var cekajici_historic_lowest = 9999;
    //get largest/lowest historic bar
    for (i = 0; i <= 24; i++) {
        cekajici_historic[i] > cekajici_historic_largest ? cekajici_historic_largest = cekajici_historic[i] : null;
        cekajici_historic[i] < cekajici_historic_lowest ? cekajici_historic_lowest = cekajici_historic[i] : null;
    }
    //draw chart bars
    oldMax = cekajici_historic_largest;
    oldMin = cekajici_historic_lowest;
    newMax = 100;
    newMin = 30;
    oldRange = (oldMax - oldMin);
    newRange = (newMax - newMin);
    document.getElementById('cekajiciChart').innerHTML = '';
    for (i = 0; i <= 24; i++) {
        convertedValue = (((cekajici_historic[i] - oldMin) * newRange) / oldRange) + newMin;
        document.getElementById('cekajiciChart').innerHTML += '<div class="bar"><div class="value" style="height: ' + convertedValue + 'px;"></div></div>';
    }
Activity icon

Started a new Conversation Simple Math Problem For Somebody More Clever Than Me...

I'm generating bar chart. Data are coming as [20, 36, 15, 58, 60, 48, 14, 26, 18].

  • Highest value from array will be equal to 100px.

  • Lowest value from array will be equal to 30px;

Calculate 'px' for all the values from the array.

//it's in javascript, but I'm just looking for general idea

Nov
22
2 months ago
Activity icon

Started a new Conversation Problem Accessing Folder Locally In Script

Via browser you can access:

//public folder
www.website.com/public/img/background.jpg

//uploaded files (upload folder is at the same level as app, routes, resources etc.)
www.website.com/upload/1.jpg

And I'm having a problem getting UPLOAD files in script:

//non of these works
file_get_contents('upload/1.jpg');
file_get_contents('/upload/1.jpg');
file_get_contents('../upload/1.jpg');
file_get_contents('/../upload/1.jpg');
file_get_contents('../../upload/1.jpg');

//this works
file_get_contents('https://www.website.com/upload/1.jpg');

My thinking is if I manage it load locally it would save time/resources by not resolving a domain? But I can't get it work.

Nov
19
2 months ago
Activity icon

Started a new Conversation [JS] Infinite Page Scroll With Intersection Observer

I'm making infinite scroll. When I scroll down to "#infinite-scroll-trigger-reached" it will remove this DIV. Insert via AJAX 10 more posts. And put new "#infinite-scroll-trigger-reached" DIV after them.

I have Intersection Observer, when "#infinite-scroll-trigger-reached" DIV gets into viewport it will trigger it.

However it will trigger only first time. After removing/adding again of "#infinite-scroll-trigger-reached" DIV it will new fire again.

I tried unobserve/observe it again and lot of other things, but I can't make it work for the second time.

/** INFINITE SCROLL OBSERVER **/
const target = document.querySelector('#infinite-scroll-trigger-reached');
function handleIntersection(entries) {
    entries.map((entry) => {
        if (entry.isIntersecting && allowChanges) {
            allowChanges = false;
            infiniteScroll();
            console.log('observed');
        }
    });
}
const observer = new IntersectionObserver(handleIntersection);
observer.observe(target);

Activity icon

Started a new Conversation Using .php File...where To Put It

I want to create a .php file, that would be accessed directly as www.site.com/../file.php and would be unaffected by Laravel = only code in that file would be executed when file called.

No matter where I save this file I can't get it work. Usually a blank page. I don't know if this is issue with apache, htaccess or Laravel itself?

Nov
18
2 months ago
Activity icon

Replied to Vanilla SQL, Why I Can't Do This?

@marianomoreyra

Oh, of course!!! Thank you.

Activity icon

Started a new Conversation Vanilla SQL, Why I Can't Do This?

$result = DB::select('
            SELECT g.*
            FROM groups g
            JOIN products p ON p.group_id = g.id
            LEFT JOIN shipping s ON s.group_id = p.group_id AND s.order_id = p.order_id



	    //why I cant add this line here to limit it to only one group being selected?
            where g.id = 255
	    //end



            WHERE p.sent = 0
            GROUP BY g.id
');