Robstar

at F9 Web Ltd.

Hire Me

Experience

25,410

4 Best Reply Awards

  • Member Since 3 Years Ago
  • 272 Lessons Completed
  • 1 Favorite

15th August, 2017

Robstar left a reply on Getting All Rows From The DB Into An Array • 1 week ago

The findOrFail() returns the first result only or throws an exception. See https://laravel.com/docs/5.4/eloquent#retrieving-single-models

As ypou

10th August, 2017

Robstar left a reply on Add/Update Cache Control Metadata On S3 Objects • 1 week ago

@Laraveldeep Have just noticed you said you need to do this for thousands of files. If that's the case use the aws-cli - it's quicker and cheaper than individual request from your application.

Robstar left a reply on Passing DB To Blade Template • 1 week ago

Back on topic, you at least need to show us (within proper code blocks) relevant Controllers and anything else relevant like View Composers.

I'm not use if the following will work, but it will helps show you what data is available to Blade:

{{ dd(get_defined_vars()['__data']) }}

However, it's probably easier to just show us the controller where you're creating all the variables in question.

Robstar left a reply on Passing DB To Blade Template • 1 week ago

@PolMac - I think @tykus means place code within code blocks :)

8th August, 2017

Robstar left a reply on Add/Update Cache Control Metadata On S3 Objects • 2 weeks ago

I've only recently discovered that the following works:

's3' => [
            'driver' => 's3',
            'key' => env('AWS_KEY'),
            'secret' => env('AWS_SECRET'),
            'region' => env('AWS_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'options' => [
                'CacheControl' => 'max_age=31536000'
            ],
        ],

Robstar left a reply on Unique Validation For Translation Table • 2 weeks ago

Sounds like it'd be quicker to create your own validation rile. See https://laravel.com/docs/5.4/validation#custom-validation-rules

7th August, 2017

Robstar left a reply on Validate Validation Rules • 2 weeks ago

I'm over thinking it probably. For the time being I'll just catch the exception without using form requests. There must be a way to do this though :/

6th August, 2017

Robstar left a reply on Validate Validation Rules • 2 weeks ago

@Snapey I can do this and catch the error:

try {
    $this->validate(request(), [
        'value' => 'email|kjdsafhkjsahdfk|string'
     ]);
} catch (\BadMethodCallException $ex) {
    // Bad rules string
}

However, that only works in the controller and not in my form request class as I'd like. It's certainly a start as it stops my app from blowing up :)

Robstar left a reply on Validate Validation Rules • 2 weeks ago

@jlrdw Yep, I know, hence the thread :)

Robstar left a reply on Validate Validation Rules • 2 weeks ago

@Snapey If you follow the validation service provider & look for the validateAttribute function, it's not immediately obvious how I'd catch the exception thrown.

There isn't really the time to implement a UI for this - maybe in the next round of changes.

Robstar left a reply on Validate Validation Rules • 2 weeks ago

Within the FormRequest:

if ($this->has('rules')) {
      $rules['value'] = $this->get('rules')
}

The value field is the the setting value.

It's very flaky as it's entirely reliant upon the user entering in valid, validation rules. I don't trust the client :)

Robstar left a reply on Using Mailgun Inbound Email Routing • 2 weeks ago

I believe Mailgun send attachments as a multipart file.

For each attachment there should be a url similar to https://api.mailgun.net/v2/domains/<<<YOUR_DOMAIN>>>>/messages/<<LONG_STRING>>>/attachments/0 that conatins the file. Note you'll need to use your Mailgun API credentials to access this url as it is password protected.

Mailgun allows you to attach custom keys and values to each message. See https://documentation.mailgun.com/en/latest/user_manual.html#attaching-data-to-messages

Why not use a key titled something like attachment-NUMBER with the value being the full path http://site.co.uk/file.png (or say the AWS s3 path).

Have you tried bin.mailgun.net? It's very useful for web hooks which are annoying to debug. See http://blog.mailgun.com/product-update-new-postbin-for-debugging-webhooks/

Robstar left a reply on How To Save Dynamic Input Data Into Database As Json ? • 2 weeks ago

You could store the raw JSon object using the newer json column type in Mysql. However, the best course is to store each record in a related table.

Robstar started a new conversation Validate Validation Rules • 2 weeks ago

So, I have a client that's been reading about Laravel validation rules.

They currently have a settings screen that manages a very basic store of keys and values. i.e. "max free samples" = 10, "login attempts" = 5 etc.

They came up with a pretty interesting idea.

For each setting, they'd like to use any of the Laravel built in rules and type these in themselves. Now, when they create a setting they'd enter the key, value and populate a rules field. i.e.

Key = Max of something
Value = 100
Rules = required|integer|max:500

I've already implemented this and everything works. However, at the moment it's very dependent upon the client following the Larvel Docs. If they were to enter in a invalid rules a BadMethodCall exception is thrown - which due to the fact I'm using form requests and the way the Validation instance is bound to the ioc, isn't immediately obvious how I can catch this.

