hepabolu

hepabolu

Member Since 1 Year Ago

Experience Points
15,900
Total
Experience

4,100 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
152
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.

Level 4
15,900 XP
16 Sep
1 year ago
15 Sep
1 year ago

hepabolu started a new conversation What Is The Best Way To Get Properties Of Model For Logged In User?

I'm working on a wishlist type of app in Laravel 5.6. A user can mark a product as 'wanted'. I have 3 models:

  • Product (id, title, more info)
  • User (the default User model of Laravel)
  • Wishlist (product_id, user_id, wanted) - 'wanted' is a boolean

There is not a wishlist record for every product/user combo.

When displaying a list of products I want to mark the ones on the 'wanted' list for the logged in user. What would be the best approach? I can turn the Wishlist into a pivot but how do I get only the record for the current logged in user, if there is one?

05 Sep
1 year ago

hepabolu left a reply on Database Tables Deleted After Running Phpunit Test

It looks like you're running into the same problem I ran into where your phpunit tests clear out the database you use for manual testing/development. PHPunit probably uses the correct APP_ENV but somehow fails to pass it on to php artisan that does the database migrations and/or database refresh.

Here is how I solved it:

  1. in config/database.php I added a 'testing' connection which in your case, looking through your description, would be a copy of your 'sqlite' connection.

  2. I created a bash script that I run instead of the ./vendor/bin/phpunit statement:

    php artisan cache:clear
    php artisan config:clear
    
    APP_ENV=testing
    
    ./vendor/bin/phpunit "[email protected]"
    
  3. in CreatesApplication.php I added a function that throws an exception if the database name is not 'testing'. I found this: https://hackernoon.com/how-i-destroyed-the-staging-database-b435f98569ab

03 Sep
1 year ago

hepabolu left a reply on Sticky Database Name Across Environments

To answer my own question (for others who might run into this):

I narrowed the problem down to php artisan using the wrong environment even when I cleared caches.

I found this: https://hackernoon.com/how-i-destroyed-the-staging-database-b435f98569ab

and took precautions to throw an exception when the testing database wasn't used.

And I created a shell script that does three things:

  • APP_ENV=testing
  • clear all the various caches with php artisan
  • run phpunit

I can now verify that the test database is used.

02 Sep
1 year ago

hepabolu left a reply on Sticky Database Name Across Environments

Unfortunately I'm back where I started. In my code I need some complex SQL statements where MySQL and Sqlite differ in code. So I had to revert to using a MySQL database for testing. So the only thing I did in the working setup described before is change the database to 'mysql' I left everything else the same. So here are the relevant config settings:

# .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=localdb


DB_TEST_DATABASE=testing

config/database.php

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
...
],
'sqlite_testing' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => 'testing',
...
]

phpunit.xml

        <env name="APP_ENV" value="testing"/>
        <env name="DB_CONNECTION" value="sqlite_testing"/>
        <env name="DB_DATABASE" value="testing"/>

22 Jul
1 year ago

hepabolu left a reply on Statement On SQLite Test Database Returns Null While Record Is Available

Good point. I'll switch back to MySQL for testing. It was just very convenient because it was fast.

21 Jul
1 year ago

hepabolu started a new conversation Statement On SQLite Test Database Returns Null While Record Is Available

I'm trying to test a function that tries to fuzzy match a name to a name in the database.

Basically:

  • givenName = 'Peter'
  • familyName = 'Pan'

match('Peter Joe Pan') should return the record.

The query running on a MySQL db would be

Person::whereRaw('"' . $name . '" like concat(givenName , "%",  familyName)')->first();

When I run my test where I test 'Peter Joe Pan', it works.

Recently I changed to using sqlite as a test database. Sqlite doesn't have the concat function, so I modified the function:

Person::whereRaw('"' . $name . '" like givenName  || "%" ||  familyName)')->first();

The test now fails, i.e. the result is NULL. If I change first() into firstOrFail(), I get an exception.

However, when I log Person::all() I get the "Peter Pan" record.

Also, when I build an sqlite database using Base and I run the query I get the record, i.e. the query is correct.

I'm at a loss what to do. If I cannot solve this problem, the only thing I can think of is switching back to using MySQL as test database.

Any suggestions?

17 Jun
1 year ago

hepabolu left a reply on Sticky Database Name Across Environments

@bobbybouwmann it is set to testing. I'm pretty sure I've cleared the config cache, but it looks like it's working now.

