Squire

Squire

Member Since 5 Months Ago

Experience Points 6,650
Experience Level 2

3,350 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 62
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.

29 Aug
2 weeks ago

Squire left a reply on Method Not Allowed On Axios Post Request With Vue And Laravel

Hey thank you for replying. I'm not trying to update, in the beginning of the thread I wrote this: "and I have to do a post request to '/projects' to create a resource."

I have nothing in my api.php, I also wrote that I created the route in the web.php file: "I'm registering the routes in my web.php like this:"

Thank you!

Squire commented on Object-Oriented Forms: Part 1

I'm getting a method not allowed error with the post request to Projects, here I explain further my issue: https://laracasts.com/discuss/channels/code-review/method-not-allowed-on-axios-post-request-with-vue?page=1#

any help is appreciated

Squire left a reply on Method Not Allowed On Axios Post Request With Vue And Laravel

Yeah I tried it before, forgot to mention it in the post

Squire started a new conversation Method Not Allowed On Axios Post Request With Vue And Laravel

Hi guys, so I'm following up this course: https://laracasts.com/series/learn-vue-2-step-by-step/episodes/19

and I have to do a post request to '/projects' to create a resource.

I created my ProjectController with the artisan command using the --resource modifier and I'm registering the routes in my web.php like this:

Route::resource('projects', 'ProjectController');

If I run the route:list, I get this: https://i.imgur.com/gx4xOsa.png

And my Vue component with the Axios request:

new Vue({
    el: '#app',

    data: {
        name: '',
        description: ''
    },

    methods: {
        onSubmit: function () {
            axios.post('projects', {
                name: this.name,
                description: this.description
            });
        }
    }
});

I don't know what's going on, I'm stuck here. The resource route is creating the post method for projects...

This is the Axios response (405): message The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE.

EDIT: I also tried with /projects instead of project in the axios request

25 Aug
3 weeks ago

Squire commented on Workshop - Card Design

how can I access those assets, the book and the clock for example

19 Aug
4 weeks ago

Squire commented on A Project Requires An Owner

public function test_a_project_requires_an_owner()
    {
        $this->withoutExceptionHandling();
        $attributes = factory('App\Project')->raw(['owner_id' => null]);
        $this->post('/projects', $attributes)->assertSessionHasErrors('owner_id');
    }

That test was giving me this error: The given data was invalid, once I removed the withoutExceptionHandling() the test passed.

Squire commented on Model Tests

that forelse blew my mind, didn't know that exists!

18 Aug
4 weeks ago

Squire left a reply on Will I Be Charged Monthly?

Do I have to do it near my subscription end or can I do it like right now so I don't foget to do it later?

Squire started a new conversation Will I Be Charged Monthly?

My sister paid for me the monthly subscription but she said that she doesn't want to get charged monthly without her knowing it. How does laracast work? Do I have to manually pay for my next month or will it do it automatically?

10 Aug
1 month ago

Squire left a reply on Would Like To Get Feedback In My First Package

Thank you! It's a small package tho :( still developing it.

These doubts put me in a non ending loop where I read articles after articles about designs and how to write good code (time where I do not code at all) and I end up procrastinating

Squire started a new conversation Would Like To Get Feedback In My First Package

Hello guys. So I've been into programing for 1 and a half year now and I've been spending the last 7 months learning Laravel. I wanted to do something different aside from the normal backend services for applications so I decided to try with a package.

I read a couple of tutorials regarding the folder structure and what I had to do to made it available in composer and all that stuff. But anyways, these are my biggest concerns right now:

  1. I'm developing it to be used only with Laravel, but I've read a lot of threads where people talk about packages should be general use, not framework orientated. What should be the best approach to achieve this?

  2. All the logic is inside one single class. I've been thinking that I can separate some stuff to improve the readability and scalability, but that would make me loss my one single facade feature. What do you recommend me?

  3. I've read that one shouldn't enforce developers to use facades but give them the option to choice between that or dependency injection. How can I make sure that my package can work thorugh dependency injection too?

  4. And this one may sound stupid but I had a tough time trying to choose the name of my logic class. First off, I placed it inside a "Helpers" class and then named it "UrlShortenerHelper" (I don't remember why) but then today I named the whole thing to "Services/UrlShortenerService" because it made more sense to me. Is there any naming convention for this kind of stuff? I'm very used to laravel convention for classic backend services naming convention, like controllers have the name of the resource in singular followed by the controller name and stuff like that.

Thank you for taking the time of read my code. This is the repository: https://github.com/cedaesca/urlshortener

08 Jul
2 months 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
3 months 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\ur[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
3 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
5 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
5 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 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?