ronon

ronon

Member Since 2 Years Ago

Experience Points 23,870
Experience Level 5

1,130 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 192
Lessons
Completed
Best Reply Awards 1
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.

11 Jul
1 week ago

ronon left a reply on Upload A File To A Model ID Subdir

I took a look at the nova documentation and you need to some customization as well. https://nova.laravel.com/docs/2.0/resources/file-fields.html#customization

Also I guess you can create your own field type, which fits your needs.

08 Jul
2 weeks ago

ronon left a reply on Problem With Exec() Within Laravel App

Check the file permissions. If you use nginx as webserver, it normally runs with the user www-data.

I guess you're connected as root in your terminal and root can access all files, so it works. If those file only have root permissions, any other user cannot access it.

Change it, so laravel "see's" it. chown -R www-data:www-data /Users/robert/Sites/start-app

I assume that your using a linux based operation system.

ronon left a reply on How To Add Row Number In Resource?

What exactly do you mean with row number? What do you want to achieve with it?

ronon left a reply on Upload A File To A Model ID Subdir

I have never used Nova, but without it, you have access to the database and can get ID from it.

Why should you want to queue Uploads? You should handle them directly after the upload (store them properly) and if you have verified that it's successfull, you can create a job with the file path and do what ever you want with it.

Why don't you fetch the model ID there and store it in the correct directory? Sth. like: UNTESTED Code! Just to give you an idea how to handle it.

// Get the model from the database, if not create it
$model = Model::where('id', $id)->first();

if(is_null($model)){
    $model = Model::create(['your' => 'data']);
}

$dir = storage_path('media/{yourID}');
if(!Storage::exists($dir)){
    mkdir($dir);
}

$path = Storage::putFile('media/{YourID}',  $request->file('file'));

You can also set the model ID in your form

<input type="text" value="{{ $model->id }}" name="model_id">
$model_id = $request->input('model_id');

Since you don't provide any more details, thats the best I can suggest. For more help, provide more details.

28 Jun
3 weeks ago

ronon left a reply on Get The Currently Active Queue Workers

That is exactly my setup, the issue i have: I don't know if the worker is doing something. I implemented a small workarround, so I increment a key in the handle and decrement it after the function. Don't think it's ideal, but i guess you cannot tell if a worker is processing sth?!?

25 Jun
4 weeks ago

ronon started a new conversation Get The Currently Active Queue Workers

I have app server who do a specific task, for example. Download a file from another server. Since this task can take some time i use supervisor with queues.

The flow is like: A command (cron) checks every minute if there is a new file that should be processed. If so add it to the queue. A queue worker will get it from the queue and process it.

Since i want to limit the amount of concurrence downloads i need to somehow check how many queue workers are currently active.

Is there a way to get the active queue workers?

12 Jun
1 month ago

ronon started a new conversation Queue Worker Seems To Timeout

Hi, we're encoding video at our plattform, but the issue is that the queue worker time out sometimes altough we set the timelimit in the supervisor config to 0.

Our supervisor worker