To save some time, is anyone aware of a good package that can validate the validation rules. i.e. required|email would be valid, whereas requireddd|asijdha would of course be invalid. There is also the issues of rules with parameters like between:10,20.

Thanks

3rd August, 2017

Robstar left a reply on Call To Undefined Method Laravel\Section::_start() • 2 weeks ago

Try clearing your view cache: php artisan view:clear.

In these situations it's always worthwhile running a command along the lines of the following too:

php artisan cache:clear && php artisan clear-compiled && php artisan config:cache && php artisan route:cache && php artisan optimize

Robstar left a reply on Laravel 5 Password Reset Not Working • 2 weeks ago

For me the password reset form was working and generating a new password.

However, I was unable to login using the password I set. I'm sure there's a better fix than this, but here is my "solution". The issue was that the password being "bcrypted" twice - once by the Eloquent mutator on the user model and once via the "resetPassword" method at Illuminate\Foundation\Auth.

Override the method "resetPassword" in your own reset controller. Change it from:

protected function resetPassword($user, $password)
    {
        $user->forceFill([
            'password' => bcrypt($password),
            'remember_token' => str_random(60),
        ])->save();

        $this->guard()->login($user);
    }

to

protected function resetPassword($user, $password)
    {
        $user->forceFill([
            'password' => $password,
            'remember_token' => str_random(60),
        ])->save();

        $this->guard()->login($user);
    }

13th July, 2017

Robstar left a reply on Adapting Font Type And Size In Text Boces • 1 month ago

Are you using the SAAS or flat CSS version of Bootstrap? If the former, you'd simply need to change a SAAS variable.

10th July, 2017

Robstar left a reply on Problem In Updating Data Into Mysql • 1 month ago

Assuming your database structure and models are setup correctly, try to isolate the problem. For example, does the following work:

$validIdFromYourDatabase = 1;
$crud = Category::find($validIdFromYourDatabase);
$crud->name = 'Hardcoded name';
$crud->status = 1;
$crud->save();

Also, add a method to your form html i.e:

<form method="POST" ....

Robstar left a reply on How To Find The Correct Path To Download File In Laravel • 1 month ago

As you're using the public disk driver you need to symlink by running php artisan storage:link

See https://laravel.com/docs/5.4/filesystem#the-public-disk

You can then reference your file via asset('storage/file.txt')

Robstar left a reply on Problem In Updating Data Into Mysql • 1 month ago

You really need to give us more to go on if you expect any form of useful reply :) At the very least, show us your code and database structure. Were there any errors etc.

For future reference I'd recommend reading https://stackoverflow.com/help/how-to-ask :)

Robstar left a reply on How To Block When Someone Paste A Link From My Api • 1 month ago

@coustas Then the simplest way is token auth. If using Lumen it takes a few moments at most to setup.

When setup, the user would need to pass a header, containing an API token (i.e. from your users table) to use the endpoint. If finer grain control is required then you'd need to use permissions/roles for the auth'd user.

9th July, 2017

Robstar left a reply on How To Block When Someone Paste A Link From My Api • 1 month ago

Implement user permissions/roles. Alternatively you can get basic token authentication up an running in a couple of minutes with Lumen. See https://github.com/laravel/lumen/blob/master/app/Providers/AuthServiceProvider.php#L33

Robstar left a reply on Place To Write Laravel RAW Queries? • 1 month ago

@jlrdw Meh, as with anything it depends :)

If I had lots of complex logic, for myself that makes sense to be placed into a separate class for organisation and ease of re-use.

Robstar left a reply on Get Just Few Records By Eloquent • 1 month ago

You need to assign the query to a variable:

$posts = $user->posts()->orderBy('id', 'DESC')->take(3)->get();
// $posts can now be used within the view

Robstar left a reply on How To Reduce Amount Of Queries • 1 month ago

@freel Have a look into eager loading too.

Robstar left a reply on Place To Write Laravel RAW Queries? • 1 month ago

@jlrdw For me, that logic doesn't belong in the controller, especially if the project is large as @pasha alludes.

Robstar left a reply on Export A PDF Document Under PHP 7.1 • 1 month ago

It looks like the bug wasn't with maatwebsite\excel, it was actually with the underlying package it uses i.e. PHPOffice/PHPExcel, which has apparently been fixed. This fix hasn't been applied to the package yet according to https://github.com/Maatwebsite/Laravel-Excel/issues/1041

Have you tried using https://github.com/PHPOffice/PHPExcel directly? There is some documentation at https://github.com/PHPOffice/PHPExcel/tree/develop/Documentation/markdown/Overview

Robstar left a reply on Wrapping Validation Errors In 'data' • 1 month ago

@joshgallagher24 IF using form requests you can customize the error format by overriding the formatErrors() function.

See https://laravel.com/docs/5.4/validation#customizing-the-error-format

Robstar left a reply on Securing API In Lumen • 1 month ago

What happens exactly? Did you note any errors in the log and/or on screen?

Some observations:

  • I always prefer to return a valid user instance from the auth service provider, based upon the token i.e:
public function boot()
    {
        // Here you may define how you wish users to be authenticated for your Lumen
        // application. The callback which receives the incoming request instance
        // should return either a User instance or null. You're free to obtain
        // the User instance via an API token or any other method necessary.

        $this->app['auth']->viaRequest('api', function ($request) {
            $token= $request->header('Api-Token');

           User::query()
                    ->whereApiToken($token)
                    ->first(); 
        });
    }

Also, are you passing the token via Postman as a proper header, as opposed to via the query string? Try hard coding in a valid api token in your service provider - does registration work now?

I'm guessing a little here as you have particularly provided much for me to go on :)

Robstar left a reply on Eloquent Won't Return What Is In The Database • 1 month ago

What output do you get if you run the following in your controller?

dd( \App\Models\User::with('p')->find(2) );

Robstar left a reply on Place To Write Laravel RAW Queries? • 1 month ago

They could go in the repository. Alternatively you could use custom classes as Jeffery does in his tutorials (I can't find the exact video, but I've definitely seen this mentioned in the TDD forum series). Essentially you have dedicated classes to house complex queries. i.e. \App\Queries\SomeUsefulNameQuery.php etc.

Robstar left a reply on New Laravel Exception Page? • 1 month ago

@whereisjefe I believe the old handler was removed a few years ago and replaced with the default Symfony error handler. IIRC there was some Github drama with whoops breaking the framework (https://github.com/laravel/framework/pull/4378). I'm not sure why the new handler was brought in.

Robstar left a reply on Best Practice To Initiate Object • 1 month ago

The FixtureMatrixGenerator class has x2 dependencies that are missing when you init the class in the way you have.

After binding your custom class (see https://laravel.com/docs/5.4/container#binding-basics) to the container, you can resolve it as so:

use App\Libraries\Generators\FixtureMatrixGenerator;

$leagueMatrixGenerator = resolve(FixtureMatrixGenerator::class);

Robstar left a reply on Dropdown From Database Using Html Classes • 1 month ago

If using the Laravel Collective package, you'd just do the following in your controller:

$sizes = ['L' => 'Large', 'S' => 'Small'];

return view('my.view', ['sizes' => $sizes]);

In your template:

{!! Form::select('size', $sizes) !!}

Robstar left a reply on New Laravel Exception Page? • 1 month ago

You're seeing the new default error handler. What does the source for User.php look like?

Typically you'll have imported a class incorrectly. Are your imports (i.e. "use" statements) at the top of the file?

Robstar left a reply on Generate Random Id From Auto Increment • 1 month ago

If you're keeping the primary key as an integer and simply want to create a random token when a user is being created, I'd advise Observers. See https://laravel.com/docs/5.4/eloquent#observers

You observer class would have a simple method that is fired after the model is created:

public function creating(User $user)
{
$user->token = str_random(20);
}

Robstar left a reply on API - GET Request With An Email As Parameter • 1 month ago

This depends upon how you've defined your "EagleModel" and what the value of the $cx_email_addr_lookup_key variable is. $cx_email_addr_lookup_key should be the id of the record you require.

Just a quick tip, you could improve that method somewhat by using "route model binding" - see https://laravel.com/docs/5.4/routing#route-model-binding

This would allow your showContact() method to be as follows:

public function showContact(EagleModel $eagle)
{
// You have the $eagle variable to work with
}


6th July, 2017

Robstar left a reply on Issues With Uploading To AWS S3 • 1 month ago

This oddly happened to me this morning out of the blue. I just pulled in all my composer dependencies from scratch, which solved the issue for myself.

Robstar left a reply on Import Excel File To Database With Mapping Each Field Dynamicaly • 1 month ago

If you're referring to the column titles being different than you model than you'll need some form of helper class. i.e. the excel column could be the key and the eloquent column as the key:

$map = [
    'Name' => 'product_title',
    'Age' => 'product_age_in_days'
    // etc.
];

You can then use this to determine data when reading the rows.

To read the Excel file have a look at http://www.maatwebsite.nl/laravel-excel/docs/import - most importantly it doesn;t load the entire file into memory. You can enable cell caching and use the "chunking" feature.

Robstar left a reply on Unable To Continue Working • 1 month ago

Definitely don;t work 16 hrs a day. That's simply not sustainable. I find writing a big list of tasks at the start of the project helps.

Then as I complete tasks or stages I mark them off the list. This is oddly motivating and keeps me on track.

Robstar left a reply on User Delete With Modal • 1 month ago

For the button, don't link directly to the url. Create a button that opens a modal. i.e.

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Delete
</button>

The button will open the below modal:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Delete Record</button>
      </div>
    </div>
  </div>
</div>

You could add a form into the modal-body element, when the user click the "Delete Record" button, you could use JavaScript to submit the form.

Note you'll need to fake a "DELETE" form method.

As the modal is a simple confirmation box, I prefer to use Sweet Alert 2 at https://limonte.github.io/sweetalert2/

Robstar left a reply on Order By Field • 1 month ago

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.