MartinZeltin

MartinZeltin

Member Since 2 Months Ago

Experience Points 8,320
Experience
Level
Lessons Completed 61
Lessons
Completed
Best Reply Awards 0
Best Answer
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.

15 Nov
5 days ago

MartinZeltin started a new conversation How To Send Raw Html Email With Laravel?

I have successfully sent a raw text email with Laravel Mail but how could I send an HTML email (without using a view)?

\Mail::raw('Text to e-mail', function($message)
{
         $message->from('[email protected]', 'Laravel');
         $message->to('[email protected]');
});

MartinZeltin started a new conversation How To Send Email With Laravel Using Sendmail?

I am running a Linux machine with configured sendmail that send email by simply executing a mail() function. How could I take advantage of the Laravel mail functionality using sendmail?

I looked into config/mail.php and it asked for driver, host, port, username, password - but those things are already configured in sendmail.

Can I just specify the driver to be sendmail and leave username, host, password blank since sendmail takes care of that stuff already?

MartinZeltin started a new conversation How To Avoid Mixing PHP Code In View And Vice Versa?

I am learning to write better code and to not mix PHP code with HTML/CSS since that will be better both for me and people who will read my code after me. However I stumbled upon a situation where I have users with different roles and each role has it's own color/class/style/html. I end up putting either HTML code in my PHP logic or vice versa. Is there a nice way around this?

In Controller:

if ($user_role == 'administrator') {
    $user_color == '#ff0000'; <-- CSS Style in my PHP
    $user_class == 'admin-class'; <-- CSS Class in my PHP
}

$users = [
    'username' => 'John',
    'user_color' => '#ff0000' <-- CSS Style in my PHP
]

In my View:

<a class="{{ $user_class }} style="color: {{ $user_color }}">Administrator</a>
or if I did not want HTML or CSS in my PHP then I end up putting PHP in my HTML.

In my View:

foreach($users as $user):
    // Too much PHP logic in my HTML view
    if ($user->role == 'administrator') {
        $user_color = 'red';
    } else if ($user->role == moderator) {
        $user_color = '#00ff00'
    }

    <a style="color: {{ $user_color }}">{{ $user->username }}</a>
endforeach;

So either way, I end up mixing the two together. This is just one example where I need to adjust the HTML depending on some logic or conditions.

MartinZeltin started a new conversation If I Install Many Packages Will It Slow Down My Laravel Project?

I was wondering if I install like 1,000 packages (that I may never even use) will that make my Laravel project bloated and slow down the performance or do libraries get loaded only when I actually use them and call them? Do all the packages get auto loaded into the memory every time the app starts?

14 Nov
6 days ago

MartinZeltin started a new conversation How Could I Filter A Collection With Multiple Conditions?

I have a collection that looks like this

 [1] => 
        (
            [username] => Sarah
            [id] => 3
        )

    [2] => 
        (
            [username] => John
            [roleid] => 4
        )

    [3] => 
        (
            [username] => Bob
            [roleid] => 5
        )

And I would like remove all the items where the username key is Sarah or John so that only Bob item is left like this

 [3] => 
        (
            [username] => Bob
            [roleid] => 4
        )

I am writing several filters to do this job, but could I join it in one?

$data->employees = $data->employees->filter(function($item) {
      return $item->username!= 'Sarah';
});

$data->employees = $data->employees->filter(function($item) {
      return $item->username!= 'John';
});

for some reason this did not work return $item->username!= 'Sarah'; || return $item->username!= 'John';

12 Nov
1 week ago

MartinZeltin started a new conversation How Could I Not Have HTML Code In My PHP Logic When Working With Templates?

I am generating a PDF file from HTML. I have most of my HTML structure in a separate file called invoice.html but the loop to generate table rows is in my PHP logic. Is there a way to not have it in my PHP so I don't mix HTML with PHP together?

invoice.html

<h1>Hi, {client.name}!</h1>
<p>You have {sum} to pay until {due.date}</p>

Here is the summary
<table>
    {table.rows}
</table>

<p>Thanks, {sender.name}<p>
<p>{issue.date}</p>

createPDF.php

$table_rows = '';
foreach ($datas as $data) {
    $table_rows .= '<tr><td>' . $data->details . '</td></tr>';
}

$invoice_html = file_get_contents( 'invoice.html' );

