elo

elo

Member Since 1 Year Ago

Experience Points 2,050
Experience Level 1

2,950 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 6
Lessons
Completed
Best Reply Awards 0
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.

15 May
5 days ago

elo left a reply on Images Uploaded In Storage Not Accessible

@JACKL - Creating a php file in the public_html and attempting to access a route with the filename worked like magic. Everything worked fine after that. Basically it was something similar to what @andreich1980 suggested but without the need to create a route for it.

elo left a reply on Images Uploaded In Storage Not Accessible

@ROBSTAR - This particular client already purchased a domain name and the hosting with a preferred host so I had no input in that but I also learnt something new today on how symbolic links can be created without ssh on shared hosting.

elo left a reply on Images Uploaded In Storage Not Accessible

@ANDREICH1980 - As suggested, I created the route for test and add this code to it then called it but got an error symlink(): No such file or directory

route::get('/test', function () {
    symlink('/home2/raydacon/public_html/storage', '/home2/raydacon/raydaconcept/public_html/storage/app/public');
});

elo left a reply on Images Uploaded In Storage Not Accessible

@ANDREICH1980 - Is there a way I can create the symbolic link on shared hosting without ssh? Been waiting on the hosting support guys but no response yet.

elo started a new conversation Images Uploaded In Storage Not Accessible

In a laravel 5.6 project, I created a symbolic link using php artisan symboli:link cammand which then created a storage directory in my public folder on my development server. Everything seems to work fine on dev server but after deploying on shared hosting, image upload works fine and I can see the image in raydaconcept/storage/app/public/images/photos but the file is not in public_html/storage/images/photos.

When I copied an uploaded file from raydaconcept/storage/app/public/images/photos to public_html/storage/images/photos, I was able to display the picture on the site as I wanted.

How can I fix this so that my uploaded files show up in both places?

05 Oct
7 months ago

elo left a reply on ErrorException: Trying To Get Property 'id' Of Non-object

@tykus thanks. What eventually did was to get an existing user, authenticate the user and add a book before updating the book.

// Select an existing user randomly & authenticate the user.
        $user = User::all()->random();
        Passport::actingAs($user);

        // User adds a book
        $selectedBook = factory(Book::class)->create(['user_id' => $user->id]);

        // Update the book.
        $response = $this->json('PUT', '/api/books/'.$selectedBook->id, [
            'title'     => $this->faker->sentence(),
            'author'    => $this->faker->name()
        ]);

        $response->assertStatus(200);

elo started a new conversation ErrorException: Trying To Get Property 'id' Of Non-object

Recently I have been learning how to write unit test for my laravel apps and it's been interesting so far.

After many attempts, I finally wrote a test that updates a record but the strange thing is that sometimes the test passes and other times it fails. When the test fails, it throws the error

ErrorException: Trying to get property 'id' of non-object

The test in question is

public function testUpdateBookRecord()
    {
        // Select an existing user randomly & authenticate the user.
        $user = User::all()->random();
        Passport::actingAs($user);

        // Get any book belonging to the user.
        $selectedBook = Book::where('user_id', $user->id)->inRandomOrder()->first();

        // Update the book.
        $response = $this->json('PUT', '/api/books/'.$selectedBook->id, [
            'title'     => $this->faker->sentence(),
            'author'    => $this->faker->name()
        ]);

        $response->assertStatus(200);
    }

The controller function for updating a record is like this

public function update(Request $request, Book $book)
    {
        $validatedData = $request->validate([
            'title'     => 'required|unique:books',
            'author'    => 'required'
        ]);

        // Update book if the logged in user_id is the same as the book user_id
        if ($request->user()->id === $book->user_id) {
            $book->update($request->only(['title', 'author']));

            return new BookResource($book);
        } else {
            return response()->json(['error' => 'You do not have the permission for this operation'], 403);
        }
    }

The question is what is the reason for the test passing sometimes and then failing other times?

03 Oct
7 months ago

