Thyrosis

Thyrosis

Member Since 1 Year Ago

Eindhoven

Experience Points 57,380
Experience Level 12

2,620 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 364
Lessons
Completed
Best Reply Awards 28
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

19 Feb
3 days ago

Thyrosis left a reply on Custom Service Provider Gives Purify Errors In PHPUnit Test

Okay, I've finally given up. Even with @nakov s help, I've come to the conclusion that sadly, there is no fixing this for me.

So, instead of having the target stored in the database inside the anchors, I've extracted it to some JavaScript code.

    <script type="text/javascript">
            var anchors = document.getElementsByTagName('a');
            for (var i in anchors) {
                if (anchors[i].href && anchors[i].href.indexOf('{{ config('app.url') }}') == -1) {
                    anchors[i].onclick = function () { return !window.open(this); };
                }
            }
        </script>

This little piece of code just loops through all anchors in the page and then checks the href. If the current app.url is not part of the href, it's an external link and it opens in a new window. If the current app.url is in fact in the href, it's a local link and so it just opens in the same window.

No, it's not foolproof and it takes away freedom from the user, but it 'works'. Still, if someone stumbles across this thread and knows the answer, shout away.

15 Feb
1 week ago

Thyrosis left a reply on Custom Service Provider Gives Purify Errors In PHPUnit Test

Hi @nakov, that's exactly what my code does already.

I have an attribute on Post:

    public function getBodyAttribute($body)
    {
        return \Purify::clean($body);
    }

The clean-method can't be called without an argument. Upping the definition_rev number declared at the top of the PurifySetupProvider doesn't work either.

Thank you so much for your help so far! If you have any great ideas left, I'm more than happy to hear them.

12 Feb
1 week ago

Thyrosis left a reply on Custom Service Provider Gives Purify Errors In PHPUnit Test

TLDR; Am I right in assuming code in an if-statement will never be executed if the statement itself defaults to null?

Well, the extra $config->set doesn't work either @nakov , but you did give me an idea.

I've been backtracking the error, adding a dd($def) to the setupDefinitions method from the PurifySetupProvider. It didn't get called in the tests. But, it didn't get called in the browser either. That leads me to believe that my statement "it works in browser" is actually incorrect. It doesn't work, it just fails silently and doesn't purify anything any more.

That led me to debug through Steve Baumans code and the Ezyang HTMLPurifier. Running through the methods, I think there might be a bug somewhere.

    if ($def = $config->maybeGetRawHTMLDefinition()) {
        $this->setupDefinitions($def);
    }
    public function maybeGetRawHTMLDefinition()
    {
        return $this->getDefinition('HTML', true, true);
    }
    public function getDefinition($type, $raw = false, $optimized = false)
    {
[...]
            if ($optimized) {
                // This code path only gets run once; once we put
                // something in $definitions (which is guaranteed by the
                // trailing code), we always short-circuit above.
                $def = $cache->get($this);
                if ($def) {
                    // save the full definition for later, but don't
                    // return it yet
                    $this->definitions[$type] = $def;
                    return null;
                }
            }

So, $optimized is true. $def is retrieved from the cache and set to $this->definitions[$type]. Return value: null.

Returning back to the start:

    if (null) {
        $this->setupDefinitions($def);
    }

Am I right in assuming $this->setupDefinitions($def) will never be executed because $def always defaults to null?

11 Feb
1 week ago

Thyrosis left a reply on Custom Service Provider Gives Purify Errors In PHPUnit Test

Thanks @nakov . I tried this as well. Same result: accessing the application via browser works fine and allows the target attribute in anchors.

Test results still fail.

Thyrosis left a reply on Custom Service Provider Gives Purify Errors In PHPUnit Test

Hi @Nakov, thanks for your reply.

As said, accessing the application via the browser yields the correct results. The config is fine:

        'HTML.Allowed' => 'a[href|target|title|rel],b,big,blockquote,br,code,del,div,em,h1,h2,h3,h4,h5,h6,hr,i,img[style|width|height|alt|src],li,ol,p[style],pre,small,span[style],strong,sub,sup,table[style|summary],td[abbr],th[abbr],tr,ul,*[style]',

This is the PurifySetupProvider:

<?php

namespace App\Providers;

use HTMLPurifier_HTMLDefinition;
use Stevebauman\Purify\Facades\Purify;
use Illuminate\Support\ServiceProvider;

class PurifySetupProvider extends ServiceProvider
{
    const DEFINITION_ID = 'tinymce-editor';
    const DEFINITION_REV = 1;

    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        /** @var \HTMLPurifier $purifier */
        $purifier = Purify::getPurifier();

        /** @var \HTMLPurifier_Config $config */
        $config = $purifier->config;

        $config->set('HTML.DefinitionID', static::DEFINITION_ID);
        $config->set('HTML.DefinitionRev', static::DEFINITION_REV);

        if ($def = $config->maybeGetRawHTMLDefinition()) {
            $this->setupDefinitions($def);
        }

        $purifier->config = $config;
    }

    protected function setupDefinitions(HTMLPurifier_HTMLDefinition $def)
    {
        $def->addAttribute('a', 'target', 'Text');
    }
}