hepabolu left a reply on Sticky Database Name Across Environments

Looks like that was it! Thanks so much.

hepabolu left a reply on Sticky Database Name Across Environments

I run the tests simply using

vendor/bin/phpunit

and

php artisan dusk

from the root dir of my app.

I think I've run

php artisan config:clear

just checking right now.

hepabolu started a new conversation Sticky Database Name Across Environments

I'm working through the Laracasts series on how to build a Forum and try to apply the instructions to my own app (Laravel 5.6).

In one of the first episodes Jeffrey defines a test database as an in memory sqlite database while he manually tests in the browser using a MySQL database.

I've tried to set up my own configuration similar to his setup but whatever I do, the unit tests drop all the tables in my local database rather than using the database that is configured in either phpunit.xml, or for the 'testing' environment (a different MySQL database called 'testing').

I've tried to fix this problem, but can't figure out what's going on. Is there any way I can troubleshoot this?

01 Jun
1 year ago

hepabolu left a reply on Best Way To Handle Complex Form With Laravel Vs Vue

Thanks for the answers so far. It’s too late here to act upon it now, but I’ll definitely give it a go tomorrow or the next day. Both answers confirmed my ideas that I need a combination of Vue and Blade etc. and both answers provide some approaches I can explore.

@andonovn I know there is no such thing as ‘best approach’ but some approaches get you nowhere and I want to avoid those. Your elaborate answer is appreciated. As is the other one.

hepabolu started a new conversation Best Way To Handle Complex Form With Laravel Vs Vue

I'm building a form that needs to add a book to the database. The intention is to:

  • make entering the data as easy as possible
  • prevent the creation of a duplicate book
  • prevent the creation of duplicates of the author's name

The idea is to do the following:

  • when the user enters an ISBN, the ISBN is checked against the database for duplicates. If it's a duplicate the book information is mentioned and the book form cannot be submitted.
  • if the ISBN doesn't exist, the website goes out and fetches the information from Google books or Amazon and prepopulates the fields so user only needs to check the information and either correct or add additional data.
  • if the author name is entered, it is checked against available names in the database using some fuzzy matching to allow for typos. If the name doesn't exists, we move on to the next field.
  • if the author exists, a list of possible candidates is shown so the user can pick the right one.

What's the best approach to handle all this interaction? Laravel Blade + Form Requests? Vue? Controllers? Any combination and so which component has which task?

21 May
1 year ago

hepabolu left a reply on 'A Non-numeric Value Encountered' After Return From Method

I copied the 'findPerson' method to the 'MyController' class and called that method in 'processPerson' --> all was fine.

I then reverted to calling the findPerson method from the PersonRepository --> all was fine.

I have no clue what happened and why it suddenly fixed itself.

hepabolu started a new conversation 'A Non-numeric Value Encountered' After Return From Method

I have a strange issue that an object that is returned from a method of a different class, is suddenly throwing the error 'A non-numeric value encountered'.

class PersonRepository
{
    public function findPerson($name)
    {
        $person = Person::where('intricate query');

        // display person to know for sure it's a Person object
        Log::debug('person found: ' . print_r($person, true)); 

            // result -> display of App\Person obj

        return $person;
    }
}


class MyController
{
    public function processPerson($name)
    {
        $personRepo = new PersonRepository();
        $person = $personRepo->findPerson($name);

        Log::debug('person found2: ' . print_r($person, true));

        // throws error
    }
}

The first Log statement displays a perfectly fine Person object. The second one throws an error.

PHP version 7.2.1

Can somebody help troubleshooting this?

UPDATE: the same error is thrown when I simply create a new Person object in the processPerson method:

        $person = new Person();

        Log::debug('person found2: ' . print_r($person, true));

        // throws error
``
16 May
1 year ago

hepabolu left a reply on Switching Env To Production Causes HTTP 500

Well, after some digging around I decided to remove everything under 'vendor' and 'bootstrap/cache' and run 'composer install --no-dev' again.