elo left a reply on Using Default UserFactory Inside Another Factory

@iyoworks Thanks for that answer. If i go this way, then in my test there will be no need to call the UserFactory since calling the BookFactory will create a user and assign the user_id. Then how will i go about checking authentication in my test? Using $response = $this->actingAs($user)->json.. will throw an error saying user is undefined.

elo started a new conversation Using Default UserFactory Inside Another Factory

I wrote a phpunit test to check that only an authenticated user with the same user id as a book's user id can update the book record but it failed.

public function test_onlyAuthenticatedUserCanUpdateBookSuccessfully()
    {
        $user = factory(User::class)->create();
        Passport::actingAs($user);

        $book = factory(Book::class)->create();

        dd($user, $book);

        // $response = $this->json('PUT', '/api/books/'.$book->id, [
        //         'id'    => $book->id,
        //         'title' => 'Updated book title',
        //         'author'=> 'New Guy'
        //     ]);

        // $response->assertStatus(201);
    }

While checking the dump, i discovered that the user id and the book's user_id are different

// Newly created user
#original: array:7 [
    "name" => "Prof. Norwood Erdman"
    "email" => "[email protected]"
    "updated_at" => "2018-10-03 14:11:20"
    "created_at" => "2018-10-03 14:11:20"
    "id" => 2
]

// Newly created book
#attributes: array:6 [
    "title" => "Quasi laudantium enim quas omnis."
    "author" => "Mr. Jayson Roob"
    "user_id" => 1
    "updated_at" => "2018-10-03 14:11:20"
    "created_at" => "2018-10-03 14:11:20"
    "id" => 3
]

This is because my BookFactory has been set up wrongly using hard coded user_id value

$factory->define(Book::class, function (Faker $faker) {
    return [
        'title'     => $faker->sentence,
        'author'    => $faker->name,
        'user_id'   => 1
    ];
});

How can I correct the BookFactory so that the user_id is set to the value of the created user? This is my UserFactory

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => '***************', // secret
        'remember_token' => str_random(10),
    ];
});
28 Sep
7 months ago

elo left a reply on Laravel PHPUnit Test Forbidden Error

@tykus Returned same error

elo started a new conversation Laravel PHPUnit Test Forbidden Error

I have written two PHPUnit test that updates and deletes a book record only if the user is authenticated. I am using Passport for authentication but my test fails with a 403 error for both test. What could be wrong with my code below

public function test_onlyAuthenticatedUserCanUpdateBookSuccessfully()
    {
        $user = factory(User::class)->create();
        Passport::actingAs($user);

        $book = factory(Book::class)->create();

        $response = $this->json('PUT', '/api/books/'.$book->id, [
                'id'    => $book->id,
                'title' => 'Updated book title',
                'author'=> 'New Guy'
            ]);

        $response->assertStatus(201);
    }

public function test_onlyAuthenticatedUserCanDeleteBook()
    {
        $user = factory(User::class)->create();
        Passport::actingAs($user);

        $book = factory(Book::class)->create();

        $response = $this->json('DELETE', '/api/books/'.$book->id);

        $response->assertStatus(204);
    }

elo left a reply on Authenticating Users In Phpunit Testing

@mehran I eventually solved it using your suggestion with a minor change. Here's what the code that worked for me

        $user = factory(User::class)->create();
        Passport::actingAs($user);

        $response = $this->json('POST', '/api/books', [
                'title' => 'new book post',
                'author' => 'new author',
                'user_id' => $user->id,
            ]);

        $response->assertStatus(201);

elo left a reply on Authenticating Users In Phpunit Testing

@mehran I tried doing it using passport but got 500 code.

So i tried creating a personal access token as suggested by @Mithrandir and use it in the POST request like this

public function test_onlyAuthenticatedUserCanAddBookSuccessfully()
    {
        $user = factory(User::class)->create();
        $token = $user->createToken('bookstore')->accessToken;

        $response = $this->withHeaders(['Authorization' => 'Bearer '.$token])
            ->json('POST', '/api/books', [
                'title' => 'book post',
                'author' => 'post author'
            ]);

        $response->assertStatus(201);
    }