Which is then loaded in config/app.php

/*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        App\Providers\PurifySetupProvider::class,
    ],

As said, it works fine using the browser, just not in the tests. Is there any caching going on maybe? For testing? Is there a PHPUnit cache I need to clear?

Thyrosis started a new conversation Custom Service Provider Gives Purify Errors In PHPUnit Test

Hi guys,

This is a weird one. I'm trying to add some extra allowable HTML elements to Steve Baumans' Purify.

It takes a custom ServiceProvider, seeing as the element (anchor target) isn't 'officially' allowed.

Now, don't get me wrong, it works. Perfectly. When showing database-content, the anchor target attribute is shown.

But when I run my tests, half of them fail with the following error:

ErrorException: Attribute 'target' in element 'a' not supported (for information on implementing this, see the support forums)

So what's happening here? Why does the custom service provider work when the application is run 'normally' but not when it's being tested?

And of course, what can I do to get it to work? I don't like these kind of results...

....EEEEEE.EEEEE.EEEFEFEE..........EEEEEE.F... 46 / 46 (100%)

Thanks in advance!

19 Nov
3 months ago

Thyrosis left a reply on Why Does Laracasts.com Use JQuery Over VueJS

has discussed his decision to use jQuery over VueJS for the new Laracasts?

What makes you think he choose jQuery over VueJS? As far as I'm aware, he's using both libraries simultaneously. Yes, jQuery is included as a separate JS file, but I think the Vue-library is included in 'all.js'.

Thyrosis left a reply on How To Regex Validate Telephone Number?

If the only limitation is 10 numbers starting with a 0, you could try this:

0([0-9]{9})

This regex will check on a leading 0, followed by 9 numbers only.

Check the regexr here: https://regexr.com/43c6t

29 Oct
3 months ago

Thyrosis left a reply on How To Remove The Index Of Public_html Cpanel Laravel 5

You're not doing anything wrong. Everything is working as it's intended.

Whenever you browse to your URL, the server will direct that request to the public_html. It'll search for an index file (php, html, htm) or, if not found, will return a directory listing.

In this case, your public_html doesn't have an index file, but a folder called 'laravel'. The server returning a directory listing is therefor correct.

Laravel is set up properly, as you do get the laravel site when going to the URL/laravel. Well done, that's actually a very tricky part when setting things up outside the ordinary way.

How do you get rid of the /laravel in the URL? Well, that depends. If you were only going to run one application from this server, I would say 'Move the content of the laravel folder to the public_html directly', exactly what s4muel already suggested.

You should still reconsider this option, as you claim there will be one project on a domain, the other on a subdomain.

Now, the domain names content should just be in the public_html itself, not in a folder. The subdomains content will be in a subfolder inside the public_html, so /home/username/public_html/subdomain/.

If you insist on keeping the main site's content in the /laravel subfolder, the only way around it is using a .htaccess redirect from the public_html to the subfolder. Something like this should do the trick:

RewriteEngine On 
Options +FollowSymlinks 
RewriteBase / 
RewriteCond %{HTTP_HOST} domain.ext
RewriteCond %{REQUEST_URI} !^/laravel/? 
RewriteRule ^(.*)$ laravel/ [L] 

Obviously replace domain.ext by your actual domain.

Hope this helps :)

10 Oct
4 months ago

Thyrosis left a reply on Laravel Site Is Not Working After Hosting It.

I'm not really sure, never had this issue. What I do notice is that in your original post, the error points to /var/www/html/vesMain/storage/logs/laravel.log while in your reply, the error is C:\laragon\www\vesFinal\storage\logs.

This seems to be virtually impossible, as the original error indicates a Linux server, while the next one points to a Windows environment.

It'll be a combination of some settings and caching. Apart from that, I'm unable to direct you any further I'm afraid. Maybe this thread on StackOverflow gives you a lead:

https://stackoverflow.com/questions/51041196/there-is-no-existing-directory-at-storage-logs-and-its-not-buildable-permissio/51065725

Thyrosis left a reply on Stucked Again With Stevebauman/purify Package? Its Blocking Youtube / Iframe Custome Video Tags From Ckeditor (oembed)

@nhayder did you ever find a solution to your question? I'm running into the same error but with a different element.

Element 's' is not supported (for information on implementing this, see the support forums)

The only way I can seem to find around it is to 'hack' the actual EZYang library, but for obvious reasons I want to stay clear of this.

07 Oct
4 months ago

Thyrosis left a reply on Laravel Site Is Not Working After Hosting It.

This really depends on your server set up. Permission 644 in a regular Apache/PHP set up is usually not enough to allow the webserver to write to files.

Try to change the permission to 777 and see what happens.

27 Sep
4 months ago

Thyrosis left a reply on How To Store Row Id In Laravvel

@irankhosravi, this is going to be a slightly longer post, but I think that by the end of it you'll know where the mistake lies.

Even though you're retrieving all schools in the CREATE route, you don't transfer that list to the STORE route.

The information the CREATE method retrieves is only available in that specific request. $school is a list of all Schools you have and those are passed through to the blade view as a variable.

So in your form (the view Admin.requisitions.create) you can do something with those schools. At the moment, you don't seem to do anything with it. I'm expecting some kind of dropdown or checkboxes populated by a @foreach, but it's not visible in the code you posted so far. Maybe you have it elsewhere, then it's fine.

Now, as soon as you hit that Send-button, a NEW request is made to the STORE route. You declare it like this:

public function store(Request $request, School $school)

Yet, the form calls it like this:

            <form action="{{ route('requisitions.store')}}" method="post">

That means either you need to pass your school through with the route, or you can't pick it up from the URL.

As I said, I'm guessing with School::all() you are retrieving a list of schools of which one or more can be selected or ticked in the form. That means it should be a variable being sent through with the form.

Which means the form could look like this:

<form action="{{ route('requisitions.store')}}" method="post">
                {{ csrf_field() }}
                <div class="radio">
                    <label for="school">School</label>
            // Create a dropdown list of all schools
            <select id="school" name="school">
            @foreach ($schools as $school)
                <option value="{{ $school->id }}" />
            @endforeach
            </select>

            // The rest of your form
                    <br>
                    <button type="submit" class="btn-warning btn">Send</button>
                </div>
            </form>

And the Store controller method like this:

public function store(Request $request)
{
    $school_id = request()->get('school');

    $requisition = new Requisition();
    $requisition->user_id = auth()->user()->id;
    $requisition->school_id = $school_id;
    $requisition->type = $request->application;
    $requisition->status = 0;
    $requisition->approved = 0;
    $requisition->save();
    return redirect(route('requisitions.show'));
}

There you go, all set!

Mind you, you'll need to pass a $schools variable through on your create-method, not $school. Notice the extra 's' at the end to signal a plural.

Hope that helps!

16 Sep
5 months ago

Thyrosis left a reply on I'm Using Facebook Url In Href But It Appends My Site Domain With This Url

If you don't specify a specific protocol, either php, the webserver or your browser will always prepend the url with the current domain. So

Url: Facebook.com Link to: Http(s)://currentdomain.ext/facebook.com

Url: Https://facebook.com Link to: Https://facebook.com

In other words: If you're linking to external sources, always prepend with http or https.

Also, your error is about retrieving an id from something which is not an object and is totally unrelated to how your profile url is linked.

15 Sep
5 months ago

Thyrosis left a reply on Help With Git

Not necessarily install, more like reinstall.

So basically, the workflow is:

  1. Clone github locally.
  2. Create branch locally for the bugfix or feature you're working on
  3. Push branch to github
  4. Merge branch into master
  5. Pull master branch to live server
  6. On live, do a composer and npm install, run migrations and clear caches where necessary.

Regarding step 2, this can also include an upgrade to a new laravel version or just general update. So maybe the only thing you do is a 'composer update ' which, for git, will only change one single file: composer.lock.

But, based on that file, your live server will install the correct packages in step 6. Take care not to run 'composer update' on live (always do 'composer install'), as the update will search for any new version and creating its own composer.lock file in the process. Hello merge conflict!

10 Sep
5 months ago

Thyrosis left a reply on Memory Usage

Simple math, right?

50000 * 12 = 600000mb, so about 600gb.

The again, how likely is it that 50000 users log in at exactly the same moment?

06 Sep
5 months ago

Thyrosis left a reply on @method Update And To Delete

You can't.

A form only has one action and therefor one method. If you need to update something, use the patch method. If you need to delete it, use the delete method.

If you need a delete button on the same page as your edit form, use two separate forms, each with their own action and method.

05 Sep
5 months ago

Thyrosis left a reply on Auto Save As Draft Like Wordpress

@journey4tech dont have a tutorial or code handy, but this is the documentation page: https://www.tiny.cloud/docs/plugins/autosave/

02 Sep
5 months ago

Thyrosis left a reply on Auto Save As Draft Like Wordpress

I don't know about CKE, but I know Ti yMCE

29 Aug
5 months ago

Thyrosis left a reply on Linking Storage Folder Without Using Artisan

If you don't have SSH access to your server, you can't create a symlink from the public directory to the storage folder. At least, not with any Control Panel i know of.

You could ask your hosting provided, possibly they can create it for you?

Alternatively, as jlrdw suggested, store your assets in the public directory.

27 Aug
5 months ago

Thyrosis left a reply on Problem With Vhosts

@Viernes sorry for the late reply, unfortunately I can't open the notifications thing in FireFox so didn't catch your reply and tag.

The answer is: Yes to all.

If you have a server in your network running a LAMP stack, it will get an IP address from the switch, router or whatever it is using to connect to the network. Make this IP static, so it will never change.

Then, just have your resolving for all PCs connect to that server for a given hostname. For instance for a single PC, the local host file would have this line:

intranet.local 127.0.1.57

Of course, assuming 127.0.1.57 is the static IP you've given it. And of course, you wouldn't set this individually for each PC, I'm sure there's a way to do this for all PCs simultaneously and centrally.

You could even use your company's own domain name to point everyone to it, by setting an A record to that IP for a subdomain.

intranet.yourcompany.com A 127.0.1.57

On the CentOS server you don't use Laragon or Xampp, you just install a LAMP stack. Ubuntu has a ready made package installer for that, so I'm guessing CentOS has too. If not, DigitalOcean has a wide range of very decent tutorials, like this one: https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-centos-7

As long as the server is connected to the network properly and accessible for all 150 PCs through the given IP, the whole company can use your application.

26 Aug
5 months ago

Thyrosis left a reply on View Auth.login Not Found And Failed To Open Stream: No Such File Or Directory Error

These are two u related issues, most likely .

The view file missing indicates an incomplete upload. Check your server to see if the file is actually there.

The file_put_contents error is a file permission issue. Check to see if your storage/framework/sessions directory is writable for your application. Contact 000webhost if you're not sure how to, as each server provider has a different setup where different permissions are required.

24 Aug
5 months ago

Thyrosis left a reply on For Loop The Variable

Also, keep in mind that you'll never get to number 2.

DD dies and dumps, so code execution will stop in the first loop, while $i is still 1.

Thyrosis left a reply on Composer Create-project --prefer-dist Laravel/laravel (Project_Name) Taking Too Long

While both answers offer a suitable roundabout solution, neither of then solves the actual problem.

I've never had this issue, but first thing that comes to mind is an unstable internet connection. The loading needs to access the remote repos for all dependencies.

Unless you've installed a laravel project before, the projects are loaded locally and maybe there is a permission or disk space error.

Thyrosis left a reply on Sample CRUD System With Login

Or just right here on Laracasts :

https://laracasts.com/series/laravel-from-scratch-2017

And slightly less simple, but an awesome series with a lot of information either way:

https://laracasts.com/series/lets-build-a-forum-with-laravel

18 Aug
6 months ago

Thyrosis left a reply on MethodnotAllowed Exception After Login

It probably redirects you back to the intended route, as seen in the sendLoginResponse method on the AuthenticatesUsers trait:

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }

The intended method pulls the url.intended value from the session:

    public function intended($default = '/', $status = 302, $headers = [], $secure = null)
    {
        $path = $this->session->pull('url.intended', $default);

        return $this->to($path, $status, $headers, $secure);
    }

So the easiest way is to overload the showLoginForm method on your LoginController and clear the url.intended variable from the session.

So add this to your LoginController:

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        session()->forget('url.intended');

        return view('core.admin.auth.login');
    }

This will bring the showLoginForm method from the AuthenticatesUsers trait in your vendor directory to the actual LoginController in app/Http/Controllers/Auth and you can modify it to tailor your needs. It will also be included in your versioning like GIT or SVN, as opposed to modifications in your vendor directory being lost.

Hope that helps!

P.S. Obviously you could also just hide the comment form to guests, so you won't get to the situation of being able to post a comment without being logged in.

17 Aug
6 months ago

Thyrosis left a reply on How Can I Listen To The Db In Real Time?

Simplest way is to enable query logging in the database software and then just read that file.

For instance, for MySQL there is the General Query Log (https://dev.mysql.com/doc/refman/8.0/en/query-log.html). All actions and queries are written to a file. Using command line, you can then use 'tail -f logfile' to see all queries run across your screen in real time.

Maybe you could also use a package like https://github.com/samuele-artuso/mysql-query-monitor? I don't know exactly what it does, I only found it while Googling for "mysql watch query real time".

13 Aug
6 months ago

Thyrosis left a reply on Problem With Vhosts

@Viernes Laragon is meant for local development, just as packages like Xampp and Wamp are. At least, that's what I'm reading from your posts so far: you have a Windows PC on which you are developing your application and want that to be accessible from your company's PCs?

If you are hosting an application for your company to use internally on 150 PCs, you should really set up a dedicated server. Something simple like Ubuntu or CentOS, make it available for your local company's network only and host the application on there.

12 Aug
6 months ago

Thyrosis left a reply on Learning To Plan Ahead And Structure My Projects

I know the feeling.

What I've recently started doing (spurred on by my wife's passion for bullet journals) is just to start drawing. Old fashioned pencil and paper drawing.

So I have an idea. How does the index page look? A posts show page? A user profile? Not for the design or layout, but for the elements that need to be on there.

judging from my drawing, a post needs a body and a title. Also a slug, because the url for this drawing is project.dev/my_first_post

Something like that. And from those drawings I'll decide on the models and fields. Ask for a second opinion, use the eraser, draw some more.

And then I fire up Artisan and start cranking out models and migrations and just see where I end up.

But yes, a 'project management' course by Jeffrey would be very interesting.

11 Aug
6 months ago

Thyrosis left a reply on Routing Issue

@Mick79 You're welcome.

Topvillas has a point thought. Is there any reason you're using /{username} as the user-profile route? Why not /profile/{username} or /user/{username}?

It really depends on your application of course, but say you have a forum or blog. Then you'll end up like this:

Route::get('login', '[email protected]');
Route::get('dashboard', '[email protected]');

Route::resource('posts', 'PostController');
Route::resource('threads', 'ThreadController');
Route::resource('users', 'UserController');

Route::get('{username}', '[email protected]');

The defining of the static 'home-routes' (the ones without an extra prefix, so login or dashboard) works fine. Then there are the posts, threads and users route groups, which include:

Route::get('users/{user}', '[email protected]')->name('user.show');

And then at the end your creating another route to [email protected], which is basically a duplicate.

It might be worth keeping those home-routes reserved for actual pages or for the main purpose of the application. Like, if you have a forum, it makes more sense to have the wildcard route for thread-slugs rather than usernames. Because threads are the primary purpose of a forum, not usernames. For blogs, you can use post-slugs as wildcard, because posts are the primary purpose of a forum, not usernames.

Of course, if you're running a dating site, usernames are the primary purpose ;)

Anyway, have a think about it. Technically it works, but will it practically work out too?

Thyrosis left a reply on Routing Issue

Just put the wildcard route at the end of the routes file.

That way, /login and /dashboard will match their routes. Only if a request hasn't matched a defined route, it will think the url is a post and fall into the /{username} route.

09 Aug
6 months ago

Thyrosis left a reply on File Validation Before Upload

  1. You can probably catch this one in the php.ini on server configuration level. Laravel validation only kicks in after the request hits the validation layer, which is after the browser completely (so including the 2GB file) sent the request.

  2. Wait, what? Instead of implementing a spinner, I'd have a look why simple tasks like you mention take 30 seconds in the first place. I can't imagine you getting any kind of userbase with performance like that.

Thyrosis left a reply on How Do I Make The Browser Ask What A User Wants To Name A Downloaded File - With A Suggestion

As soon as the file is actually offered to the browser for download, it's up to the browser's setting how to handle that. Either the user gets a pop up to specify a name and location or the browser will use the defaults.

The only way to reliably solve this is to catch the desired name server side. So

Route::get('download/create', [email protected]);

In the view for this route, the user only sees a simple form: an input field to decide on the name and a download button. Upon submitting:

Route::post('download/store', [email protected]);

This store route will use the code you've got now, but with a slight difference:

// Use Request validation first of course!
$randomFilePath = public_path().'/temp/'.request('filename').".csv"; 

This way, the user decides on the name before hitting the download button, therefore the downloadable name will always be what the user decided on.

07 Aug
6 months ago

Thyrosis left a reply on Developing Without A Local VM.

+1 for the local development server. That is the only (easy) way with which you can keep the development environment identical to the live environment.

Failing that, packages like wamp and xampp aren't too bad to work with. Depending on your own OS it might take a bit of effort to set up, but I personally have developed quite a few projects that way.

05 Aug
6 months ago

Thyrosis left a reply on Buy A File In Laravel

php artisan buy:file SomeFile --currency dollars

Thyrosis left a reply on Missing HTTP Security Headers

Have a look at Scott Helme's blogpost about the different headers. He providers code samples for you to include in whatever webserver you use (Apache, NginX or IIS).

https://scotthelme.co.uk/hardening-your-http-response-headers

You could also have them included in an .htaccess file, the code isn't that much different from the ones in Scott Helme's post.

I personally use the httpd.conf (Apache) for the four headers you mentioned and only use .htaccess for the Content Security Policy as that is the only header which is site-specific.

Thyrosis left a reply on Undefined Index: Title What Is The Problem With This Code And Where I Miss The Title

Nope I am holding the value of the title as an array...

No you're not.

public function store(Request $request)

{

$data = $request->only('title','body');
// $data is now an array with two elements: 'title' and 'body'

$data = str_slug($data['title']);
// $data is now no longer an array, but only the sluggified title.

$data = Auth::user()->id;
// $data is now the authenticated user's ID.

// So what you're doing here is Post::create(Auth::user()->id)
$post = Post::create($data);

The error is correct, you're missing the title in the $data variable passed through to the Post::create call.

Thyrosis left a reply on Mail Or Notification

Also, notifications are, by default, meant to be tied to a user. So it depends on your application.

If you intend to send emails to non-users, use the make:mail. If you only use mail to notify users, you could use notifications.

For instance, I have a blog where the admin user gets a notification when a new comment is posted. I recently realised that I needed to have commenters be alerted when someone replied to their comment. That is now done using a mail, because commenters don't have user accounts.

03 Aug
6 months ago

Thyrosis left a reply on How To Calculate Total Likes Of Users All Post

@Dev0ps in that case you probably didn't quite understand what I meant.

$posts = Post::with('likes')->whereUserId(Auth::id())->get();

This will get you all Auth::User() posts, as you mentioned.

Now, looping over these posts and adding the $posts->likes->count() to a counter, will get you total likes received by all Auth::user() posts.

$likes = Post::with('likes')->whereUserId(Auth::id())->get()->sum(function($post) {
    return $post->likes->count();
}    

So this does exactly what your original code did, but in a more Laravel oriented way. In plain English:

Select all Post and all their likes from user Auth::id() and add (sum) all the posts likes count together.

Again, the raw query already provided will be much faster to get you what you need. But, I was just thinking that your code - even though it works - could benefit from an improvement.

As Tray2 said, your code will loop over each post and then hit the database to retrieve the likes. If you include the likes in the original query which collects all posts (using the relationship and 'with'), you only hit the database twice and you can still use 'regular' code instead of a raw DB query.

02 Aug
6 months ago

Thyrosis left a reply on How To Calculate Total Likes Of Users All Post

Of course, Tray2's raw query is what you're looking here.

But just wondering why you're using a static PostLike model, here:

    $post= PostLike::wherePostId($post->id)->count();

When you could also do this with the relationship between Post and Likes:

    $post= $post->likes->count();

Of course, this is assuming you've set the relationship so that $post->likes returns the likes for a $post.

Also, if you did set your relationships, then

$posts = Post::with('likes')->whereUserId(Auth::id())->get()

would get you all of the currently logged in user's posts, including the related likes. In that case, looping over them using the relationship does not hit the database on every iteration.

Thyrosis left a reply on Am Working On Reply To Comments To My Posts In My Blog. But Its Not Woking Out

Afaik, the global route() function only accepts two parameters, the first one being the URL to redirect to and the second one any parameters that may be defined in the route.

The second parameter may be a single variable or an array. So if you actually need two parameters to the route, the redirect would look like this:

    return redirect(route('posts.show',['comment_id' => $comment->id, 'post_id' => $comment->post->id))->with('success', 'Reply submitted');

I'm assuming there's a relationship between comment and post. If not, you could also replace $comment->post->id with $comment->post_id so that the ID is loaded from the comment object directly, instead of from the related post object.

Thyrosis left a reply on Am Working On Reply To Comments To My Posts In My Blog. But Its Not Woking Out

Last line in your PostController:reply method

        return redirect(route('posts.show',$comment->id,$post->id))->with('success', 'Reply submitted');

You redirect to a route with a $post->id variable, but $post doesn't seem to be declared anywhere.

20 Jul
7 months ago

Thyrosis left a reply on Blade Directives - Why?

I suppose it depends on what the actual logic and purpose of your directive would be.

I personally use them to extend easy authorisation checks, like @ admin or @ moderator as supplements to the out of the box @ guest and @ auth.

If you are looking to replace @ include, I think your purpose might not be something to use custom blade directives for or you need to rethink the way you structure them.

18 Jul
7 months ago

Thyrosis left a reply on Cannot Migrate Database

This is just a regular access denied message. You most likely don't have a user 'homestead' on the mysql server.

In that case, you need to change the .env file with the correct user credentials to log in to the mysql database you need. Log in to phpmyadmin as root and create a database with user, set those in your .env and your good to go.

15 Jul
7 months ago

Thyrosis left a reply on Display Exception Message In A Secure And Proper Way

@scala if your showing output to the end user, your application is in production mode and app_debug should be false by definition.

Live or production environments should never have app_debug to true imho, for exactly the reason you are now asking for another way around it.

13 Jul
7 months ago

Thyrosis left a reply on Queue:work Not Responding

Hmm. And in your database table, the queued jobs show up in your jobs table?

As you work your queues, do the attempts in the database table go up? Are they available immediately or are they set for future sending? Showing a few lines of your jobs table might help.

Thyrosis left a reply on Queue:work Not Responding

What are your env and config like?

Also, do you wait long enough with pressing ctrl c to let the queue work?

12 Jul
7 months ago

Thyrosis left a reply on Accessing Object Properties...

Cannot access private property

This usually means there is a public getLatitude() method or something to fetch the contents of a private variable.

Or a result() method which returns whatever you need.

I just quickly skimmed through the git repo, but my phone is being a pain so I cant really look properly for the thing you might need.

06 Jul
7 months ago

Thyrosis left a reply on Hi Everyone, I Am Really New Laravel Learner. I Have Some Error That Want To All Of You. I Got The Error As Below When I Ran "phpunit". Thank In Advance..! :)

Are you using databaseMigrations or refreshDatabase in your tests?

For instance, in the phpunit.xml file, this is my configuration for php:

        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="MAIL_DRIVER" value="array"/>
        <env name="DB_CONNECTION" value="sqlite"/>
        <env name="DB_DATABASE" value=":memory:"/>
    </php>

Notice the DB_CONNECTION and DB_DATABASE pointing to a SQLite database in memory.

Then, in the test itself:

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    /**
     * @test
     */
    public function aPostCanBeRead()
    {
    //test
    }
}

Notice the use of Illuminate\Foundation\Testing\RefreshDatabase to have PHPUnit run migrations at run time.

Hope that helps!