Squire

Squire

Member Since 4 Months Ago

Experience Points 3,820
Experience Level 1

1,180 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 36
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

08 Jul
2 weeks ago

Squire started a new conversation Laravel Forge: Deploy From Monorepo

Hello, I paid Laravel Forge and a Digital Ocean droplet and when trying to deploy from my repo which is structured like this:

backend /laravelRoot frontend /angularRoot

but it gave me an error. What would be the best approach to deploy both frontend and backend? there's something I have to edit? any resource you can give me so I can read?

25 May
1 month ago

Squire started a new conversation Class Not Found In Package's Controller

So, I'm following a tutorial to create a package and I have the following structure:

root/packages/vendor/package/src

And in the src folder I have the following files:

routes.php (For routing):

<?php
namespace cedaesca\URLShortener;

Route::get('cedaesca/urlshortener/create', 'cedaesca\URLShortener\[email protected]')->name('cedaesca/urlshortener/create');
Route::post('cedaesca/urlshortener/store', 'cedaesca\URLShortener\[email protected]')->name('cedaesca/urlshortener/store');

ShortenedUrl (model)

<?php

namespace cedaesca\URLShortener;

use Illuminate\Database\Eloquent\Model;

class ShortenedUrl extends Model
{

    /**
     * Fillable columns for model's mass assignment
     *
     * @var array
     */
    
    protected $fillable = [
        'shortlink',
        'target',
        'title',
        'description'
    ];

    /**
     * Custom table for the current model
     *
     * @var string
     */

    protected $table = 'shortenedurls';

    /**
     * URL's code length
     *
     * @var integer
     */
    
    public $length = 4;

    /**
     * If the code doesn't exist, it redirects to this default
     *
     * @var string
     */

    public $defaultRedirect = '/';

    /**
     * Genearet an unique code that will serve as an URL parameter
     *
     * @return string
     */

    public function generateCode() {

        $extraCharacter = '';

        if( $this->length % 2 != 0 ) {

            $extraCharacter = bin2hex( random_bytes(4) );
            $extraCharacter = substr( $extraCharacter, -1 );

        }

        do {

            $code = bin2hex( random_bytes( $this->length / 2 ) ) . $extraCharacter;

        } while( $this->checkIfExists('shortlink', $code) );

        return $code;
        
    }

    /**
     * Check if there are records for the specified column with the given value
     *
     * @param string $type
     * @param string|integer $value
     * @return boolean
     */

    public function checkIfExists($type, $value) {

        $collection = $this::where($type, $value)->first();

        if( !is_null( $collection ) ) {

            return true;

        }

        return false;

    }
    
}

UrlShortenerController (controller)

<?php

namespace cedaesca\URLShortener;

use Illuminate\Http\Request;
use ShortenedUrl;
use Illuminate\Support\Facades\Route;

class UrlShortenerController extends Controller
{
    public function create() {

        return view('url.create');

    }

    /**
     * Store a new record in the shortenedurls table
     *
     * @return json
     */

    public function store(Request $request) {

        $validatedData = $request->validate([

            'target' => 'required|max:255'

        ]);

        $shortenedUrl = new ShortenedUrl;

        $shortenedUrl = $shortenedUrl::create([

            'shortlink' => $shortenedUrl->generateCode(),
            'target' => $request->target,
            'title' => $request->title,
            'description' => $request->description

        ]);

        if( $shortenedUrl->id ) {

            return response()->json([
                'message' => 'Created successfully',
                'data' => [
                    'id' => $shortenedUrl->id,
                    'shortenedlink' => $shortenedUrl->shortlink,
                    'title' => $shortenedUrl->title,
                    'description' => $shortenedUrl->description,
                    'created_at' => $shortenedUrl->created_at
                ]
            ], 201);

        }

        return response()->json([
            'message' => 'Occured an error while trying to create a shortened URL, try again'
        ]);

        

    }

    /**
     * Check if there are records for the specified column with the given value
     *
     * @param string $code
     * @return object
     */

    public function redirect($code) {

        $shortenedUrl = new ShortenedUrl;
        
        $collection = ShortenedUrl::where('shortlink', $code)->first();

        if( ! is_null( $collection ) ) {

            return redirect($collection->target);

        }

        return redirect($shortenedUrl->defaultRedirect);

    }
}

URLShortenerServiceProvider (service provider)

<?php

namespace cedaesca\URLShortener;

use Illuminate\Support\ServiceProvider;

class URLShortenerServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadRoutesFrom(__DIR__.'/routes.php');
    }
}

Now, when I try to access /cedaesca/urlshortener/create I get this error:

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)
Class 'cedaesca\URLShortener\Controller' not found

