Tippin

Tippin

Member Since 1 Month Ago

TAMPA

Experience Points
4,640
Total
Experience

360 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
5
Lessons
Completed
Best Reply Awards
7
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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 1
4,640 XP
Apr
08
1 day ago
Activity icon

Replied to How To Get User Id In Constructor

@jinsonjose It is not recommended to try to access Auth inside the constructor of the controller, however at one point I was playing around with this, and if you MUST do it, you can reorder the session middleware to run before your web group middleware is run. Inside your Http/Kernal.php, move the session middleware from web to the global middleware, but know this means it is run for ANY request at any time through your app.

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        CheckForMaintenanceMode::class,
        ValidatePostSize::class,
        TrimStrings::class,
        ConvertEmptyStringsToNull::class,
        TrustProxies::class,

        //put session middleware here instead of web group below
        StartSession::class,
        AuthenticateSession::class,
        ShareErrorsFromSession::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            EncryptCookies::class,
            AddQueuedCookiesToResponse::class,
            VerifyCsrfToken::class,
            SubstituteBindings::class,
        ],

        'api' => [
            //\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
            'bindings'
        ],


    ];
Apr
07
2 days ago
Activity icon

Replied to Laravel Passport When Pass Bad Credential, This Error Is Show

Are you asking how to suppress the error message itself, assuming you are also getting that in your error log? If so, edit your Exceptions/Handler.php to ignore them, and you can also add the unauthenticated method to catch such errors and return your own message:

<?php

namespace App\Exceptions;

use App;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Laravel\Passport\Exceptions\OAuthServerException;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        OAuthServerException::class,
        \League\OAuth2\Server\Exception\OAuthServerException::class
    ];

    /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  Request  $request
     * @param AuthenticationException $exception
     * @return RedirectResponse|JsonResponse
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        session()->flash('info_message', 'Please login to continue');
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }
        return redirect()->guest(route('login'));
    }
Activity icon

Replied to Load Balancers