$invoice_html = str_replace('{client.name}', $client_name, $invoice_html);
$invoice_html = str_replace('{table.rows}', $table_rows, $invoice_html);
...

$pdf = DomPDF::loadHTML( $invoice_html );
return $pdf->download( 'invoice.pdf' );
07 Nov
1 week ago

MartinZeltin left a reply on How To Access Files From Blade In My Storage Directory?

Thanks this helped

ln -s /var/www/new_project/storage /var/www/new_project/public/storage

MartinZeltin started a new conversation How To Access Files From Blade In My Storage Directory?

I have a file in my storage directory in /storage/invoices/invoice.pdf and I can't access it from my blade view file.

For example:

<a href="{{ storage_path() . '/invoices/' . $data->invoice_pdf }}">

this generates this url

http://localhost/var/www/new_project/storage/invoices/invoice_07_11_2018_18_59_36.pdf
02 Nov
2 weeks ago

MartinZeltin started a new conversation Selecting A Custom Column - ERROR Column "'custom_column'" Does Not Exist

I am trying to write a query like this:

SELECT id, 'Arnold the Guy' as custom_column FROM inbox LIMIT 3

when I run it in phpmyadmin it works fine and I get this result

id custom_column
1    Arnold the Guy
2    Arnold the Guy
3    Arnold the Guy

But when I try it with Eloquent then I get an error

$result = Inbox::select("id", "'Arnold the Guy' as custom_column")
->get();

ERROR: SQLSTATE[42703]: Undefined column: 7 ERROR: column "'Arnold the Guy'" does not exist

MartinZeltin started a new conversation View Composer - Undefined Variable

I have set up a view composer but when I try to print the variable it says undefined variable

app\providers\AppServiceProvider.php

public function boot()
    {
        view()->composer('includes.navigation', function($view) {

            $view->with( 'testvar', 'Hello world!' );

        });
    }

And in my includes/navigation.blade.php

{{ $testvar }}
Undefined variable: testvar (View: /var/www/php7/website/resources/Views/page/includes/navigation.blade.php) (View: /var/www/php7/website/resources/Views/page/includes/navigation.blade.php)
01 Nov
2 weeks ago

MartinZeltin started a new conversation Reading .ods Files With FastExcel - "the File Must Contain At Least One Sheet"

I have successfully imported a .xlsx file with FastExcel library, however it is giving me and error if I try to read an .ods file.

Although it should be supported, am I missing some parameters or configuration? https://learninglaravel.net/import-big-xlsx-csv-and-ods-files-with-laravel-fast-excel

if ($extension == "xlsx" || $extension == "ods")
{
    $collection   = (new FastExcel)->import( $filename );
}

If I try to upload .ods it gives me this error

Box \ Spout \ Common \ Exception \ IOException
Could not open /tmp/php934KBw for reading! (The file must contain at least one sheet.)

I am 100% positive it has one sheet. I created the file with LibreOffice Calc.

31 Oct
2 weeks ago

MartinZeltin left a reply on How To Create A Custom Log File?

After some digging around I found that I could add a channel to config/logging.php like this

'customlog' => [
            'driver' => 'single',
            'path' => storage_path('logs/custom.log'),
            'level' => 'info',
],

and write to it like this

Log::channel('customlog')->info('Hello world!!');

MartinZeltin left a reply on How To Create A Custom Log File?

@Ishatanjeeb I already tried it and I'm still getting the same error of undefined method...

MartinZeltin left a reply on How To Create A Custom Log File?

@Ishatanjeeb I still get this error message

Call to undefined method Monolog\Logger::useFiles()

MartinZeltin left a reply on How To Create A Custom Log File?

@Ishatanjeeb I get an error

Call to undefined method Monolog\Logger::useFiles()
public function testing()
{
     Log::useFiles('logs/mycustom.log');
     Log::info('Hello world!');
}

MartinZeltin left a reply on How To Create A Custom Log File?

@Ishatanjeeb I get an error

Call to undefined method Monolog\Logger::useFiles()
public function testing()
{
     Log::useFiles('logs/mycustom.log');
     Log::info('Hello world!');
}

MartinZeltin left a reply on How To Create A Custom Log File?

I get an error

Call to undefined method Monolog\Logger::useFiles()
public function testing()
{
     Log::useFiles('logs/cron.log');
     Log::info('Hello world!');
}

MartinZeltin started a new conversation How To Create A Custom Log File?