I added the class in the composer's autoload section:

"autoload": {
        "psr-4": {
            "App\": "app/",
            "cedaesca\URLShortener\": "packages/cedaesca/URLShortener/src"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },

And dumped the autoload with composer dump-autoload

What am I missing? I didn't find anything controller related in the laravel's pacakge documentation :/

18 May
2 months ago

Squire started a new conversation Create URL's From UI

Hello guys,

I want to create an URL shortener but I don't really know how to generate new routes from an UI. Any suggestion or article I can read?

22 Mar
4 months ago

Squire left a reply on Get Fields From Table Related To Pivot Table

@matt.libera

Hey man! Thanks for your time, your reply was amazing. It helped me understand it better and I read the documentation again with other mind and I could achieve what I was trying.

On my staff model:

public function roles() {
        return $this->belongsToMany('App\Roles','role_staff','staff_id','role_id');
    }

On my roles model:

public function roleStaff() {
        return $this->belongsToMany('App\Staff','role_staff','role_id','staff_id');
    }

My pivot table (I changed the name as you suggested), extending the pivot class:

public function staff() {
        return $this->belongsToMany('App\Staff')->using('App\RoleStaff');
    }

And in my controller:

public function getStaffMembers() {
        $staff = new Staff;
        return $staff::where('active',1)
                                ->orderBy('nickname','asc')
                                ->with(['addedByUser','roles'])
                                ->get();
    }

I really appreciate your answer, I'm starting to understand better Laravel and I'm beggining to love it!

21 Mar
4 months ago

Squire left a reply on Get Fields From Table Related To Pivot Table

@MATT.LIBERA - I have 7 roles I think in my table, and a Staff can have them all. They don't grant permissions, they're just informative.

Squire started a new conversation Get Fields From Table Related To Pivot Table

Hello guys. I'm building a small project just to learn Laravel. I have three tables:

-users (default created with auth),

-staff

public function up()
    {
        Schema::create('staff', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('nickname');
            $table->timestamps();
            $table->date('left_at')->nullable();
            $table->bigInteger('added_by')->unsigned();
            $table->bigInteger('removed_by')->unsigned()->nullable();
            $table->bigInteger('last_modification_by')->unsigned();
            $table->boolean('active');
            $table->foreign('added_by')->references('id')->on('users');
            $table->foreign('removed_by')->references('id')->on('users')->nullable();
            $table->foreign('last_modification_by')->references('id')->on('users');
        });
    }

-Roles

public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
        });
    }

And staff_role

public function up()
    {
        Schema::create('staff_role', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('staff_id')->unsigned();
            $table->bigInteger('role_id')->unsigned();
            $table->bigInteger('added_by')->unsigned();
            $table->foreign('staff_id')->references('id')->on('staff');
            $table->foreign('role_id')->references('id')->on('roles');
            $table->foreign('added_by')->references('id')->on('users');
        });
    }

Staff and roles are just for reading purposes, I don't plan to do any authentication nor login with these.

These are my models:

-Staff

class Staff extends Model
{

    protected $fillable = [
        'nickname',
        'left_at',
        'added_by',
        'removed_by',
        'last_modification_by',
        'active'
    ];

    public function addedByUser() {
        return $this->belongsTo('App\User','added_by');
    }

    public function removedByUser() {
        return $this->belongsTo('App\User','removed_by');
    }

    public function lastModificationByUser() {
        return $this->belongsTo('App\User','last_modification_by');
    }

    public function staffRole() {
        return $this->hasMany('App\StaffRole','staff_id');
    }
}

-Roles

class Roles extends Model
{
    public $timestamps = false;

    public function staffsRoles() {
        return $this->hasMany('App\StaffRole','role');
    }
}

-StaffRole

class StaffRole extends Model
{
    protected $table = 'staff_role';

    public $timestamps = false;
    
    protected $fillable = [
        'staff_id',
        'role_id',
        'added_by'
    ];

    public function staff() {
        return $this->belongsTo('App\Staff');
    }

    public function roles() {
        return $this->belongsTo('App\Roles');
    }
}

I'm getting the staff data with a query, and getting the roles per staff too and it's working fine, it gives me what I want, but, now I want to get the role name regarding the roles.name regarding the staff_role.role and I have no clue on how to approach this, I tried reading the documentation but no result.

This is my method:

public function getStaffMembers() {
        $staff = new Staff;
        return $staff::where('active',1)
                                ->orderBy('nickname','asc')
                                ->with(['addedByUser', 'staffRole'])
                                ->get();
    }

So, if an user has the rol with id 3, what I actually want to get is the role name instead of the role id, for example. Any suggestion?