On a setup I have running I used a single wildcard flag in my trusted proxies

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = '*';

    /**
     * The headers that should be used to detect proxies.
     *
     * @var int
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

My nginx conf is as follows:

map $http_upgrade $type {
  default "web";
  websocket "ws";
}

upstream php {
    server ${PHP_SERVICE_HOST}:${PHP_SERVICE_PORT};
    server ${PHP_SERVICE_HOST}:${PHP_SERVICE_PORT} backup;
}

server {
    listen 80;
    server_name example.com www.example.com;
    client_max_body_size 50M;

    access_log /var/log/example.com.access.log;
    error_log /var/log/example.com.error.log warn;

    root /var/www/html/public/;

    # security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

    index index.html index.htm index.php;

    charset utf-8;

    #GZIP
    gzip on;
    gzip_disable "msie6";

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    location /socket.io {
        proxy_pass http://echo:6001;
        proxy_read_timeout     300;
        proxy_connect_timeout  60;
        proxy_redirect         off;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

        # Allow the use of websockets
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'Upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    location / {
        try_files /nonexistent @$type;
    }

    location @web {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }
    error_page 404 /index.php;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
        fastcgi_next_upstream error timeout;
        fastcgi_buffers 8 16k;
        fastcgi_buffer_size 32k;
        fastcgi_read_timeout 600;
        proxy_read_timeout     300;
        proxy_connect_timeout  60;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location ~ /\.(?!well-known).* {
            deny all;
    }
}
Activity icon

Replied to How To Authenticate Without Username And Password Fields?

@pratheep Just locate whatever model you want that extends Authenticatable, and call the login directly using auth facade along with a guard if you had one

$user = User::find($some_id);
Auth::guard()->login($user);
//now logged in
Activity icon

Replied to How Do I Take Data From Eager Loaded Nested Relationship?

@medala Just call the relation in the order it stems from:

$VendorOrder = VendorOrder::with('order.user')->find($id);
$email = $VendorOrder->order->user->email;
Apr
02
1 week ago
Activity icon

Replied to How To To Return User Info With His Resized Image

@mehmetanbaki Checkout http://image.intervention.io/api/resize

One example where I use that along with the Image Cache addon package to resize, and orientate:

public function makeImageThumb($file, $new_width = null, $new_height = null)
{
    $width = ($new_width ? $new_width : 200);
    $height = ($new_height ? $new_height : 200);
    return Image::cache(function($image) use($file, $width, $height){
        return $image->make($file)->resize($width, $height, function ($constraint){
            $constraint->aspectRatio();
        })->orientate();
    },120)->response();
}
Apr
01
1 week ago
Activity icon

Replied to Error In Run Scheduled Job With Cron Job And Schedule Artisan Command

https://laravel.com/docs/6.x/scheduling#defining-schedules

When you call

$schedule->call(\App\Libs\Schedules::renewLeases())->everyMinute()->runInBackground();

It expects the class alone to be injected, and the Schedules class to have __invoke magic method. You can't call the method renewLeases on the ->call() command.

Activity icon

Replied to Microsoft Azure SQL Server

Double check from your azure portal. When I switched from a pod in K8s and persistent volume for my MySQL to the Azure MySQL Service, SSL was forced, or at least enabled by default.

https://docs.microsoft.com/en-us/azure/mysql/concepts-ssl-connection-security

Activity icon

Replied to Microsoft Azure SQL Server

@thamink If you are connecting to an Azure MySQL, do you have SSL enabled? If you do, you have to export the .pem file from azure into your project and update the database.php config to point to the ssl, as well as your .env

database.php

        'mysql' => [
            'driver'    => 'mysql',
            'url'       => env('DATABASE_URL'),
            'host'      => env('DB_HOST', 'yourdatabase.com'),
            'port'      => env('DB_PORT', '3306'),
            'database'  => env('DB_DATABASE', 'DBname'),
            'username'  => env('DB_USERNAME','username'),
            'password'  => env('DB_PASSWORD', 'password'),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
            'engine'    => null,
            'modes'       => [
                'ONLY_FULL_GROUP_BY',
                'STRICT_TRANS_TABLES',
                'NO_ZERO_IN_DATE',
                'NO_ZERO_DATE',
                'ERROR_FOR_DIVISION_BY_ZERO',
                'NO_ENGINE_SUBSTITUTION',
            ],
            'sslmode' => env('DB_SSLMODE', 'prefer'),
            'options'   => (env('MYSQL_SSL')) ? [
                PDO::MYSQL_ATTR_SSL_KEY => base_path('config/ssl/YourApp.crt.pem'),
            ] : []
        ],

.env

DB_CONNECTION=mysql
DB_HOST=yourapp.mysql.database.azure.com
DB_PORT=3306
DB_DATABASE=yoursite
[email protected]
DB_PASSWORD=password
MYSQL_SSL=true
Activity icon

Awarded Best Reply on How To Catch All Exceptions In Laravel Application And Prevent Users From Seeing Bugs

@noblemfd First do as mentioned above by @buzzyburrows2 and set your environment to those, and be sure to config:cache if you use that artisan command. As far as intercepting certain errors to your own liking, you can edit the app/Exceptions/Handler.php to see what exceptions are thrown and return a custom response if you wish. Here is an example of my render and unauthenticated methods in Handler.php I have used to catch the most common errors I have faced. Note this is laravel 6, laravel 7 changed Exception to a Throwable instance.

    /**
     * Render an exception into an HTTP response.
     *
     * @param Request $request
     * @param Exception $exception
     * @return Response|JsonResponse|RedirectResponse|Redirector
     * @throws Exception
     */
    public function render($request, Exception $exception)
    {
        switch(class_basename($exception)){
            case 'TokenMismatchException':
                if ($request->expectsJson()){
                    return response()->json(['error' => 66, 'errors' => ['forms' => 'Your request was denied. Please try again or reload your page']], 403);
                }
                return redirect(route('login'))->with('modal.title', 'Session Expired!')->with('modal.msg', 'Your session expired. Please login again.');
            break;
            case 'ThrottleRequestsException':
                return response()->json(['errors' => ['forms' => 'You have been rate limited, please try again shortly']], 429);
            break;
            case 'MethodNotAllowedHttpException':
                if ($request->expectsJson()){
                    return response()->json(['errors' => ['forms' => 'Method Not Allowed']],405);
                }
                return redirect()->route('dashboard');
            break;
            case 'NotFoundHttpException':
                if ($request->expectsJson()){
                    return response()->json(['errors' => ['forms' => 'We could not locate the data you requested, it may have been lost forever']],404);
                }
                return parent::render($request, $exception);
            break;
            case 'MaintenanceModeException':
                if ($request->expectsJson()){
                    return response()->json(['errors' => ['forms' => 'The site is currently down for maintenance, please check back with us soon']],503);
                }
                return parent::render($request, $exception);
            break;
            case 'AuthenticationException':
            case 'ValidationException':
                return parent::render($request, $exception);
            break;
        }
        if (app()->isProduction()){
            if ($request->expectsJson()){
                return response()->json('Server Error',500);
            }
            return response()->view('errors.500', [], 500);
        }
        return parent::render($request, $exception);
    }

    /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  Request  $request
     * @param AuthenticationException $exception
     * @return RedirectResponse|JsonResponse
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        session()->flash('info_message', 'Please login to continue');
        if ($request->expectsJson()) {
            return response()->json(['error' => 01, 'errors' => ['forms' => 'Unauthenticated']], 401);
        }
        return redirect()->guest(route('login'));
    }