But ended up with the error

There was 1 error:

1) Tests\Feature\BooksTest::test_onlyAuthenticatedUserCanAddBookSuccessfully
ErrorException: Trying to get property 'client' of non-object

C:\wamp64\www\bookstore\vendor\laravel\passport\src\ClientRepository.php:89
C:\wamp64\www\bookstore\vendor\laravel\passport\src\PersonalAccessTokenFactory.php:71
C:\wamp64\www\bookstore\vendor\laravel\passport\src\HasApiTokens.php:67
C:\wamp64\www\bookstore\tests\Feature\BooksTest.php:21

ERRORS!
Tests: 4, Assertions: 17, Errors: 1.

Any one knows what is wrong now?

elo started a new conversation Authenticating Users In Phpunit Testing

How can I authenticate a user when doing phpunit test? I have written a phpunit test that first creates a user then uses the user's token credentials in the header when adding a new book item. Unfortunately, my test is failing with 401 status returned.

This is my BooksTest

class BooksTest extends TestCase
{
    public function test_onlyAuthenticatedUserCanAddBookSuccessfully()
    {
        $user = factory(User::class)->create();
        $token = str_random(10);
        $book = factory(Book::class)->create();

        $response = $this->withHeaders(['Authorization' => "Bearer $token"])
            ->json('POST', '/api/books', [
                'title' => 'book post',
                'author' => 'post author'
            ]);

        $response->assertStatus(201);
    }
}

I am using Passport for my app and using the default UserFactory for users. I also have a BookFactory that looks like this

$factory->define(Book::class, function (Faker $faker) {
    return [
        'title'     => $faker->sentence,
        'author'    => $faker->name,
        'user_id'   => 1
    ];
});

$factory->define(Rating::class, function (Faker $faker) {
    return [
        'user_id'   => 1,
        'book_id'   => mt_rand(1, 2),
        'rating'   => mt_rand(1, 5)
    ];
});

I have never worked with phpunit testing before now, so I would appreciate help with explanation too on the best way to do it.

21 Sep
7 months ago

elo started a new conversation Seeding Data Using Factory And Eloquent Models

I am trying to seed my books and ratings table, and the relationship between them is that a book has many ratings while a rating belongs to a book. I want the each seeded book record to have a rating for each seeded user. Which means if i have only one user and 2 books, my ratings table should have only 2 records.

Unfortunately my code doesn't work like I want it to. I have a situation where one user has multiple rating for each book, how do I achieve my goal of having a user rate a book just once?

This is my code

BookFactory.php

$factory->define(Book::class, function (Faker $faker) {
    return [
        'title'     => $faker->sentence,
        'author'    => $faker->name,
        'user_id'   => 1
    ];
});

$factory->define(Rating::class, function (Faker $faker) {
    return [
        'user_id'   => 1,
        'book_id'   => mt_rand(1, 2),
        'rating'   => mt_rand(1, 5)
    ];
});

BooksTableSeeder.php

public function run()
    {
        // First remove existing books records
        Book::truncate();

        factory(App\Book::class, 2)->create()->each(function ($book) {
            // Add book rating
            $ratings = factory(App\Rating::class, 1)->create(['book_id' => $book->id]);
            $book->ratings()->saveMany($ratings);
        });
    }
18 Sep
8 months ago

elo left a reply on How Do I Implement API Delete Endpoint For Authorized User Only

Thanks, another reason why I should take a break and read over my code again.

elo started a new conversation How Do I Implement API Delete Endpoint For Authorized User Only

Hi, I have created API endpoints using Passport for authorization and API resource feature. My goal is to allow everyone get api/books and api/books/book but only authorized users can update and delete. This is the code I am working with in BookController

public function __construct()
    {
        $this->middleware('auth:api')->except(['index', 'show']);
    }