I am trying to understand how I could write a log message to a custom log. Right now I am able to write to storage/logs/laravel.log using Log::debug('message')

\Log::debug('Hello world!');

And the message gets added to laravel.log which is great!

But I would also like to add a custom log for example /storage/logs/myownlog.log

\Log::debug('Hello world!');   // logs to laravel.log
\Log::mycustomlog('Hello!'); // logs to myownlog.log

I was reading through the documentation on it but I could not understand what I need to change in /config/logging.php to add a custom log file. Channels, stacks and drivers seem really confusing to me....

29 Oct
3 weeks ago

MartinZeltin started a new conversation How Not To Have To Add Every File To Autoload?

I have 20 files that I have to manually add to composer.json autoload. Is there a way to add the whole folder so it is not a long list of auto loaded files?

    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\": "app/"
        },
        "files": [
           "app/Helpers.php",
           "app/Classes/Sender/upload_file/one_file.php",
           "app/Classes/Sender/upload_file/two_file.php",
           "app/Classes/Sender/upload_file/one2_file.php",
           "app/Classes/Sender/upload_file/one3_file.php",
           "app/Classes/Sender/upload_file/one4_file.php",
           "app/Classes/Sender/upload_file/one_5file.php",
           "app/Classes/Sender/upload_file/one6_file.php",
           "app/Classes/Sender/upload_file/one7_file.php",
           "app/Classes/Sender/upload_file/one8_file.php"
        ]
    },

each file contains a simple function like this..

<?php
    function some_function()
    {

        return "Hello World!";
    }
?>

MartinZeltin left a reply on I'm Seeing Chinese Letters After Converting UTF-16 To UTF-8

Also if I switch to UTF-16LE then the left side is correct but the number are chinese

array:3 [▼
  0 => array:1 [▼
    "Phone number" => "∀⬀㌀㜀㄀ ㈀㘀㄀  㜀㄀㠀∀਀"
  ]
  1 => array:1 [▼
    "Phone number" => "∀⬀㌀㜀㄀ ㈀㔀㄀㔀㄀㤀㄀㤀∀਀"
  ]
  2 => array:1 [▼
    "Phone number" => null
  ]
]

MartinZeltin left a reply on I'm Seeing Chinese Letters After Converting UTF-16 To UTF-8

After running this here is the result that I got...

$text = file_get_contents($file->getPathName());
                    
foreach(mb_list_encodings() as $chr){ 
    echo mb_convert_encoding($text, 'UTF-8', $chr)." : ".$chr."<br>";    
}

https://pastebin.com/dpwsUbBH

MartinZeltin started a new conversation I'm Seeing Chinese Letters After Converting UTF-16 To UTF-8