Activity icon

Replied to How To Catch All Exceptions In Laravel Application And Prevent Users From Seeing Bugs

The code I put above was the same I used when I was on laravel 5.6 up to 6.x.

Laravel 7.x is where only a small part changed (Throwable class instead of base exception class)

Mar
31
1 week ago
Activity icon

Replied to How To Catch All Exceptions In Laravel Application And Prevent Users From Seeing Bugs

@noblemfd First do as mentioned above by @buzzyburrows2 and set your environment to those, and be sure to config:cache if you use that artisan command. As far as intercepting certain errors to your own liking, you can edit the app/Exceptions/Handler.php to see what exceptions are thrown and return a custom response if you wish. Here is an example of my render and unauthenticated methods in Handler.php I have used to catch the most common errors I have faced. Note this is laravel 6, laravel 7 changed Exception to a Throwable instance.

    /**
     * Render an exception into an HTTP response.
     *
     * @param Request $request
     * @param Exception $exception
     * @return Response|JsonResponse|RedirectResponse|Redirector
     * @throws Exception
     */
    public function render($request, Exception $exception)
    {
        switch(class_basename($exception)){
            case 'TokenMismatchException':
                if ($request->expectsJson()){
                    return response()->json(['error' => 66, 'errors' => ['forms' => 'Your request was denied. Please try again or reload your page']], 403);
                }
                return redirect(route('login'))->with('modal.title', 'Session Expired!')->with('modal.msg', 'Your session expired. Please login again.');
            break;
            case 'ThrottleRequestsException':
                return response()->json(['errors' => ['forms' => 'You have been rate limited, please try again shortly']], 429);
            break;
            case 'MethodNotAllowedHttpException':
                if ($request->expectsJson()){
                    return response()->json(['errors' => ['forms' => 'Method Not Allowed']],405);
                }
                return redirect()->route('dashboard');
            break;
            case 'NotFoundHttpException':
                if ($request->expectsJson()){
                    return response()->json(['errors' => ['forms' => 'We could not locate the data you requested, it may have been lost forever']],404);
                }
                return parent::render($request, $exception);
            break;
            case 'MaintenanceModeException':
                if ($request->expectsJson()){
                    return response()->json(['errors' => ['forms' => 'The site is currently down for maintenance, please check back with us soon']],503);
                }
                return parent::render($request, $exception);
            break;
            case 'AuthenticationException':
            case 'ValidationException':
                return parent::render($request, $exception);
            break;
        }
        if (app()->isProduction()){
            if ($request->expectsJson()){
                return response()->json('Server Error',500);
            }
            return response()->view('errors.500', [], 500);
        }
        return parent::render($request, $exception);
    }

    /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  Request  $request
     * @param AuthenticationException $exception
     * @return RedirectResponse|JsonResponse
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        session()->flash('info_message', 'Please login to continue');
        if ($request->expectsJson()) {
            return response()->json(['error' => 01, 'errors' => ['forms' => 'Unauthenticated']], 401);
        }
        return redirect()->guest(route('login'));
    }
Mar
28
1 week ago
Activity icon

Replied to You Have Ventured Into 404 Space

@jlrdw Seems it would be an issue with Vue markdown. If you look at the body returned in the API response for the original post, the owner had an open a href tag, but never closed the tag (as he was pasting example from his code). Seems this bled off into the rest of the page. Here is screenshot, you can see in hover text the A tag at the end of his BODY is not closed