public function destroy(Book $book)
    {
        $book->delete();

        return response()->json(null, 204);
    }

Right now any logged in user can delete any book. What I want is to allow delete only if the logged in user()->id === book->user_id, so I have modified my code like so

public function destroy(Request $request, Book $book)
    {
        // Delete book only if user_id matches book's user_id
        if ($request->user()->id === $book->user_id) {
            $book->delete();

            return response()->json(null, 204);
        } else {
            response()->json(['error' => 'You do not have the permission for this operation'], 403);
        }
    }

When I delete a book owned by the logged in user, the operation is successful and 204 status code is returned. But if the book doesn't belong to the user, i get a 200 ok status and book is not deleted. I want to display the error message in this case.

How do I fix it?

27 Jul
9 months ago

elo started a new conversation Database Migration Failing On AWS Elastic Beanstalk

I have deployed a laravel app using AWS Elastic Beanstalk and able to hit pages with no dynamic contents. To create my RDS db, I have edited the database.php file like so

// at the very top after php tag

define('RDS_HOSTNAME', $_SERVER['RDS_HOSTNAME']);
define('RDS_USERNAME', $_SERVER['RDS_USERNAME']);
define('RDS_PASSWORD', $_SERVER['RDS_PASSWORD']);
define('RDS_DB_NAME', $_SERVER['RDS_DB_NAME']);

// inside return block connections
'mysql' => [
            'driver' => 'mysql',
            'host' => RDS_HOSTNAME,
            'port' => env('DB_PORT', '3306'),
            'database' => RDS_DB_NAME,
            'username' => RDS_USERNAME,
            'password' => RDS_PASSWORD,
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

I also added a folder .ebextenisons folder and the init.config file inside it. The init.config file has the following code in it

container_commands:
    01initdb:
        command: "php artisan migrate"

On AWS elastic beanstalk console, I configured the username and password for mysql 5.7 version. But the application failed to upload and I got the error below

[Instance: i-0e113cddded1802a6] Command failed on instance. Return code: 1 Output: (TRUNCATED)... In Connection.php line 647: SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from inform ation_schema.tables where table_schema = and table_name = migrations) In Connector.php line 68: SQLSTATE[HY000] [2002] No such file or directory. container_command 01initdb in .ebextensions/init.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.

What could I be doing wrong and how can i fix this error?

29 Jun
10 months ago

elo left a reply on Using Mcamara/laravel-localization In Laravel 5.4

@BishoyWagih are you saying that there is no need for me to create a resources/views/fr directory, instead i simply create resources/lang/fr?

in a situation where the page has hard code text(text not coming from a database query), how do i do my translation?

elo started a new conversation Using Mcamara/laravel-localization In Laravel 5.4

Hello, I'm currently trying to add localization to my laravel 5.4 app and opted to use mcamara as it seems to be very popular. However I'm stuck and confused as what next to do after doing the following

  1. Installed the package

  2. Registered service provider and facede both in config/app.php

'providers' => [
    // other providers are above this
    Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider::class,
],

'aliases' => [
    // others are above this
    'LaravelLocalization' => Mcamara\LaravelLocalization\Facades\LaravelLocalization::class,
],
  1. Registered middleware in app/Http/Kernel.php
protected $routeMiddleware = [
        // lang-support
        'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
        'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
        'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
        'localeViewPath' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class
    ];
  1. Added route to localize in route group like so
Route::group(
    [
        'prefix' => LaravelLocalization::setLocale(),
        'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
    ],
    function()
    {
        Route::get('test', function () {
            return view('test');
        });
    }
);
  1. Edited config/laravellocalication.php file by uncommenting out the languages i want to support.

  2. Created resources/views/dewhere test.blade.php is kept.

My questions are

  1. Do I have to do the translation myself? If so, how do I go about it? I saw from the documentation that I can put some sort of php file in resources/lang directory

  2. If I have done the right thing by creating resources/views/de, do I also put the public folder inside it? At the moment, I do not see the images in the public folder's image directory when I visit http://127.0.0.1:8000/de/test. From developer tools, the requested URL is http://127.0.0.1:8000/de/images/test.png

