memele

memele

Member Since 10 Months Ago

Experience Points 9,510
Experience Level 2

490 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 87
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

14 Jul
1 month ago

memele started a new conversation How To Properly Check For Duplicate Files In Storage?

I have a project where I want to crawl other websites for files. In this crawler I want to check if an identical file is already saved in my storage. I have this code at the moment, but it is not working properly. If a file doesn't exist, a new one with an id is not being created.

Also, for some reason, not all files are deleted from the /zip directory. Unlink() works on some files but not all of them, why is that?

$zip = new ZipArchive;
$res = $zip->open('storage/app/public/zip/files.zip');

$dir = "storage/app/public/zip/";

if ($res === TRUE) {
   $zip->extractTo($dir);
   $zip->close();

    foreach (glob($dir . '*') as $file) {

           if (pathinfo($file, PATHINFO_EXTENSION) === 'txt') {

               $fileNameWithoutExt = basename($file, '.txt');

               $files= MyFile::where('url', $filename . '.txt')->get();

                     if ($files->count() > 0) {

                            $id = $files->count();
                            $id = $id + 1;

                            foreach ($files as $file) {
                                $originalFile = 'storage/app/public/files/' . $file->url;

                                if (md5_file($dir . basename($file)) === md5_file($originalFile )) {
                                    echo "file " . basename($file) . " already exists \n";
                                    return;
                                }

                                $filename= $filename. '-' . $id;

                           }

                        }


                        // If file not found in db, create one
                        Myfile::create([
                            ....
                        ]);

                        copy($dir . basename($file), 'storage/app/public/files/' . $filename. '.txt');
                        echo "FILE CREATED \n";


                    // Delete any subdirectories created
                    // Delete all files from the /zip folder
                    if (is_dir($file)) {
                        File::deleteDirectory('./' . $file);
                    } else {
                        unlink($file);
                    }

                    }

Any thoughts on how to improve this? Thanks.

01 Jul
1 month ago

memele started a new conversation Remove Unnecessary Text From String

I am learning about web scraping and I have created a website that lists movies and tv shows from the omdb API. I want to copy subtitles from other websites to mine. A lot of websites save subtitles with names that have a lot of additional info like 1080p.BluRay.x264.DTS-FGT but I only need the movie/tv show title so I can look it up in my database and then add the subtitle file to it. How do I get rid of all the extra info in the title? I was thinking of creating an array with most common acronyms like ['720p', '1080p', 'webrip', 'x264', 'en', 'web', 'dl', 'hevc', 'bluray', 'hd', 'aac', 'hdcam'] etc, but this isn't gonna work 100%. Is there a better way to do this?

24 May
2 months ago

memele left a reply on Route::current()->parameter() In AppServiceProvider

@JOHNBRAUN - I was expecting to get the slug like you would with Route::current()->parameter('forum'), I overlooked the other options. Thanks, your solution works perfectly :)

memele left a reply on Route::current()->parameter() In AppServiceProvider

@CRNKOVIC - What would be the best way to return the $forum variable from the middleware? There is a StackOwerflow answer that says to do $request->merge(compact('foo')); Is this considered good practice?

memele left a reply on Route::current()->parameter() In AppServiceProvider

@JOHNBRAUN - This also returns null.

dd($this->app->request) returns

+request: ParameterBag {#51 ▼
    #parameters: []
  }
#requestUri: "/login"
#baseUrl: ""

Should baseUrl be empty?

memele started a new conversation Route::current()->parameter() In AppServiceProvider

Creating subdomains has broken most of my application :D I have a forum with subforums (as subdomains) and I want to display the current subdomain in the header (in layouts.app view). I already have a View composer in AppServiceProvider that shares some variables to all views. I also want to share the current subdomain (forum). I can fetch it easily in any controllers like this:

$subdomain = Route::current()->parameter('forum');
$forum = Forum::where('slug', $subdomain)->first();

But it doesn't work in the AppServiceProvider

View::composer('*', function ($view) {
    $subdomain = Route::current()->parameter('forum');
       $forum = Forum::where('slug', $subdomain)->first();

    View::share([
                'forum' => $forum
            ]);
}

dd(Route::current()->parameters()); returns []

What is this not working?

23 May
2 months ago

memele started a new conversation Is It Bad Practice To Use Absolute URL In An Anchor Tag?

I am creating a website with multiple subdomains (forums). On my home view I want to list all discussions from all subdomain forums. I can't use a relative URL because I need to prefix the route with the subdomain. I found a way that works -

<a href="http://{{$discussion->forum->slug}}.frm.test/discussion/{{$discussion->id}}/{{$discussion->slug}}">{{$discussion->title}}</a>

But something about this feels wrong. Is there a better way to achieve this or is this ok?

memele left a reply on Models Not Accessible After Creating Subdomains

I found the problem and it was indeed the url parameters. When I did dd($id) in [email protected] it returned the forum name, so I guess if you have your routes inside a dynamic subdomain route group, the first url parameter will always be the subdomain.

memele left a reply on Models Not Accessible After Creating Subdomains

@DEVFREY - Thanks, great suggestions (especially the with() part).

The other route is pretty much the same, except that it doesn't take any parameters from the url. Could that be the problem here?

public function forum() {
    $subdomain = Route::current()->parameter('forum');
        $forum = Forum::where('slug', $subdomain)->firstOrFail();

    $latestComments = Discussion::where('forum_id', $forum->id)->with('user')->orderBy('updated_at', 'desc')->paginate(5);

    
    return view('home)->with([
        'forum' => $forum,
        'discussions' => $discussions
    ]); 

}

memele started a new conversation Models Not Accessible After Creating Subdomains

I created dynamic subdomain routes for my forum. The homepage works just fine with listing all discussions related to the subdomain. I moved the route for showing a single discussion inside the subdomain route group and it broke. When I try to access a discussion I get Trying to get property 'title' of non-object. The Model returns null.

web.php

Route::domain('{forum}.frm.test')->group(function () {

    Route::get('/', '[email protected]'); // Works just fine


    //Discussion routes

    Route::get('/discussion/{id}/{slug}', '[email protected]'); // Returns the error

});

DiscussionController

public function show($id, $slug)
    {
        $discussion = Discussion::where('id', $id)->where('slug', $slug)->with('user')->with('category')->first();

        return view('discussion.show')->with(['discussion' => $discussion]);
    }

What am I missing here? Why is the '/' route working but not the single discussion view?

20 May
2 months ago

memele left a reply on WYSIWYG Image Upload

@KUNDEFINE - I want to save the file to storage and save the file path in my database. With the code above I'm getting this error - https://imgur.com/a/036g37F but nothing in the console.

memele left a reply on WYSIWYG Image Upload

@KUNDEFINE - I'm still getting an error :/ I would actually like to save images to my database, but I can't even get this example to work.

memele started a new conversation WYSIWYG Image Upload

I am creating a forum and using Trumbowyg text editor for thread and comment textareas. I want my users to be able to upload images to comments and threads using Trumbowyg's upload plugin but I am having trouble understanding the documentation (https://alex-d.github.io/Trumbowyg/demos/plugins/upload.html).

How can I allow users to add multiple images and store them in my database? I understand that I should change the serverPath to a route that would catch the image upload post request. I don't understand why the fileFieldName is set to 'image' in this example, because when I inspect it with Dev Tools the file upload input name is 'file'.

The code from Trumbowyg's documentation:

$('#editor')
.trumbowyg({
    btns: ['upload'],
    plugins: {
        // Add imagur parameters to upload plugin for demo purposes
        upload: {
            serverPath: 'https://api.imgur.com/3/image',
            fileFieldName: 'image',
            headers: {
                'Authorization': 'Client-ID xxxxxxxxxxxx'
            },
            urlPropertyName: 'data.link'
        }
    }
});

Or is there an alternative WYSIWYG editor with a simpler image upload option?

15 May
3 months ago

memele left a reply on How To Use Contains() On This Collection?

@KEVINBUI - Changed it to @if ($onlineUsers->pluck('user')->contains('name', $comment->user->name)) and it works. Thanks :))