I have a UTF-16 encoded .CSV file. The field delimiter is a comma (,) and string delimiter is double quotes ("). Changing the encoding outside of PHP is not an option. I need to turn it into an associative array with PHP. But I can't seem to get it to recognize that UTF-16 encoding.

Here is my file contents for numbers.csv:

"Phone number"
"+1 55500718"
"+1 55551919"

I have successfully uploaded the file like this:

$file = $request->file('numbers-file');
$filename = $file->getPathName();

I also have a custom function csvToAssocArray() that turns it into an associative array. I am using mb_convert_encoding to convert UTF-16 to UTF-8.

function csvToAssocArray($filename)
{
    $csvAsArray = array_map(function($data) {
            return str_getcsv(mb_convert_encoding($data, 'UTF-8', 'UTF-16'), ",");
        }, file($filename));

        $header = array_shift($csvAsArray);

        $csv = array();

        foreach ($csvAsArray as $row) {
          $csv[] = array_combine($header, $row);
        }

    return $csv;
}

But the end result of dd(csvToAssocArray($filename)) looks like this:

array:3 [▼
  0 => array:1 [▼
    "∀倀栀漀渀攀 渀甀洀戀攀爀∀" => "+1 55500718"
  ]
  1 => array:1 [▼
    "∀倀栀漀渀攀 渀甀洀戀攀爀∀" => "+1 55551919"
  ]
]

What is happening here?

MartinZeltin started a new conversation How To Display UTF-8 File?

I have a simple .csv file but it is UTF-8 encoded, so the output I get is very strange.

My file contents:

"Phone number"
"+1 5556669999"

This is the output I get

dd( file_get_contents($file->getPathName()) );

"""
"\x00P\x00h\x00o\x00n\x00e\x00 \x00n\x00u\x00m\x00b\x00e\x00r\x00"\x00\n
\x00"\x00+\x001\x00 \x005\x005\x005\x000\x000\x007\x001\x008\x00"\x00\n
\x00"\x00+\x001\x00 \x005\x005\x005\x005\x001\x009\x001\x009\x00"\x00\n
\x00
"""

How could I get the correct output instead of this gibberish?

26 Oct
3 weeks ago

MartinZeltin left a reply on How To Print To Log Logged In User In Every Controller?

@tykus but will I have access to the Auth session in middleware?

MartinZeltin started a new conversation How To Print To Log Logged In User In Every Controller?

I am puttying this code in every single controller before rendering the view but is there a way to do this in all controllers instead of having to repeat myself?

Is it a good idea to put this in the __construct() or that's a bad idea?

// Who is online?
\Log::debug('Online: ' . Auth::user()->fullname);
22 Oct
4 weeks ago

MartinZeltin started a new conversation Vue.js - Change Color For All Buttons Except The Button Clicked

I am trying to switch from jQuery to Vue.js and I am a little bit stuck with this. I have 3 buttons on the page. When I click on a button, I want all the other buttons to change the background color to green and the button that was click - change it's color to black. It was just 2 lines of code with jQuery but I can't figure out how to accomplish it with Vue.js.

Also, at this point, I'd like to just apply raw css background-color property instead of applying a class.

Here is my jQuery code - very simple

<div class="main-content-area">

    <div class="btn">Click me!</div>
    <div class="btn">Click me!</div>
    <div class="btn">Click me!</div>

</div>


const Example = new Vue
({
    el: '.main-content-area',

    methods:
    {
        addEventListeners()
        {
            $( document ).ready(function()
            {
                $( ".btn" ).click(function()
                {
                   // Make all buttons green
                    $(".btn").css( "background-color", "green" );

                    // Make the clicked button black
                    $(this).css( "background-color", "black" );
                });
            });
        }
    },

    mounted: function ()
    {
        this.addEventListeners();
    }
})

With Vue.js - I got only this far...

<div class="main-content-area">

    <div class="btn" @click="changeColor">Click me!</div>
    <div class="btn" @click="changeColor">Click me!</div>
    <div class="btn" @click="changeColor">Click me!</div>

</div>

const Example = new Vue
({
    el: '.main-content-area',

    methods:
    {
        changeColor()
        {
        // Change color to green for all .btn elements
            // and change  color for clicked .btn to black
        }
})
21 Oct
4 weeks ago

MartinZeltin left a reply on Will Node.js Replace PHP & Laravel?

I also think that the beautify of Laravel syntax doesn't even come close to how complicated and difficult the syntax of Node.js is for beginners. So I'm willing to sacrifice some speed in the name of beautiful/elegant code.

MartinZeltin started a new conversation Will Node.js Replace PHP & Laravel?

Let's talk about node.js. A lot of people are saying that node.js is the future. That it will take over PHP which means also Laravel. For those of use who love Laravel and have invested time and resources in learning it - should we be worried? Can node.js really replace PHP on the server? What does that mean for Laravel? What are you thoughts on this?

MartinZeltin started a new conversation How To Find A Database Row That Matches A String?

0 down vote favorite I have a databse table with 100K rows and an array of 100 items. And I need to find if an array item is found in my Users table username row.

My database table Users

| id | username | fullname |
  1      John    John Smith
  2      Elliot  Jim Elliot
  3      Max     Max Richard

My array looks like this

[
   {
      string: 'Hello, this is Elliot from downtown Las Vegas!'
   },

   {
      string: 'Hey how are you?'
   }
]

My idea was to do a foreach loop through every row in my Users table (100k records) and find if it matches in my array, but it is so slow.

$usernames = Users::select('username')->get();

foreach ($MyArray as $Array) {
    foreach ($usernames as $username) {
        if (strpos($Array['string'], $usernames->username) !== false) {
            echo 'found it!';

            break;
        }
    }
}
17 Oct
1 month ago

MartinZeltin left a reply on How To Remove Items From Collection Array?

oh, that's right. Thank you @cmdobueno !

MartinZeltin left a reply on How To Remove Items From Collection Array?

I tried both of these but none of them removed the items where string length was < 5

$sms_collection->filter(function  ($sms) {
   return (bool) strlen($sms['Phone number']) > 5;
});

$sms_collection->filter(function  ($sms) {
   return (bool) strlen($sms['Phone number']) > 5;
});

MartinZeltin left a reply on How To Remove Items From Collection Array?

@tykus the empty items still were not removed from the collection.

MartinZeltin left a reply on How To Remove Items From Collection Array?

@cmdobueno it gave me this message

Error
trim() expects parameter 1 to be string, array given

MartinZeltin left a reply on How To Remove Items From Collection Array?

Could you provide an example on how I could remove an item if it is empty?

MartinZeltin started a new conversation How To Remove Items From Collection Array?

I have this collection where some values are empty and I would like to remove those items from my collection array. So for example if "Full name" is null or an empty string then remove that array item (all 3 values). I could do a foreach loop and check for empty values but how could I do it on a collection?

$sms_collection = (new FastExcel)->import( $file->getPathName() );
return $sms_collection;
[
 {
  "Phone number": 123456789,
  "Full name": "John Smith",
  "Salary": 10
 },
 {
  "Phone number": "",
  "Full name": null,
  "Salary": null
 },
 {
  "Phone number": 987654321,
  "Full name": "Adams Sanders",
  "Salary": 500
 }
]
15 Oct
1 month ago

MartinZeltin left a reply on $with Inside Two Models Causing A Strange Loop

I know I could just do $user->employee but sometimes it's nice to have it joined every time I call for User.

MartinZeltin started a new conversation $with Inside Two Models Causing A Strange Loop

I have 2 tables "users" and "employees". I have set up a relationship for both tables both ways. But I also have $with defined for both models which seems to be causing a strange loop that runs for a while before crashing with no errors - just a blank screen.

users table

| id | username | password |
| 1  |  Martin  | c98d09dx |
| 2  |   John   | b23d09ee |

employees table

| id | user_id |     fullname     |
| 1  |    1    |   Martin Zeltin  |
| 2  |    2    |     John Doe     |

My Users Model

    class Users extends Authenticatable
    {
        use Notifiable;
       
        protected $table = 'users';
        protected $with = ['employee'];

        public function employee()
        {
            return $this->hasOne('App\Models\Employees', 'user_id'); 
        }
    }

My Employees Model

    class Employees extends Model
    {
        protected $table = 'employees';
        protected $with = ['user'];

        public function user()
        {
            return $this->belongsTo('App\Models\Users', 'user_id');
        }
    }

It seems to get stuck in this $user->employee->user->employee... loop because of the $with in both models. Is there a way round it?

Basically I wanted so that whenever you call the Users model you also get the associated Employees entries and vice versa.

MartinZeltin left a reply on How To Set Up A BelongsTo Relationship Properly?

Still the same result - after 5 seconds of loading shows a blank page

MartinZeltin left a reply on How To Set Up A BelongsTo Relationship Properly?

Still showing a blank page after 10 seconds of loading...

MartinZeltin left a reply on How To Set Up A BelongsTo Relationship Properly?

Also, it works fine if I remove protected $with = ['employee']; from Users model

MartinZeltin left a reply on How To Set Up A BelongsTo Relationship Properly?

   $user = \App\Models\Users::where('id', 23)->first();
   dd($user);

It took 3 seconds to load and there was no output at all - just a blank white page.

MartinZeltin left a reply on How To Set Up A BelongsTo Relationship Properly?

    class Users extends Authenticatable
    {
        use Notifiable;
       
        protected $table = 'users';
        public $timestamps = false;
        protected $with = ['employee'];

        public function employee()
        {
            return $this->hasOne('App\Models\Employees', 'user_id');
        }
    }

if I use $with it breaks...

MartinZeltin left a reply on How To Set Up A BelongsTo Relationship Properly?

Yes it does work.

But if I put this in my Users model it's not returning anything...

protected $with = ['employee'];

MartinZeltin left a reply on How To Set Up A BelongsTo Relationship Properly?

What do you mean?

public function testing()
{
       $employee = \App\Models\Employees::where('id', 12)->get();
 }
    class Employees extends Model
    {
        protected $table = 'employees';

        public function user()
    {
            return $this->belongsTo('App\Models\Users');
    }
    }

MartinZeltin left a reply on How To Set Up A BelongsTo Relationship Properly?

Then I get

Property [user] does not exist on this collection instance.