Kindly help

10 Jun
11 months ago

elo left a reply on Unable To Check Authenticated User's Property

@Cronix Yes the equality check too was am issue. Thanks for pointing that out as well.

elo left a reply on Unable To Check Authenticated User's Property

I was right! Somehow the whole foreign key thing was messing something up. Modifying my user's table and having no foreign key reference fixed my logic. I still wonder why though.

elo left a reply on Unable To Check Authenticated User's Property

@Cronix I'm not using caching. I just used the default laravel make:auth without changing anything besides the table structure for users and creating a roles table referenced by the user's table role_id column. Is it possible that the issue is due to foreign key reference?

Let me reset migrations and just add a role column to the user table and see what happens

elo left a reply on Unable To Check Authenticated User's Property

login using user 1 after logging in, go to yoursite.test/usertest what is the role_id?

"role_id" => 1

logout login as user 2 go to yoursite.test/usertest what is the role_id?

"role_id" => 2

elo left a reply on Unable To Check Authenticated User's Property

@Cronix Cleared the view, no change. Yes to questions 2. I have no idea why or where the value is coming from, doesn't seem to be coming from the database but Auth::user()->name is right as it is in the database.

elo left a reply on Unable To Check Authenticated User's Property

@Cronix I have made that correction but nothing has changed. I'm wondering why Auth::user()->role_id returns 1 for both users (keep in mind that one has a role_id of 1 and the other 2), I believe if I fix that then everything will work fine.

elo left a reply on Unable To Check Authenticated User's Property

@Cronix this is the code that checks the role_id of the user and displays the menu item

@if (Auth::user()->role_id = 1)
    <li class="nav-item">
        <a class="nav-link" href="{!! url('user') !!}">
        Users
        </a>
    </li>
@endif

The issue is this link is always shown even when the authenticated user isn't an admin and the role_id from in the user's table is 2 and not 1. When i displayed the the role_id of this user in my view like so {{ Auth::user()->role_id }}, the role_id is 1 but it is 2 in the user's table which is very wierd.

elo left a reply on Unable To Check Authenticated User's Property

@xtremer360 Look at my user's table data

id  name            email                          password     role_id
1   Developer   [email protected]     **********  1
3   ayo             [email protected]    **********  2

The role_id are not passed inside the form but in the controllers. The form actions for register and create user are

<form class="form-horizontal" method="POST" action="{{ route('register') }}">

<form class="form-horizontal" method="POST" action="{!! url('user') !!}">

elo started a new conversation Unable To Check Authenticated User's Property

I have a user's table setup with a role_id column that references the id on the roles table. When a user registers using the registration page generated with make:auth command, the user will be automatically assigned role id of 1. RegisterController

$user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'role_id' => 1,
       ]);

        return $user;

When the user is created by an admin, the user will be assigned the role id of 2. UserController

public function store(Request $request)
    {
        $role_id = 2;
        
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
            'role_id' => $role_id
        ]);

        return redirect('user');

    }

From the database record I can see the right role id being assigned as intended but when i try to show a menu item based on the authenticated user's role_id, I noticed the same menu items are shown for both the roles. While trouble shooting, i noticed that for both users whose user table role_id values are 1 and 2 respectively, Auth::user()->role_id returns 1.

How did I manage to screw things up with something as straight forward as this?

09 Jun
11 months ago

elo started a new conversation Unable To Register New User

I'm trying to set a role_id = 1 for a user when they register, then this user can create other users that will have a role_id = 2. I have created a roles table and modified the users table to have a role_id column that references the roles id column. This what my create user method in the RegisterController looks like now

protected function create(array $data)
    {

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'role_id' => 1,
        ]);

        return $user;
    }

My users table migration is as below

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->unsignedInteger('role_id');
            $table->foreign('role_id')->references('id')->on('roles');
            $table->rememberToken();
            $table->timestamps();
        });
    }