https://i.imgur.com/GJztRIK.png

Activity icon

Replied to You Have Ventured Into 404 Space

I noticed that as well. It seems to happen on the post :

https://laracasts.com/discuss/channels/laravel/too-few-arguments-to-function-apphttpcontrollersblogcontrollershow-0-passed-and-exactly-1-expected

I added a screenshot, you can see when hovering over reply box, it shows the "URL" in the bottom left, and goes there if you click anywhere in the reply box

https://i.imgur.com/LoNWb1e.png

Mar
25
2 weeks ago
Activity icon

Replied to How To Get Duration Date Between Two Days?

@emperor999 If you are using Carbon in your laravel app, checkout their docs using the many "diff" methods they have.

https://carbon.nesbot.com/docs/#api-difference

Activity icon

Replied to Custom Helper Not Working Correctly

@dru Try manually deleting cache files located in bootstrap/cache/(config.php services.php packages.php), then try the composer and artisan commands again. Also, what php version are you on? Seems the error you mentioned above has responses stating to update php

https://stackoverflow.com/questions/56658142/laravelsyntax-error-in-vendor-laravel-framework-src-illuminate-support-arr-php

https://laracasts.com/discuss/channels/laravel/unexpected-illuminatesupportarrphp-on-line-388

Activity icon

Awarded Best Reply on "Friendships" - Bidirectional Many-to-many Relationship

So in my own experience I chose to use two tables, pending_networks and networks. Pending is only sent by one, received by the other. But when accepted, both parties get a row in the networks table, where the owner and receiver are reversed for the two entries. The original pending is then removed from the pending table. Then I am able to query once on a model for all of their friends by getting only "networks" where they are the owner column. For pending request, the I can query the pending table if owner is yourself, so that would be sent request, and on the other end, I query where the "network" is yourself, thus you have a pending received request. I use morphs however since I implement with multiple models using a trait.

class Networks extends Model
{
    use Uuids;

    public $incrementing = false;

    public $keyType = 'string';

    protected $table = 'networks';

    protected $guarded = [];

    public function owner()
    {
        return $this->morphTo();
    }

    public function party()
    {
        return $this->morphTo();
    }
}
class PendingNetworks extends Model
{
    use Uuids;

    public $incrementing = false;

    public $keyType = 'string';

    protected $table = 'networks_pending';

    protected $guarded = [];

    public function sender()
    {
        return $this->morphTo();
    }

    public function recipient()
    {
        return $this->morphTo();
    }
}
trait Networked
{
    public function networks()
    {
        return $this->morphMany(Networks::class, 'owner');
    }

    public function pendingSentNetworks()
    {
        return $this->morphMany(PendingNetworks::class, 'sender');
    }

    public function pendingReceivedNetworks()
    {
        return $this->morphMany(PendingNetworks::class, 'recipient');
    }

    public function isNetworked($model)
    {
        return $this->networks()->where('party_id', $model->id)->where('party_type', get_class($model))->first() ? true : false;
    }

    public function isPendingNetwork($model)
    {
        return $this->pendingSentNetworks()->where('recipient_id', $model->id)->where('recipient_type', get_class($model))->first() ? true : false;
    }

    public function notApprovedNetwork($model)
    {
        return $this->pendingReceivedNetworks()->where('sender_id', $model->id)->where('sender_type', get_class($model))->first() ? true : false;
    }

    public function networkStatus($model)
    {
        if($this->isNetworked($model)){
            return 1;
        }
        if($this->isPendingNetwork($model)){
            return 2;
        }
        if($this->notApprovedNetwork($model)){
            return 3;
        }
        return 0;
    }
}
 Schema::create('networks', function (Blueprint $table) {
            $table->uuid('id');
            $table->uuid('owner_id');
            $table->string('owner_type');
            $table->uuid('party_id');
            $table->string('party_type');
            $table->timestamps();
            $table->primary('id');
        });

        Schema::create('networks_pending', function (Blueprint $table) {
            $table->uuid('id');
            $table->uuid('sender_id');
            $table->string('sender_type');
            $table->uuid('recipient_id');
            $table->string('recipient_type');
            $table->timestamps();
            $table->primary('id');
        });
Activity icon

Awarded Best Reply on Custom Helper Not Working Correctly