14 May
3 months ago

memele left a reply on How To Use Contains() On This Collection?

@YEZAWHEIN - now I get Call to undefined method Kim\Activity\Activity::contains()

memele started a new conversation How To Use Contains() On This Collection?

I am using a package to retrieve online users - https://github.com/thomastkim/laravel-online-users I have a global collection in AppServiceProvider that fetches all currently online users. Unfortunately this package doesn't provide a method for checking if a specific user is online and I am having trouble implementing this. I tried running contains() on the collection but it doesn't work. When I echo this collection with blade I get this:

[{"id":0,"user_id":2,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0","payload":"YTo0O...,"user":{"id":2,"type":"user","name":"testuser","image":"default.png","email":"[email protected]","email_verified_at":null,"banned":0,"strikes":0,"created_at":"2019-05-09 10:21:58","updated_at":"2019-05-09 10:21:58"}}]

and in user view:

@if ($onlineUsers->contains($comment->user->name))
                <img src="/storage/img/avatars/{{$comment->user->image}}" alt="" height="50px" width="50px" style="border-radius: 100%; object-fit:cover; border: 4px solid lime">
            @else
                <img src="/storage/img/avatars/{{$comment->user->image}}" alt="" height="50px" width="50px" style="border-radius: 100%; object-fit:cover;">
            @endif