When i try to register a new user, i get the error below

Illuminate \ Database \ QueryException (HY000) SQLSTATE[HY000]: General error: 1364 Field 'role_id' doesn't have a default value (SQL: insert into users (name, email, password, updated_at, created_at) values (tester, [email protected], $2y$10$GHPuA0t5Tr8/1oU2wYg97O2tuxRJhNaE8FPtQnP0M8GXg5mfwiSta, 2018-06-09 07:25:31, 2018-06-09 07:25:31))

What am I doing wrong? Note I'm working with version 5.5

03 Mar
1 year ago

elo left a reply on API Call FatalErrorException

@meeshka Thanks for breaking it down. I will install the package and test again.

elo left a reply on API Call FatalErrorException

@meeshka yes I installed OAuth. I quickly created a new project and left out OAuth, deployed it again and API routes are working properly. For situations where I install a composer package, how do I stop my project from throwing errors like this?

02 Mar
1 year ago

elo started a new conversation API Call FatalErrorException

Hi guys, I deployed an API service built with Lumen 5.4 on shared hosting. When i try to test the API routes, i get this error

(1/1) FatalErrorException
Illuminate\Support\ServiceProvider::mergeConfigFrom(): Failed opening required '' (include_path='.:/opt/cpanel/ea-php56/root/usr/share/pear')

in ServiceProvider.php (line 59)

at Application->handleShutdown()
in RegistersExceptionHandlers.php (line 54)

at Application->Laravel\Lumen\Concerns\{closure}()

but test on my development system with Postman was successful. I have no idea what the problem and need help fixing this error.

13 Feb
1 year ago

elo started a new conversation Using Google Forms Inside A Laravel App

Hi guys, is it possible to use google forms inside a laravel application? I have built one with laravel 5.4 and my client wants people to apply for advertised jobs using google forms. So when they click apply, the form is displayed to them and the response and resume attachment sent to the client's email address. Can it be done this way and how? Never done anything like this before.

21 Sep
1 year ago

elo left a reply on File Validation Failing On Larger Files.

@bashy I have made the changes to my php.ini file and restarted wamp and then shutdown and restarted my system. Issue is that I'm still getting the error

The file "20161118_120328.jpg" exceeds your upload_max_filesize ini directive (limit is 2048 KiB).

Inside my php.ini file, here are the edits

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 100M

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20

; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size = 125M

I have no idea why the changes won't work.

19 Sep
1 year ago

elo left a reply on Displaying Dynamic Data Inside Lightbox

Fixed it! By simply switching the default bootstrap 4 jquery.slim cdn to jquery.min cdn, i was able to get my gallery display just as i wanted it to. Discovered from SO that jquery slim did not include the fadeIn function and this caused my code to throw up that error. I hope this helps someone too.

elo left a reply on Displaying Dynamic Data Inside Lightbox

@topvillas thanks for chipping in but that didn't fix it.

18 Sep
1 year ago

elo started a new conversation Displaying Dynamic Data Inside Lightbox

My goal is to have an image gallery page that displays images in a modal when users click on a picture and be able to view other pictures by clicking on the left and right arrows. I'm attempting to achieve this with lightbox by Lokesh Dhakar http://lokeshdhakar.com/projects/lightbox2/ . I have added lighbox.css and lightbox.js to my laravel project and my view renders properly but when i click on an image in chromo, the image opens fully in the same tab so that i don't have that modal effect. From the console i see this warning message

Resource interpreted as Document but transferred with MIME type image/png: "http://127.0.0.1:8000/images/albums/albumImg/ckmUU5_album_image.png".

This is the first time I'm doing anything like this with laravel, so i haven't been able to figure out what I'm doing wrong. This is the code i have below

<div class="card-columns mb-5" id="albumImgs">