@dru I would not use helpers as a provider. Instead you should make a helpers.php file and tell composer to auto load it. Article I found : https://laravel-news.com/creating-helpers

Mar
24
2 weeks ago
Activity icon

Replied to Custom Helper Not Working Correctly

@dru I would not use helpers as a provider. Instead you should make a helpers.php file and tell composer to auto load it. Article I found : https://laravel-news.com/creating-helpers

Mar
22
2 weeks ago
Activity icon

Replied to "Friendships" - Bidirectional Many-to-many Relationship

So in my own experience I chose to use two tables, pending_networks and networks. Pending is only sent by one, received by the other. But when accepted, both parties get a row in the networks table, where the owner and receiver are reversed for the two entries. The original pending is then removed from the pending table. Then I am able to query once on a model for all of their friends by getting only "networks" where they are the owner column. For pending request, the I can query the pending table if owner is yourself, so that would be sent request, and on the other end, I query where the "network" is yourself, thus you have a pending received request. I use morphs however since I implement with multiple models using a trait.

class Networks extends Model
{
    use Uuids;

    public $incrementing = false;

    public $keyType = 'string';

    protected $table = 'networks';

    protected $guarded = [];

    public function owner()
    {
        return $this->morphTo();
    }

    public function party()
    {
        return $this->morphTo();
    }
}
class PendingNetworks extends Model
{
    use Uuids;

    public $incrementing = false;

    public $keyType = 'string';

    protected $table = 'networks_pending';

    protected $guarded = [];

    public function sender()
    {
        return $this->morphTo();
    }

    public function recipient()
    {
        return $this->morphTo();
    }
}
trait Networked
{
    public function networks()
    {
        return $this->morphMany(Networks::class, 'owner');
    }

    public function pendingSentNetworks()
    {
        return $this->morphMany(PendingNetworks::class, 'sender');
    }

    public function pendingReceivedNetworks()
    {
        return $this->morphMany(PendingNetworks::class, 'recipient');
    }

    public function isNetworked($model)
    {
        return $this->networks()->where('party_id', $model->id)->where('party_type', get_class($model))->first() ? true : false;
    }

    public function isPendingNetwork($model)
    {
        return $this->pendingSentNetworks()->where('recipient_id', $model->id)->where('recipient_type', get_class($model))->first() ? true : false;
    }

    public function notApprovedNetwork($model)
    {
        return $this->pendingReceivedNetworks()->where('sender_id', $model->id)->where('sender_type', get_class($model))->first() ? true : false;
    }

    public function networkStatus($model)
    {
        if($this->isNetworked($model)){
            return 1;
        }
        if($this->isPendingNetwork($model)){
            return 2;
        }
        if($this->notApprovedNetwork($model)){
            return 3;
        }
        return 0;
    }
}
 Schema::create('networks', function (Blueprint $table) {
            $table->uuid('id');
            $table->uuid('owner_id');
            $table->string('owner_type');
            $table->uuid('party_id');
            $table->string('party_type');
            $table->timestamps();
            $table->primary('id');
        });

        Schema::create('networks_pending', function (Blueprint $table) {
            $table->uuid('id');
            $table->uuid('sender_id');
            $table->string('sender_type');
            $table->uuid('recipient_id');
            $table->string('recipient_type');
            $table->timestamps();
            $table->primary('id');
        });
Mar
21
2 weeks ago
Activity icon

Replied to Where Are You All From?

Tampa, FL

XD

Mar
20
2 weeks ago
Activity icon

Replied to How To Make Button Redirect To A Page

@noblemfd

<button onclick="window.location.href='{{route('dashboard')}}'" class="bg-transparent text-grey-darkest font-bold uppercase tracking-wide py-3 px-6 border-2 border-grey-light hover:border-grey rounded-lg"> Go Home</button>
Mar
19
3 weeks ago
Activity icon

Replied to Implements ShouldQueue Not Sending Notifications

If you are using ShouldQueue, did you add the trait?

use Queueable;

Also, that means you need the artisan queue:work running to process the job on the queue

Mar
17
3 weeks ago
Activity icon

Replied to Laravel-Websockets And WebRTC RTCPeerConnection

Right now I do not have any public code I can link to from myself, as it is all local testing, but if you did choose to go that route I could show you how my backend handles it. I am working on it with someone else and it is alot to digest for sure. Janus server config itself is alot, but like anything, once it works it becomes easy.