rm -rf vendor/*
rm bootstrap/cache/*
composer install --no-dev

Then I ran some of the artisan statements to clear caches:

php artisan cache:clear
php artisan view:clear
php artisan config:cache

and now it works.

hepabolu started a new conversation Switching Env To Production Causes HTTP 500

I've built my first Laravel appication locally (Laravel 5.6) and the basic functionality works. So I decided to put a beta version on a Digital Ocean server for others to look at.

Here's what I did:

  • droplet = ubuntu 16.04 1-click app with LEMP stack
  • php 7.2 fpm
  • letsencrypt cert installed so everything runs at https
  • rsync copy the entire local directory (so I also have my resources etc.)
  • local dump of database imported on the server

With 'APP_ENV=local, APP_DEBUG=false' everything at the server works as expected. I've clicked around and all pages seem to load fine.

I then switched the APP_ENV to 'production' and suddenly a page that worked before now throws an HTTP 500.

I can't find any logging that can give more information so I'm lost as to what to do.

Questions:

  • what could be wrong?
  • where can I find more logging so I can troubleshoot this?
  • where do I configure more logging if there is no logging configured?
23 Apr
1 year ago

hepabolu left a reply on Best Practice To Handle Business Logic With Interlinked Objects

@bobbybouwmann You nailed my feeling exactly re the use of controllers in controllers.

I'm going to try out Repositories as per your advice and linked article.

Just a follow up question: where would you put the code to convert the most recent images into a list of poems these images are attached to so I can pass the appropriate into to the view? The keys are defined by the blade view, but I'd like to hide the relation between image and poem from the controller.

22 Apr
1 year ago

hepabolu started a new conversation Best Practice To Handle Business Logic With Interlinked Objects

This is my first Laravel project and I find it difficult to figure out where to put the business logic.

These are the main objects:

  • books
  • poems
  • authors
  • images

Business rules:

  • books can contain 1 - many poems

  • poems can occur in 1 - many books

  • a poem is written by an author

  • a book is written by an author

  • authors can write 1 - many poems

  • authors can write 1 - many books

  • a book has a cover image

  • a poem has one or more images displaying the poem

  • an author has an image

  • when a book is displayed on a book detail page, the author is displayed and a list of poems it contains

  • when a poem is displayed on a poem detail page, the author is displayed and a list of books it occurs in

  • when an author is displayed on an author detail page, a list of books and a list of poems is displayed

  • the "what's new" section has the latest 10 books added and the latest 10 images uploaded for the poems (i.e. show the poems for which the images are uploaded).

For brevity I left out all CRUD actions on the various objects.

I created a Model for each of the objects (Book, Poem, Author, Image) and resource controllers to handle the CRUD operations. Each of the models have relationships and, if necessary pivot tables.

For the 'what's new' section I added a WhatsNewController that pulls in the latest 10 books and the latest 10 images, but I have trouble finding the right location to add the code.

I added a method 'getMostRecent' to the BookController to get the appropriate Books:

return (new Book)->orderBy('created_at', 'desc')->take(10);

With the poem images I started with 'getMostRecentPoemImages' on PhotoController:

return (new Image)->where('type', 'poem')->orderBy('created_at', 'desc')->take(10);

In the WhatsNewController I pulled them in, but for the images I had to do some conversion:

$books = (new BookController)->getMostRecent();

$images = (new PhotoController)->getMostRecentPoemImages();

$poems = [];
foreach ($images as $image) {
    $poems[] = [
        'id' => $image->poem->id,
        'name' => $image->poem->name,
        'image' => $image->file,
}

// pass poems and books to view

This exposes way too much of the relationships to all kinds of classes. How can I improve this code?

hepabolu left a reply on Handling Data Import From Older Version

Thanks, that sounds like a reasonable approach.

hepabolu left a reply on Handling Data Import From Older Version

Good idea, but where would you put the code?

This is my first Laravel project so I'm looking for the best practice of handling this one-off import. I think it should not be part of the code that runs the regular site.

hepabolu started a new conversation Handling Data Import From Older Version

I'm working on a site that already has data that needs to be moved to the new site and to be converted to the new schema and cleaned up in the process.

Currently I use Seeders to process export files from the old database schema, but it doesn't look right.

What would be the best practice to do this?

11 Apr
1 year ago

hepabolu left a reply on Routing Problem, Single Route Not Found

@rin4ik I've tried similar approaches and none of them worked until I moved the top two routes to the bottom of the file.

Thanks for the commands, though.

hepabolu left a reply on Routing Problem, Single Route Not Found

I think I found the problem: /articles/create probably triggers /articles/{article}. On a hunch I moved the two routes at the top below the Route group. Once I did that, the 'new' form showed.

So the question remains: how could I have debugged this or which other action could I have taken to figure this out?

hepabolu started a new conversation Routing Problem, Single Route Not Found

I'm new to Laravel and based on the Laracasts episodes I've built my routes list and my Controller to handle the routes. Right now I'm running into the problem that /articles/create results in 404 and I have no clue how to troubleshoot this. Here is my routes list:

// Articles
Route::get('/articles', '[email protected]');
Route::get('/articles/{article}', '[email protected]');

Auth::routes();

// Registered User Routes
Route::group(['middleware' => ['auth']], function () {
    Route::get('/logout', ['uses' => 'Auth\[email protected]'])->name('logout');

    // Protected articles
    Route::get('/articles/create', '[email protected]');
    Route::post('/articles', '[email protected]');
    Route::get('/articles/{article}/edit', '[email protected]');
    Route::patch('/articles/{article}', '[email protected]');
    Route::delete('/articles/{article}', '[email protected]');
});

The ArticleController does contain the 'create' method:

class ArticleController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth')->except(['show', 'index']);
    }

    /**
     * Show the form for creating a new article.
     *
     * @return \Illuminate\Http\Response
     */

    public function create()
    {
        Log::debug('ArticleController.create');
        return view('articles.new');
    }