@foreach($album->photos as $photo)

    <div class="card">

        <a href="{{URL::to('/')}}/images/albums/albumImg/{{$photo->image}}" data-lightbox="photos">

            <img class="card-img" src="{{URL::to('/')}}/images/albums/albumImg/{{$photo->image}}" alt="">

        </a>

    </div>

@endforeach

</div>

I need help figuring out what I'm doing wrong and how to achieve my goal.

elo left a reply on How Can I Display A Data From Eloquent Relationship In Bootstrap Modal?

@mattsplat Thanks for reponding, tried that code but still getting errors & yes all album photos are shown when i click on the album.

@Dhaval_patel I'm yet to try out your suggestion since I'm not very good with javascript but i plan on giving it a shot.

13 Sep
1 year ago

elo left a reply on How Can I Display A Data From Eloquent Relationship In Bootstrap Modal?

@mattsplat I have updated my code. I added a carousel inside the modal body and displays each $album->photo inside it so users can click on the controls to slide through the album images. But what happens now is that only the first album images are displayed in the carousel but the images are stacked. There are 2 things to look at now

  1. How do i make only the first image active?
  2. How do i ensure that the album with id=2 has its own images showing in the carousel when it is clicked?
12 Sep
1 year ago

elo started a new conversation How Can I Display A Data From Eloquent Relationship In Bootstrap Modal?

I have this idea for an image gallery. First I have created an album and also added images to the album. On the gallery page, I'm able to display the album cover. Now what I want to achieve is this, if an album is clicked on then a modal pops up and images inside the album will be displayed in it. I have no idea how I can use the relationship data inside a bootstrap modal. Here's what I have in my Album model

<?php

namespace App;

use App\Image;
use Illuminate\Database\Eloquent\Model;

class Album extends Model
{
    protected $guarded = ['id'];

    public function photos()
    {
        return $this->hasMany(Image::class, 'album_id');
    }
}

AlbumController

public function index()
{
     $albums = Album::with('photos')->orderBy('created_at', 'ASC')->get();

     return view('gallery.gallery', compact('albums'));
}

gallery.blade.php

<div class="card-columns col-12" id="albums">
                
    @if($albums->isNotEmpty())

        @foreach($albums as $album)

            <div class="card">
                <img src="{{URL::to('/')}}/images/albums/{{ $album->cover }}" class="card-img img-responsive" alt="" height="280" width="356">
                <p class="text-muted text-center"><em>{{ ucfirst($album->description) }}</em></p>
            </div>

        @endforeach

    @endif

</div>
07 Sep
1 year ago

elo left a reply on How To Update IsApprove Value In Database Upon Clicking Approve Button?

@chim3y Were you able to find an answer to your question?

elo left a reply on How Do I Display The Value Of Count() Inside Blade View?

Solved it. Forget to share the variable when returning the view. Time for a break

elo started a new conversation How Do I Display The Value Of Count() Inside Blade View?

I feel like I will be kicking myself for asking this question but I just can't seem to figure it out. What I'm trying to do is count the value of a collection right inside a blade view and display the result at the same time. Here's the simple code I have written controller

$pendingMembers = Member::where('status', '=', null)->get();

That result contains data as i can see array when i die and dump it. blade view

<div class="mr-5">
                        
{{ $pendingMembers->count() }} Pending
                        
</div>

This returns the error

Undefined variable: pendingMembers

So how is it done?

01 Sep
1 year ago

elo left a reply on Class 'Carbon\carbon' Not Found In Web.php

@Robert-Jan Thanks, I will make that correction. However I got it to work by renaming the config.php file in bootstrap/cache/ path. Based on what I learnt, it looks like the route path on my local server were cached. I would love to know it this is the best way to fix this issue though.

elo started a new conversation Class 'Carbon\carbon' Not Found In Web.php

Hi, I'm working with Laravel 5.4 and my app works perfectly on my local system. As part of my development, I'm testing how to deploy laravel on shared hosting (though i have read that VPS is recommended). I have followed the steps here