[program:encoding-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/artisan queue:work --queue=encoding --sleep=10 --tries=1 --timeout=0
autostart=true
autorestart=true
user=apache
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/html/storage/logs/encoding-worker.log

We're using https://github.com/PHP-FFMpeg/PHP-FFMpeg to encode the videos. We also set the timeout to about 6 hours there to be sure it won't timeout.

The log just tells:

Encoding job failed App\Jobs\ProcessVideo has been attempted too many times or run too long. The job may have previously timed out.

What are we missing? How can we debug this issue further?

30 May
1 month ago

ronon started a new conversation Create Custom Package

I want to create a package for omnipay but I struggle to find out how to include that.

I use laravel so I created a folder app\omnipay\nameofpaymentprovider

Also i created a composer.json

{
    "name": "omnipay/nameofpaymentprovider",
    "type": "library",
    "description": "nameofpaymentprovider driver for the Omnipay payment processing library",
    "autoload": {
        "psr-4": { "Omnipay\Nameofpaymentprovider\" : "src/" }
    },
    "require": {
        "omnipay/common": "^3"
    },
    "require-dev": {
        "omnipay/tests": "^3",
        "squizlabs/php_codesniffer": "^3",
        "phpro/grumphp": "^0.14"
    },
    "extra": {
    },
    "prefer-stable": true
}

But its not recognised anywhere. I placed it inside the app directory since i asumed that

 "autoload": {
        "psr-4": {
            "App\": "app/"
        },
    },

in the main composer.json would include it. But I guess I was wrong. So how can I fix it?

27 May
1 month ago

ronon started a new conversation Manage Multiple Queues From Different Servers

We have many servers which executes long running tasks. For this we use queues and supervisor. Any server has it's own queue. As queue driver we're using beanstalkd.

Is it possible to use a queue management system like laravel horizon, beanstalkd-ui-admin, etc. to manage those multiple queues from a single server?

Also is it a bad approach that every server has it's own beanstalkd instance? Or should we go with only one instance on one server where all servers fetches it's job from?

The server gets the job over a http request and dispatches it on it's queue.

06 May
2 months ago

ronon left a reply on One To One Relationship

InventoryJob hasOne SubJob

SubJob belongsTo InventoryJob

21 Apr
3 months ago

ronon left a reply on Why Does \Log Not Work In Jobs

\Log::info(); Log::debug() are working in jobs. Make sure that if you use Linux thtat your files have the same owner as the webserver is running under, e.g. www-data.

It doesn't has to do with what for a QUEUE_DRIVER you're using

16 Apr
3 months ago

ronon started a new conversation Queue Retry: Failed Method Executed But Job Is Active

It can happen that a long running job fail. We're talking about an encoding job which can run longer than 30+ minutes. So I configured the supervisor with the --timeout=0 option.

Now I wrote an endpoint to restart a failed job. It basically calls the artisan command:

 Artisan::call('queue:retry', [
                    'id' => $job->id
                ]);

So far so good, the job is also restarted.

But now the weird things are happening. After approx 30 secs the failed method in my job is called

 /**
     * The job failed to process.
     *
     * @param  Exception  $exception
     * @return void
     */
    public function failed(Exception $exception)
    {
       // Update some values in the db
        Log::debug('Job failed '. $exception->getMessage());
   }

The message from the log: ProcessVideo has been attempted too many times or run too long. The job may have previously timed out. Since retry resets the attempts, I guess it's thrown because of a timeout exception?!?

But here it gets really weird. With htop I can still see the job running through supervisor. All values are updated as expected like if it wasn't cancelled.

So why is the failed job method called but the job itself is still active? How can I prevent this behaviour?

02 Apr
3 months ago

ronon left a reply on One To One Relationship

If you're sure that in no case the InventoryJob can has multiple childs, go for the One to One relation, else you need to go for the One to Many

ronon left a reply on Accessing Localhost From My Iphone?

You need to setup a webserver on your MacBook to achieve this.

ronon left a reply on How Do I Find Out How Many Times

The LIKE operator matches everything that contais Dram. So it's not possible to achieve the behaviour you want with your design. In your design your categories are not allowed to be similiar to another categories name.

The only way you can solve this is using a Many-To-Many relation. You will then have 3 tables: posts, categories and category_post. category_post will look sth like this:

post_id | category_id

Make sure you use a unqiue ID on that, else it can happen that a post has the same category more than once.

So later you can do:

$post = Post::first();
$post->categories()->count();

ronon started a new conversation Beanstalk Create New Tube?

Since the servers are running different long running processes I'm use beanstalkd queue. To prevent a server fetching all jobs i'm want to check the size of the queue with:

Queue::size('audio');

and

Queue::size('video');

but I receive this error:

 Pheanstalk\Exception\ServerException  : Server reported NOT_FOUND

  at /var/www/html/laravel/vendor/pda/pheanstalk/src/YamlResponseParser.php:37
    33|      */
    34|     public function parseResponse($responseLine, $responseData)
    35|     {
    36|         if ($responseLine == Response::RESPONSE_NOT_FOUND) {
  > 37|             throw new Exception\ServerException(sprintf(
    38|                 'Server reported %s',
    39|                 $responseLine
    40|             ));
    41|         }

  Exception trace:

  1   Pheanstalk\YamlResponseParser::parseResponse("NOT_FOUND")
      /var/www/html/laravel/vendor/pda/pheanstalk/src/Connection.php:145

  2   Pheanstalk\Connection::dispatchCommand(Object(Pheanstalk\Command\StatsTubeCommand))
      /var/www/html/laravel/vendor/pda/pheanstalk/src/Pheanstalk.php:395

  Please use the argument -v to see more details.

I push to queue with this this command:

ProcessAudio::dispatch($audio)->onQueue('audio');

and

ProcessVideo::dispatch($video)->onQueue('video');

I use beanstalkd Admin UI to monitor the queues and it shows that the audio queue doesn't exists, but the video queue does.

I guess the video queue exists, since i tried it a few times before I added the method to check the queue size?!?

So how do I create a new tube and prevent this error? I know that I could use a try catch but that seems like a bad approch imho.

01 Apr
3 months ago

ronon left a reply on Installing Laravel In A Subdirectory - Images Not Showing

Why don't you use the location setting of your webserver? For example if you use nginx:

location ~ /subfolder { root /path/to/your/second/laravel/installation; }

and add the other neccessary stuff.

Is using a subdomain not an option at all?

ronon left a reply on Remember The Owner Of An Uploaded File Without Force Him To Sign In?

I would go with a cookie. User visits your site -> set cookie with an unique id. User uploads documents -> use that id and prefix the filenames. User registers -> Parse the files and assign the user to it.

Note: Any client side method may break if the user uses private sessions or things like NoScript

ronon left a reply on How Do I Find Out How Many Times

I guess the type of post_categories is text? If so use LIKE. WHERE post_categories LIKE '%$yourValue%'

But you should better use an One-To-Many relation, since the categories are going to be repeated https://laravel.com/docs/5.8/eloquent-relationships#one-to-many

ronon started a new conversation Avoid Race Condition. Best Way To Lock Resource?

I have a multi server setup where some server have specific tasks. A server can get a new task through an endpoint. /api/task

Since the tasks are fetched through cronjobs, it can happen that some servers are trying to fetch a new task at the same time. Since I need to do many database requests and some calculation this process can take some time. So I thought of using some kind of lock to prevent incorrect values in the database and accidentailly assigning a job to more than one server.

Should I go for Database transaction or should i better use a variable stored in the cache, or any other approach?

ronon left a reply on How Do I Find Out How Many Times

First of all your images aren't working.

Next: So you want to count the occurences of a specific category name in nother table? Your query needs to look like similiar to this

SELECT count(*) FROM posts WHERE category_name = 'yourCategoryValue';
15 Mar
4 months ago

ronon left a reply on Relationship Null In Console

That doesn't matter. The model is loaded correctly no matter how i do it, the relation won't load! As already mentioned i broke it down to the point where it's not working.

ronon left a reply on Relationship Null In Console

@snapey i broke it down to the part what's not working and forgot to add the where('slug', $slug) part. But that also won't explain why it's working in browser but not from console

14 Mar
4 months ago

ronon left a reply on Relationship Null In Console

@CRONIX - Yes. If i run it with through web, it also works as expected. It just won't work if i try it from console.

ronon left a reply on Relationship Null In Console

@snapey updated the post, but i guess it will not help.

ronon started a new conversation Relationship Null In Console

I need to load relationships on a command.

The problem is that it's always null.

I tried it with with('myrelation') and load('myrelation') but it's always empty. Running it from browser the relationship is available.

Why the heck is it null? I don't get it

13 Mar
4 months ago

ronon left a reply on Ajax Not Posting Data. What Am I Doing Wrong?

@stereoh you're right my fault

@behnampmdg3

Don't know which jQuery versino you're using, but success has been removed in 3.0. Also your success aproach looks wrong for me.

Try

                $.ajax({
                    method: "POST",
                    url: "{{ url('/lessons') }}",
                    data: {
                        name: jQuery('#title').val(),
                        description: jQuery('#description').val(),
                        title: jQuery('#title').val(),
                        release_after: jQuery('#release_after').val()
                    }
                })
                    .done(function( msg ) {
                        jQuery('.add_lesson_box').hide();
                        jQuery('.alert').html(result.success);
                    });

ronon left a reply on Ajax Not Posting Data. What Am I Doing Wrong?

You never fall the ajax part

You closedthe click function before tue ajax part

26 Feb
4 months ago

ronon started a new conversation Best Way To Assign The Disabled Tag To Input Values

I need to assign the disabled tag on multiple values depending on a entry on the ´user´ model.

What's would be the best way to do that without writing this peace of code over and over again on every input field?

{{ Auth::user()->disabled ? 'disabled' : '' }}

Ideas I came up with are: Create a Blade::directive and Create a view where it contains the logic and import it on every view.

I'm not sure if those two ways are good ones. Sp what would be the best way to do this?

06 Feb
5 months ago

ronon left a reply on Control Number Of Queue Workers With A Value From Config

I would like to control the amount of running encoding processes on each app server from the main server. So I need some sort of control of the supervisor and/or the queue. Or any other idea how to solve it

ronon started a new conversation Control Number Of Queue Workers With A Value From Config

Is it possible to control the number queue workers with a value from the config file? E.g. run 3 workers.

We are using ffmpeg to convert video files. This are long running tasks. I thought of using laravel queues with supervisor to deal with it, but as mentioned, it has to be controlable how many ffmpeg processes should run at the same time.

Is it possible to archive this behavior with Laravel and queues?

If not do you have any recommendations how we can solve this issues?

04 Jan
6 months ago

ronon left a reply on ToCustomChannelName Not Called

@d9705996 You're totally right. Don't know how i could overread that. Thanks!!! :)

ronon started a new conversation ToCustomChannelName Not Called

We're using FirebaseCloudMessaging to push notifications to our android app. For this we use https://github.com/brozot/Laravel-FCM .

Now i wrote a channel to handle the stuff, but the toFirebaseCloudMessaging($notification) isn't called.

The notification file


namespace App\Notifications;

use App\Channels\FirebaseCloudMessagingChannel;
use App\Models\Message;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;

class NewMessage extends Notification
{

    /**
     * @var
     */
    protected $message;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(Message $message)
    {
        $this->message = $message;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  \App\Models\User  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [FirebaseCloudMessagingChannel::class];
    }


    public function toFirebaseCloudMessaging($notifiable)
    {
        dd('toFirebaseCloudMessaging called');
        return 'test message';
    }
}

the channel:


namespace App\Channels;

use Illuminate\Notifications\Notification;
use LaravelFCM\Facades\FCM;
use LaravelFCM\Message\OptionsBuilder;
use LaravelFCM\Message\PayloadDataBuilder;
use LaravelFCM\Message\PayloadNotificationBuilder;
use Spatie\Fractalistic\ArraySerializer;

class FirebaseCloudMessagingChannel
{


    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return void
     */
    public function send($notifiable, Notification $notification)
    {

        dd('send');
        
// Send the notification
    }
}

I call the notification like:
```php
Notification::send($users, new NewMessage($message));

but in the NewMessage class the toFirebaseCloudMessaging method isn't called. It goes directly to the send() method in the channel.

What am I doing wrong?

29 Nov
7 months ago

ronon started a new conversation Facade Not Working And Autocomplete Not Showing

I need to use youtube_dl in a project. For this i want to use this wrapper https://github.com/norkunas/youtube-dl-php, unfortunatly there is no facade available for it, so i wanted to write one on my own.

in app\Facades i created a faceade YoutubeDlFacade


namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class YoutubeDlFacade extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'youtubedl';
    }
}

I also created a ServiceProvder YoutubeDlServiceProvider.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use YoutubeDl\YoutubeDl;

class YoutubeDlServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('youtubedl', function ($app) {
            return new YoutubeDl();
        });

        $this->app->alias('youtubedl', 'YoutubeDl\YoutubeDl');
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [ 'youtubedl' ];
    }
}

I registered the ServiceProvider in the configs array. ´

Now I have two problems: First, this works:

$youtubeDl = app('youtubedl');
dd($youtubeDl->getExtractorsList());

This don't:

dd(YoutubeDl::getExtractorsList());

Here i get this error Non-static method YoutubeDl\YoutubeDl::getExtractorsList() should not be called statically

Second, i don't get the autocomplete suggestions from PHPStorm.

28 Nov
7 months ago

ronon left a reply on Convert Custom Non Eloquent Model To Json

I want to have the flexibility the Model has. So I extend from Model and call the parent constructor with the attributes array. Also I have set the fillable array to the same values as the attributes array

protected $attributes = ['title', 'content'];

public function __construct(){
    parent::_construct($this->attributes);
}

But now I get

{
  0 :  [
    [ 'title', 'content'], [ 'title', 'content'], [ 'title', 'content']]
}

Shouldn't that do the trick?

ronon started a new conversation Convert Custom Non Eloquent Model To Json

I have a custom model, which is not filled with data from the database.

class MyModel {
        /**
          * @var string
      */
    protected $title;

    // Getter and setter for it
}

I also tried to extend it extend Model but i always get an empty response.

{
  0 :  [[],[],[],[]]
}

How can I get it to work that i can use return response()->json($data).

17 Oct
9 months ago

ronon left a reply on Laravel Queue

Provide more info

09 Oct
9 months ago

ronon left a reply on Error In Integrate Bootstrap With Laravel

Remove the .../public asset('css/bootstrap.min.css')

asset('css/bootstrap.min.js')

22 Aug
11 months ago

ronon started a new conversation Trait Not Found

I have read many other threads regarding this issue, but nothing helped.

I'm using laravel 5.5 and for the passwordreset is overwrote the setPasswordAttribute function

User extends Authenticatable{
public function setPasswordAttribute($value)
    {
            $this->attributes['password'] = bcrypt($value);
    }
}

Now I had to modify the ResetPasswords file, because i had to change this line

        $user->password = Hash::make($password);

to this

$user->password = $password;

I have a folder for traits under App\Traits.

I copied the whole content from ResetsPasswords to App\Traits\ResetsPasswordTrait and modified the line

<?php

namespace App\Traits;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Foundation\Auth\RedirectsUsers;

trait ResetsPasswordsTrait
{
    use RedirectsUsers;

    [...]

    /**
     * Reset the given user's password.
     *
     * @param  \Illuminate\Contracts\Auth\CanResetPassword  $user
     * @param  string  $password
     * @return void
     */
    protected function resetPassword($user, $password)
    {
        $user->password = $password;

        $user->setRememberToken(Str::random(60));

        $user->save();

        event(new PasswordReset($user));

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

[...]
}

I updated the trait in ResetPasswordController

<?php

namespace App\Http\Controllers\Auth;

use App\Traits\ResetsPasswordsTrait;
use App\Http\Controllers\Controller;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswordsTrait;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }
}

I have other Traits in the foler as well which are working which are working but for this one I always get a Trait not found exception. I executed composer dump-autoload and php artisan clear:cache but I cannot get rid of it. What's wrong with my code?

14 Aug
11 months ago

ronon left a reply on Change Form Of Address Efficiently

Thats not what I'm looking for. The authorization is working as it should. I have many parts where I need to change the phrase the user sees depending on if the user is visiting his own profile or not. I think it's suboptimal to do it like

if(auth->id == $user->id)
  print this
else 
    print that

those checks in the blade files is getting too much, need to refactor it to a better way to do it

ronon started a new conversation Change Form Of Address Efficiently

I need to change the form of address depending if the owner is visiting his profile or if anyone else is visiting it.

Is there a better way than do it like

@if(auth()->id() === $user->id)
       Your friends
@else
    Friends of $user->name
@endif 

The string are located in language files.

I thought of an one liner, maybe like

echo getFormOfAddress('string for owner', 'string for foreigners', $user(?));

function getFormOfAddress($owner, $foreigner, $visitedUser){
    return ($visitedUser->id === auth()->id()) ? $owner : $foreigner;
}

but i guess there might be a better way to do it with laravel where i'm not aware of.

Maybe someone knows a better solution for it :)

16 Jul
1 year ago

ronon started a new conversation Override Can Policy Response

I use Policies to check if an user has the permission to perform an action. For the api endpoint I need to put that response in a specific format.

If a user who is not allowed to view messages for a message Route::get('/{message}/messages', '[email protected]')->middleware('can:view,message')

it throws a 403 error.

But I need to have it as a json ouput like:

{
    error: true,
    msg: 'Unauthorized'
}

How can I override it?

24 Jun
1 year ago

ronon started a new conversation Log In Scheduled Tasks Breaks API. Only Log From Tasks Appear In Log File

On a website i have an API api.example.com and approx. 12 scheduled tasks. Some of these tasks run once daily, others every minute or hourly. If I use Log::debug, Log::info, Log::error in one of these tasks the api endpoint breaks completly and I receive 500 - Server errors and no further error message in the logs, neither in nginx nor laravel.

The website is usable as always, but also won't write anything to the log. Only the Log:: from the tasks occur in the log.

What causes this behaviour?

I use daily logs with log_level debug.

ronon left a reply on User Session In API Response

If you use any kind of authenthication, you are authenticated. So you even don't need to use Auth::check

23 Jun
1 year ago

ronon left a reply on User Session In API Response

You can use Auth::check on the API side as well.

13 Jun
1 year ago

ronon left a reply on NPM Installing Scripts And Then Running Them On My Blade Template

the php section is the wrong way for this.

How it should work.

  1. npm install --save toastr

  2. Include in your resources/assets/js/app.js file.

  3. compile it npm run watch see https://laravel.com/docs/5.6/mix#running-mix for options like production/dev

  4. include the js file from your public/js/app.js at the end of your body.

Use it toastr.info('Are you the 6 fingered man?')

Don't forget to include the css file!

08 Jun
1 year ago

ronon started a new conversation How To Use PECL/Pear Extensions In Laravel?

I need to use pecl/pear extension in my laravel app, but I really don't have a clue how to include them the proper way.

For example this package: http://pear.php.net/package/Net_CheckIP/docs/latest/Net_CheckIP/Net_CheckIP.html

Where do I have to place the require_once "Net/CheckIP.php"; so it works in laravel?

I know that to use require_once in a controller is a nogo.

21 May
1 year ago

ronon started a new conversation Merge Two Huge Collections 10k+ Items Each, One Is An Eloquent Collection The Other An [array] Collection

I have two collection. One is an eloquent collection files and the other one is a file array converted to a collection.

I need to lookup if the file array is already in the database and append some attributes to the file array. For example if the file exists in the database, if the file was modified etc..

// create collection from files array
$collection = collect($files);

// First idea
// Chunk it, so the eqloquent collection is smaller
foreach($collection->chunk(1000) as $chunk){

      // ID list for db query
    $ids = $chunk->pluck('file_id')->toArray();
       
        $files = File::whereIn('file_id', $ids)->get();

       foreach($chunk as $file){
          
             // Here it gets tricky
             // I need to check if the file exists in the $files collection
            // I tried it with
            $found = $files->where('file_id', $file->file_id)->first();
            // But the execution time exceeds

           if(!is_null($found)){
                 // Add some values, like, etc...
                $file->existsInDb = true;
                $file->created_at = $found->created_at;
             } else {
               $file->existsInDb = false;
                $file->created_at = -1;
             }
      }

return $files;
}

file_id is type of string and unique.

How can I improve the $found = $files->where('file_id', $file->file_id)->first(); search in the collection part?

If i make a query for each File i receive an 504 Gateway Timeout, so I think the database don't like that approach.

Might there be a much better approach for this problem?

ronon left a reply on Generate Multidimensional Array From Singledimensional Array, Entry Only Nows It's Parent

@jlrdw The dataset didn't come from the database, so wasn't an option

@hjgarcia1 You brought me on the correct path. Had to do it as tree. Thanks for that :)

This solution worked for me https://stackoverflow.com/a/22020668