Locally I have Janus server setup inside portainer through docker. I did have to write my own service class to handle talking to janus through the backend, as you lock certain things out like creating a room from the frontend, or having the backend clear out empty calls. Since I run everything through a firewall, I let janus use my already existing STUN/TURN servers, but it is capable of handling that itself.

My plan will be to start it on our deployment on azure, probably giving it 4 cores and 6gb ram to start, but that will end up being scaled and we will deploy more janus servers if we see limits being met. There is no real "best" way to gauge how intensive it can be, but I can link you to an article I found interesting when looking into this months back. And definitely be sure to checkout the janus FAQs as well on their site.

https://webrtchacks.com/sfu-load-testing/

https://www.slideshare.net/LorenzoMiniero/scaling-webrtc-applications-with-janus

Mar
16
3 weeks ago
Activity icon

Replied to Vapor Broadcast To Pusher

Sorry was not of much help, as I do not use Vapor. However, possibly you may find something in these docs

https://github.com/laravel/vapor-docs/blob/master/1.0/projects/environments.md

https://laravel.com/docs/5.8/upgrade#environment-variable-parsing

Be sure to see if that past change also impacts you if you have # in your key

Activity icon

Awarded Best Reply on How Can I Put Space In .env ?

Put it in quotes.

APP_NAME="MY RECIPE"
Activity icon

Replied to How Can I Put Space In .env ?

Put it in quotes.

APP_NAME="MY RECIPE"
Activity icon

Replied to Vapor Broadcast To Pusher

If you ever ran this in the past

php artisan config:cache

Then you need to run it everytime after you deploy and have new/updated config files/values.

Also double check the key name matches exactly what you have in your .env, and that your server is pulling the proper .env if you are using a shared/persistent image or volume for it. Also I do not think the pusher key should be in quotes when in your env, so check on that as well.

Activity icon

Replied to Laravel-Websockets And WebRTC RTCPeerConnection

If you go the WebRTC route and run no media server as the middleman, I would still setup TURN/STUN, however you can find public ones with a google search. But if you choose to use a public one, know it can go down at anytime or they can kick you off if you abuse it.

I will say in my own experience (not the best on WebRTC advanced methods), in my demo app above I am using adapter.js and my own WebRTC javascript, but I have a few issues

https://github.com/RTippin/messenger-demo/blob/master/resources/js/managers/WebRTCManager.js

I was unable to figure out how to "subscribe" to a single stream without publishing my own by creating offers. So in your case that would not work. If I did not get my own media first I was unable to see anyone else basically.

Now on the other project I am working on (Remote teaching whiteboard/streaming/recording) I am using Janus server. Janus has many advantages as it handles so much for you. It allows me to easily have publishers and/or subscribers, so webinars are easy. On top of that, I can record the streams for playback after.

Activity icon

Awarded Best Reply on RESTful API

@cookie_good I use Passport to provide our mobile app with API, as well as utilizing their web token to allow the web app to consume parts of the same API endpoints. So far it has been working out great! Just alot to figure out one piece at a time. Passport is also handy if you do need to open parts of your API to 3rd parties, or separate apps you may be working on. I do not have experience using AirLock yet, but I hear it can also be useful if you do not need all the options passport provides.

Activity icon

Replied to RESTful API

@cookie_good I use Passport to provide our mobile app with API, as well as utilizing their web token to allow the web app to consume parts of the same API endpoints. So far it has been working out great! Just alot to figure out one piece at a time. Passport is also handy if you do need to open parts of your API to 3rd parties, or separate apps you may be working on. I do not have experience using AirLock yet, but I hear it can also be useful if you do not need all the options passport provides.

Activity icon

Replied to Laravel-Websockets And WebRTC RTCPeerConnection

@jinxkitt What exactly are you trying to accomplish? A webinar, (one to many), or one to one, many to many streams? WebRTC alone is not too hard to get one to one or many to many working, however if you want more of a webinar, then a media server such as janus is a good option. I have a demo messenger app that has video calls using WebRTC you can checkout here https://github.com/RTippin/messenger-demo

I will say with a base WebRTC setup, you will probably need to setup your own TURN/STUN servers and your own signaling server (pusher/socketio). In one of my projects, I am currently working on using Janus as the media server to handle video calls/webinars. You can check out their documentation as well here https://janus.conf.meetecho.com/docs/