[http://novate.co.uk/deploy-laravel-5-on-shared-hosting-from-heart-internet/]

and looks like I'm almost there but I get the error Class 'Carbon\carbon' not found in web.php

This is the line throwing up the error

<?php
use Carbon\carbon;

Route::get('/', function () {
    
    $today = Carbon::now()->toDateString();

    //dd($today);

    $prices = App\Price::with('product')->whereDate('date', $today)->get();

    return view('welcome', compact('prices'));
});

What am I doing wrong?

30 Aug
1 year ago

elo started a new conversation What Is The Best Way To Handle Html Returned From Guzzle GetBody() Function

I'm trying to grab current oil price from a site and so far my code has returned the entire html of the page. I'm working with Guzzle and here is the code i have written and part of the html returned

<?php 

require 'vendor\autoload.php';
use GuzzleHttp\Client;


$prices = new Client();

$response = $prices->request(
    'GET',
    'http://oilprice.com/oil-price-charts',
    [
        'body' => 'WTI Crude'
    ]
);

/*$prices = GuzzleHttp\Psr7\parse_body($response->getBody());
foreach ($prices as $price) {
    if (array_key_exists('Futures & Indexes', $price)) {
        echo $price['Futures & Indexes'];
    }
}*/

echo $response->getBody();

`

<table class="oilprices__table" data-id="1">
  <tr class="thead">
    <th class="flag_holder"></th>
    <th>Futures & Indexes<span class="section_update_text"></span></th>
    <th>Last</th>
    <th>Change</th>
    <th>%Change</th>
  </tr>

  <tbody class='row_holder'>
  <tr class='stripe show_graph' data-id='45'>
    <td class='flag_holder'><img class='flag' src='http://cdn.oilprice.com/a/img/flags/flag_image/small/usa.png'></td>
    <td>WTI Crude</td>
    <td>46.07</td>
    <td class='change_down'>-0.37</td>
    <td class='change_down_percent'>-0.8%<span class='blend_update_text'>(14 minutes delay)</span></td>
  </tr>
  <tr class='stripe show_graph' data-id='46'>
    <td class='flag_holder'><img class='flag' src='http://cdn.oilprice.com/a/img/flags/flag_image/small/7533e5804c93632e2296caf7ed04b1ff.png'></td><td>Brent Crude</td>
    <td>51.16</td>
    <td class='change_down'>-0.50</td>
    <td class='change_down_percent'>-0.97%<span class='blend_update_text'>(14 minutes delay)</span></td>
  </tr>
  <tr class='stripe show_graph' data-id='50'>
    <td class='flag_holder'><img class='flag' src='http://cdn.oilprice.com/a/img/flags/flag_image/small/468ba2a47c953eef9c5aa50f4ba1b46c.png'></td>
    <td>Mars US</td>
    <td>47.39</td>
    <td class='change_up'>+0.66</td><td class='change_up_percent'>+1.41%<span class='blend_update_text'>(11 hours delay)</span></td>
  </tr>
  <tr class='stripe show_graph' data-id='29'>
    <td class='flag_holder'><img class='flag' src='http://cdn.oilprice.com/a/img/flags/flag_image/small/f255096d3073714e1a54d91c58bf84d8.png'></td>
    <td>Opec Basket</td>
    <td>49.86</td>
    <td class='change_down'>-0.07</td><td class='change_down_percent'>-0.14%<span class='blend_update_text'>(EOD)</span></td>
  </tr>
</table>
` I'm clueless at the moment, wondering how i can get each product name and corresponding price. What's the best possible way to do this inside a laravel 5.4 project?
11 Aug
1 year ago

elo left a reply on Property [date] Does Not Exist On This Collection Instance

@rumm.an problem solved, thanks to your solution. If you have the time, please drop a note for those of us learning so we understand better what we were doing wrong. Cheers

elo left a reply on Property [date] Does Not Exist On This Collection Instance

@Snapey @rumm.an this is the result of my code so far http://imgur.com/p2f1VJI but what i want is to have the cost of the products displayed for each date.