......

This is what works:

  • /articles shows the index
  • /articles/4 shows the content of article with id 4
  • /articles/4/edit redirects to the login page when the user is not logged in, otherwise it shows the edit form

However, when I enter /articles/create I get the default 'Sorry, this page cannot be found' with a 404.

When I run php artisan route:list it's there

GET|HEAD | articles/create               |                  | App\Http\Controllers\[email protected]                          | web,auth

The log statement isn't fired, so I guess the controller method isn't even started.

What I've tried:

  • I've tried retyping the text to avoid typos.
  • I've cleared caches.
  • I've moved the route outside the 'auth' group AND disabled the auth middleware in the constructor.
  • I'm using MAMP with a vhost just for this website with its own logfiles, but there is nothing in the logfiles.

I've googled for possible clues, but I can't find any.

What could be wrong, or how can I debug this?

hepabolu left a reply on Set General Dateformat For Display

I've set one to be the best answer, but in all I like all suggestions.

10 Apr
1 year ago

hepabolu left a reply on Set General Dateformat For Display

Thanks. This looks very useful too.

I managed to get @Snapey’s suggestion working. Thank you all for the help.

hepabolu left a reply on Set General Dateformat For Display

Thank you all for the various ways to solve this and the quick responses. @Snapey in particular thanks for the link. I think I'm going to try your approach since I want a little bit more control over the date, e.g. don't display the time if it's 'midnight' (i.e. no time available) and your approach looks like it's the most flexible to do this.

And thank you for your other post on the fontawesome star ratings. I need the same you but solved it much more elegantly.

@Cronix where would you put your helper function?

09 Apr
1 year ago

hepabolu started a new conversation Set General Dateformat For Display

I'm building my first Laravel application while learning Laravel. I'm currently looking for a way to set the dateformat for displaying dates in a single location so I don't have to pass it on in a view every time I'm displaying a date.

I'd like to display the dates always as 'j M Y'. I've added it to a config file so I can pull it in like

$dateformat = Config::get('siteconfig.dateformat');

But then I need to do this in every location I want the dateformat.

I've also tried to create an Accessor method on my Article model like:

public function getUpdatedAtValue()
{
    return $this->attributes['updated_at']->formatLocalized('j M Y');
}

but that doesn't seem to work AND I still need to set this for every date field I want to display.

Is there a better way?

02 Apr
1 year ago

hepabolu left a reply on Dusk Not Working With Factories And/or Migrations

Just in case this happened to someone else:

I had the same problem with the default Laravel 5.6 + current Laravel Dusk testcases for a user login.

I added the 'useDatabaseMigrations' trait to my LoginTest but it cleared out the database tables and didn't run the migrations so all tests failed. I used this post: https://www.neontsunami.com/posts/speed-up-your-laravel-tests-by-70-with-this-one-simple-trick

and the migrations started to work.

Finally I noticed I accidentally deleted the '/** @test */' annotation before my tests. Once I put those back in the 'use DatabaseMigrations' trait worked out of the box.

So

public function testValidLogin() {
...
}

doesn't trigger the database migrations. But

/** @test */
public function testValidLogin() {
...
}

does.