but it returns everything as true (all users get the green border, online or not)

if I change the condition to @if ($onlineUsers->contains('name', $comment->user->name)) then everything returns as false and online users don't get the green border.

and if I do @if ($onlineUsers->user->contains('name', $comment->user->name)) I get an error : Property [user] does not exist on this collection instance.

03 May
3 months ago

memele started a new conversation How To Block Content From Blocked Users?

I'm creating a forum. I want users to have the ability to block other users so that they wouldn't see any of their content and wouldn't get private messages from them. I have created a BlockedUser model and functions in the controller - block, unblock and list all blocked users.

But how do I go about hiding the content? Should I just check if user is blocked directly in the view or is there a better way to do this?

30 Apr
3 months ago

memele started a new conversation How To Convert Typed Emojis To Unicode?

I am using CKEditor with unicode emoji for posts and comments. I want typed emoji like ':D, :), :( etc' to automatically convert to unicode emojis which uses shortcuts like :grinning_face: How can I do this? Find all occurrences of typed emojis and replace them? Or is there a better way to do this?

Thanks

25 Apr
3 months ago

memele left a reply on How To Sort Posts By Latest Commented

@EDOC - Awesome, this works :) Didn't know about the touch() method, I'll read up on it.

Thanks.

memele left a reply on How To Sort Posts By Latest Commented

Post Model

class Post extends Model
{
    public function category() {
        return $this->belongsTo('App\Category');
    }

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

    public function comments() {
        return $this->hasMany('App\Comment');
    }

}

Comment Model:

class Comment extends Model
{
    public function post() {
        return $this->belongsTo('App\Discussion');
    }

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

I want to display posts by latest comments. I also want to display the comment count for the post.

memele left a reply on How To Sort Posts By Latest Commented

@BRAUNSON - orderByDesc() didn't work, switched it to sortByDesc() but I'm still getting posts in a random order: a post 2 comments, 4 comments, 1 comment.

memele left a reply on How To Sort Posts By Latest Commented

@BRAUNSON - I'm getting an error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'comments.created_at' in 'order clause' (SQL: select * from posts order by comments.created_at desc)

memele started a new conversation How To Sort Posts By Latest Commented

I have a One to Many relationship for a Post model and a Comments model. I want to sort posts by latest commented - if someone posts a new comment that post goes to the top of the page.

This is what I tried but I still don't get posts sorted by latest comment. What is the correct way to do this?

$latestComments = Post::with(['comments' => function ($q) {
      $q->orderBy('created_at', 'desc');
}])->get();
21 Apr
3 months ago

memele started a new conversation How To Save Multiple Models From One Form

I am building a resume generator. I have a form where the user fills out basic data about themselves and a section with info about education. The user can append multiple fields about education with jQuery. The question is - how do I create a foreach loop to save all the information? I know how to do this with one field but how do I do this with multiple fields and have them all saved as a separate Education model instance? This is the html for each section for education:

    <div class="form-group education-container">
                    <div class="education-wrapper">
                        <div class="form-group">
                            <div class="form-row">
                                <div class="col-6">
                                    <div class="form-group">
                                        <label for="education-title">Title of Institution</label>
                                        <input type="text" class="form-control education-title" name="education-title[]" id="education-title" placeholder="Title of Institution" required>
                                    </div>
                                </div>

                                <div class="col-6">
                                    <div class="form-group">
                                        <label for="education-specialty">Specialty</label>
                                        <input type="text" class="form-control education-specialty" name="education-specialty[]" id="education-specialty" placeholder="Specialty" required>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="form-row">
                                <div class="col-6">
                                    <label for="education-year-from">Year From</label>
                                    <select class="form-control education-year-from" name="education-year-from[]" id="education-year-from" required>
                                        <option>Year from..</option>
                                        <option>2</option>
                                        <option>3</option>
                                        <option>4</option>
                                        <option>5</option>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label for="education-year-to">Year to</label>
                                    <select class="form-control education-year-to" name="education-year-to[]" id="education-year-to" required>
                                        <option>Year to..</option>
                                        <option>2</option>
                                        <option>3</option>
                                        <option>4</option>
                                        <option>5</option>
                                        <option> - now</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    

                </div>
                <button class="btn btn-success add-education">+</button>
13 Mar
5 months ago

memele left a reply on How To Create A Php File Caching Mechanism?

@CRNKOVIC - When exactly do I trim the $key? I tried this before but realized I can't call the get() method without the timestamp.

For example, I have a file named result1552492419, how would I call it with the get() method?

memele left a reply on How To Create A Php File Caching Mechanism?

I got it working (kind of).

Since the interface requires a $duration argument in the set method, I added it as a property. If I run the set function once and then the get function separately, the $duration property is empty. If I hardcode the duration it works just fine. What am I doing wrong here?


class Cache implements CacheInterface 
{
    private $duration;
    
    public function set(string $key, $value, int $duration) 
    {
        $this->duration = $duration;
        file_put_contents($key, $value);
    }


    public function get(string $key) 
   {

        if (file_exists($key) && time() - filemtime($key) < $this->duration) {
            $fileContents = file_get_contents($key);
            $output = unserialize($fileContents);
            var_dump($output);
        } else {
            echo 'cache expired';
            return null;
        }
    }


}

//Instantiate the Cache class
$file = new Cache;

//$file->set('result', $resultFinal, 60*5);

$file->get('result'); //Returns null because $duration is empty once the set method is commented out

memele left a reply on How To Create A Php File Caching Mechanism?

@crnkovic, I was also thinking about file_put_contents but I wasn't sure. Also didn't know how to check the time, will try your way. Also, did I guess right - the $key argument is supposed to be the file name?

A few other questions - as I mentioned before I'm not too good with OOP yet. The code I wrote is a mixture from Laracasts videos and some tutorials I found. (One of the requirements is that the interface should be constructor-injected in to the service). Can you explain the need for a CacheController? Can't I do the same in the Cache object?

memele started a new conversation How To Create A Php File Caching Mechanism?

I applied for a Junior PHP Developer position and got a test that I need to finish today. The idea is to get data from their API and cache it for a set amount of time. I got the data, that part was easy, but I'm having trouble writing the set method for caching (I need to use an interface they supplied).

I know they want to test my knowledge of OOP and I thought I have the basics down but I guess this is too advanced for me. I have rewatched PHP OOP videos (inheritance, messages 101..) at least five times and I still don't fully get it.

Am I aiming too high and not ready for a job?

Any help would be greatly appreciated. Here's the code I have so far. Just to make it clear, I don't want an exact answer but maybe some pointers in the right direction? Thanks.

$result = $response->getBody(); //Data that needs to be cached
$jsonToArray = json_decode($result, true); //Needs to be stored as an array

interface CacheInterface 
{
    public function set(string $key, $value, int $duration);
    public function get(string $key);
}



class CacheController 
{
    private $cache;

    public function __construct(CacheInterface $cache) {
        $this->cache = $cache;
    }
}

class Cache implements CacheInterface 
{
    
    public function set(string $key, $value, int $duration = 60*5) {
        //key->filename?
        //value->json
    }


    public function get(string $key) {
        //if file exists, return file
        //else return null
    }

}