In general I would suggest heavily looking over the examples from the WebRTC project to get a better understanding of how they setup streams in each module. https://webrtc.github.io/samples/

Activity icon

Replied to Video Call App

I have a demo app available I'm working on that includes video calls if you'd like it as an example. I have installation docs but not necessarily tutorial on how to. If you have questions I can try to be of some help.

https://github.com/RTippin/messenger-demo

Activity icon

Awarded Best Reply on Broadcasting On Private Channels

Also add dot to javascript private channel name

axios.get(/tasks/+this.project.id).then(response=>{
    this.tasks = response.data;
});
window.Echo.private('task.'+this.project.id)
.listen('TaskAdded', e=>{
    console.log(e.task.description);
    // this.tasks.push(e.task.description);
})
Activity icon

Replied to Broadcasting On Private Channels

Also add dot to javascript private channel name

axios.get(/tasks/+this.project.id).then(response=>{
    this.tasks = response.data;
});
window.Echo.private('task.'+this.project.id)
.listen('TaskAdded', e=>{
    console.log(e.task.description);
    // this.tasks.push(e.task.description);
})
Activity icon

Replied to Broadcasting On Private Channels

In your providers folder in app, do you also have un-commented the broadcast routes?

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Broadcast::routes();

        require base_path('routes/channels.php');
    }
}
Activity icon

Replied to Broadcasting On Private Channels

Sorry posted right as you did. Two things though I notice...projectId must also be $projectId in method. Also, where you define PrivateChannel,

    public function broadcastOn()
    {
        return new PrivateChannel('task.'.$this->task->project_id);
    }

Be sure to use the dot in the string name for channel if you call it that way in channels.php

Activity icon

Replied to Broadcasting On Private Channels

What about your channels.php file. Did you add the channel to the channel routing?

Broadcast::channel('task.{project_id}' , function($user, $project_id) {
   return true; //run logic to see if user has permission to access project channel
});
Mar
15
3 weeks ago
Activity icon

Replied to Does Anyone Put All Of The Images Into One Folder?

I usually would use a unique identifier of that user to name the parent directory of all of their uploads. You could even then inside their folder, make unique folders for each event if they may have multiple uploads per event. This in my experience makes it easier to delete all user uploads, specific event uploads, etc.

Mar
13
3 weeks ago
Activity icon

Awarded Best Reply on How To Structure A Console Command Handle() Method?

Personally I try to avoid too many foreach's or nesting them within one main method. Getting it working is the first step though! Now I have no way of testing this, but I believe you can at least condense your collections down and reuse them instead of grabbing and looping multiple times. Here is how I would condense it along with eager loading the bids :

    public function handle()
    {
        $biddedJobs = SlugJob::where([
            ['deadline', '<=', Carbon::now('America/Los_Angeles')->toDateTimeString()],
            ['bidded', '=', 0]
        ])
        ->with(['bids'])
        ->get();

        foreach ($biddedJobs as $biddedJob):
            $bids = $biddedJob->bids;
            $winning = $bids->sortBy('bid')->first();
            $loosing = $bids->sortByDesc('bid')->pop();

            foreach ($loosing as $lost):
                $lost->user->notify(new SendJobBiddedLosingBiddersNotified($lost));
            endforeach;
            
            $winning->user->notify(new SendJobBiddedWinningBidderNotified($biddedJob));
            
            $biddedJob->user->notify(new SendJobBiddedBuyerNotified($biddedJob));
        endforeach;
        
        $biddedJobs->update(['bidded' => 1]);
        
    }
Mar
12
4 weeks ago
Activity icon

Replied to How To Structure A Console Command Handle() Method?

Personally I try to avoid too many foreach's or nesting them within one main method. Getting it working is the first step though! Now I have no way of testing this, but I believe you can at least condense your collections down and reuse them instead of grabbing and looping multiple times. Here is how I would condense it along with eager loading the bids :

    public function handle()
    {
        $biddedJobs = SlugJob::where([
            ['deadline', '<=', Carbon::now('America/Los_Angeles')->toDateTimeString()],
            ['bidded', '=', 0]
        ])
        ->with(['bids'])
        ->get();

        foreach ($biddedJobs as $biddedJob):
            $bids = $biddedJob->bids;
            $winning = $bids->sortBy('bid')->first();
            $loosing = $bids->sortByDesc('bid')->pop();

            foreach ($loosing as $lost):
                $lost->user->notify(new SendJobBiddedLosingBiddersNotified($lost));
            endforeach;
            
            $winning->user->notify(new SendJobBiddedWinningBidderNotified($biddedJob));
            
            $biddedJob->user->notify(new SendJobBiddedBuyerNotified($biddedJob));
        endforeach;
        
        $biddedJobs->update(['bidded' => 1]);
        
    }
Mar
10
4 weeks ago
Activity icon

Replied to How To Structure A Console Command Handle() Method?

If there is no way any one of your situations gets called twice for a user ( bidders and buyer who won, who lost, and the final price ), then get 3 collections to begin with using those constraints, and send them through their own logic services to loop through them, say 3 separate jobs.

Activity icon

Replied to How To Structure A Console Command Handle() Method?

Thanks! I personally have not used Notifications in a batch before in your sense, however there is a difference between Notification/Event/Broadcast. If you are using notifications, I assume you use the notifications database table to store them. You may be confusing event listeners to broadcast events. Your DeadlineExpired is a broadcast event for a private channel, which means that itself is not the notification channel for any individual user. Using broadcast events would only be realtime events but would not be shown to anyone offline, however broadcast events can take in a batch of user private channels (up to 100 at a time) to push simple data out. If you are storing the notification, I would just loop through and notify each user one at a time, and if it is a huge data set, try chunking it into multiple jobs.

Activity icon

Replied to How To Structure A Console Command Handle() Method?

On a side note, it seems you are running a DB::transaction for every individual action, when that is more meant to run outside of your foreach so that if any one failed, you can roll the entire updates back on all that had already passed.

Activity icon

Replied to How To Structure A Console Command Handle() Method?

First off, if your first example above works, you can choose to stick with that for now. I just prefer separating logic out myself. After your refactor, the error seems because you are passing the whole collection from the ->get() query instead of the individual slugJob which the event needs. Here is a commands directory in a project of mine you can look over. https://github.com/RTippin/messenger-demo/tree/master/app/Console/Commands

Activity icon

Replied to How To Structure A Console Command Handle() Method?

What I personally do is have the handle method call my external services and pass them data directly. When you have a collection you can either use foreach or the collection method ->each(). For your constructor error, I would need to see your DeadlineExpired class to better understand, but it seems that class expects a single SlugJob and not the collection $biddedJobs you are sending it. I can link you my repo for examples of how I handle commands if you want.

Mar
05
1 month ago
Activity icon

Replied to Laravel Passport - Consuming API Issue

You do not have to use Vue.js, or any certain library for axios itself to set the headers on its own. Assuming you still compile with the base app.js laravel ships with, you should have the following code already in place after axios is defined. If not, here is what it looks like:

let token = document.head.querySelector('meta[name="csrf-token"]');
window.Laravel = { csrfToken: token.content };
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;

Again, wherever you require axios in your js, you can set the headers right there. That csrf token will also contain the same details needed for backend to understand the "api token". As long as whatever base page your app points to via web, so your main SPA route, if you are logged in and authed from web middleware, you can add that creates token middleware, append the token to axios headers, and API should run smooth

Mar
04
1 month ago
Activity icon

Replied to Laravel Passport - Consuming API Issue

@rn-code So I have a messaging application that uses API for all routing (mobile app or web). However, in my mobile app I communicate to my API using the oauth token system, but my web version also hits the same API as the mobile app. Because I am logged in on WEB, I use the CreateFreshApiToken::class, which means axios automatically adds that cookie to all request. So my web facing side can hit the same API routes as mobile, without needing to worry about oauth tokens or handshakes, which is what I believe you are trying to accomplish. I would give it a try still.

Activity icon

Replied to Laravel Passport - Consuming API Issue

If you are going by cookie from WEB, did you add the following middleware to your web group so that the passport cookie is set?

CreateFreshApiToken::class
Mar
02
1 month ago
Activity icon

Replied to Message System

I am in the middle of building one myself, that I started 2 years ago using that package you mentioned above as a base. I have a fully working demo app up with source code, but you will have to dissect it yourself for now, since I have not extracted out to a package yet. Source and link to demo can be found at https://github.com/RTippin/messenger-demo