_Marco_

_Marco_

Member Since 4 Months Ago

Experience Points
1,040
Total
Experience

3,960 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
0
Lessons
Completed
Best Reply Awards
1
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
1,040 XP
Sep
18
5 days ago
Activity icon

Replied to Laravel 5.4 PHP Unit Test Missing Methods And Not Working

This happens to me in some assertions as well like assertMatchesRegularExpression() just throws an error:

Error: Call to undefined method

I am extending TestCase from Tests\TestCase which is extending BaseTestCase from Illuminate\Foundation\Testing\TestCase.

Looks like something that should be fixed.

I am using Laravel 6 btw.

Sep
17
6 days ago
Activity icon

Replied to How To Create A Route With Slug Or Id

I have a similar problem but mine is slightly more complicated because my slugs are numeric as well so if I do orwhere and first() and my slug is 1000 and I have a record with id 1000 as well it will just find one of them. Any idea how could I solve this? The only thing that occurs to me is have different routes with different methods but I would like to have the same route and method if possible.

Sep
04
2 weeks ago
Activity icon

Replied to Please Help Refactor This Controller

For validations I would probably generate a ProfileRequest with

 php artisan make:request ProfileRequest

and use the rules there.

You could also do something like

private function _createProfile(User $user, ProfileRequest $request) {
    
	$data = $request->all();

	$query = Profile::create($data);

    
Sep
03
2 weeks ago
Activity icon

Replied to Call To Undefined Relationship [category , Subcategory] On Model

@sohail49 you are missing single quotes so it's 'category' , 'subCategory' and not 'category, subcategory'.

Activity icon

Replied to Call To Undefined Relationship [category , Subcategory] On Model

@sinnbeck totally missed that, that's why you are level 50 I guess ahahah

Activity icon

Replied to Call To Undefined Relationship [category , Subcategory] On Model

i see you are putting 'App\Models\subCategory' but your class is called SubCategory, not sure if it is related but try to change that. Also don't forget the use sentences on top.

Activity icon

Replied to Call To Undefined Relationship [category , Subcategory] On Model

where are you calling the relation??

Aug
28
3 weeks ago
Activity icon

Replied to Laravel 5: Trying To Get Property Of Non-object

And maybe show us dd for $blog->user as well.

Aug
27
3 weeks ago
Activity icon

Replied to Get Nested Subquery With Eloguent

Have a look on this library it might help you with this.

https://github.com/staudenmeir/eloquent-has-many-deep

Aug
26
4 weeks ago
Activity icon

Replied to Get Nested Subquery With Eloguent

@dosmukhanbet you want to get the points of the order right??

first parameter should be the final model you want the relation like it shows on the docs:

"The first argument passed to the hasOneThrough method is the name of the final model we wish to access, while the second argument is the name of the intermediate model."

Activity icon

Replied to Get All Ids Of Subcategories

Did you try $categories->subcategories->pluck('id'); ?

Aug
07
1 month ago
Activity icon

Replied to [PDOException] Access Denied For User 'forge'@'localhost'

This happened to me before. Make sure that in your database.php in config your default connection name is the same as in your .env.

database.php:

	 /*
  |--------------------------------------------------------------------------
  | Default Database Connection Name
  |--------------------------------------------------------------------------
  |
  | Here you may specify which of the database connections below you wish
  | to use as your default connection for all database work. Of course
  | you may use many connections at once using the Database library.
  |
   */

  'default'     => env('DB_CONNECTION', 'mysql'),

.env:

##############################################################
# Database Configuration
##############################################################

DB_CONNECTION=mysql
DB_HOST=mybase
DB_USERNAME=myname
DB_PASSWORD=mypassword
Aug
04
1 month ago
Activity icon

Replied to Eloquent, Group By Relationship.

Hi,

probably a relation hasManyThrough is what you are looking for in order to get the projects from a subtask.

Have a look in the documentation:

https://laravel.com/docs/7.x/eloquent-relationships#has-many-through

Jul
01
2 months ago
Activity icon

Awarded Best Reply on Laravel Permission

I don't think is going to change much more in terms of performance if you add roles to your project. It's a pretty straight forward query.

Activity icon

Replied to Laravel Permission

I don't think is going to change much more in terms of performance if you add roles to your project. It's a pretty straight forward query.

Jun
29
2 months ago
Activity icon

Replied to Laravel Permission

The thing is that if you use a role, this role will haven many permissions and you can assign just the role to each user instead of assigning all the permissions one by one.

i don't know if this answers your question.

Using a library like the one I mentioned before will make the process much quicker and stable because the problems you are going to have by implementing something from scratch they probably already had them.

Activity icon

Awarded Best Reply on Sync() In One To Many Relation

I can't delete them all because there is a different relation with this entity in a poly pivot and the id will change if I do this.

So to explain better: Entity A haves one to many relation with Entity B. Entity B haves a poly relation with Entity C and Entity D.

If I delete them all and create them again id will change and poly will not work anymore.

Activity icon

Replied to Sync() In One To Many Relation

I can't delete them all because there is a different relation with this entity in a poly pivot and the id will change if I do this.

So to explain better: Entity A haves one to many relation with Entity B. Entity B haves a poly relation with Entity C and Entity D.

If I delete them all and create them again id will change and poly will not work anymore.

Activity icon

Replied to Laravel Permission

Try Spatie/permissions

https://docs.spatie.be/laravel-permission/v3/introduction/

this will help you a lot.

Activity icon

Started a new Conversation Sync() In One To Many Relation

Is there a way to use sync() or a similar function in a one to many relation??

May
21
4 months ago
Activity icon

Replied to Turning My Laravel App Into A GraphQL Endpoint

Have a look at this guys it might help you out https://lighthouse-php.com/

Activity icon

Replied to GraphQL Client For Laravel

I don't know if this answers your question but have a look at https://lighthouse-php.com/ maybe there is something for you.

May
14
4 months ago
Activity icon

Replied to Spatie Permissions And Multiple Guards

At the end the problem was in the middleware in the route because I had api and was using web but thanks anyway @michaloravec

Activity icon

Replied to Spatie Permissions And Multiple Guards

Just did some debugging and if I do a dd(Auth::user()) in login method I get $guard_name = 'web2';

but if I do dd(Auth::user) in hairdresser() method I get web instead...

very strange.

Activity icon

Replied to Spatie Permissions And Multiple Guards

I get a Call to a member function createToken() on null error because probably when I register is still taking the guard as web instead of web2 despite that in my model I have $guard_name = 'web2';

I am just confused...

Activity icon

Replied to Spatie Permissions And Multiple Guards

Not really working because that line is just to check if that record exists in db

if (!Auth::attempt($credentials)) {
      return response()->json([
        'message' => 'Unauthorized',
      ], 401);
    }
Activity icon

Replied to Spatie Permissions And Multiple Guards

My Hairdresser Model:


<?php

namespace App\Models\Hairdressers;

use App\Models\Shops\Shop;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class Hairdresser extends Authenticatable
{
  use HasApiTokens, Notifiable;
  use HasRoles;

  protected $table      = 'users';
  protected $guard_name = 'web2';

  /**
   * The attributes that are mass assignable.
   *
   * @var array
   */
  protected $fillable = [
    'name',
    'surname',
    'mobile',
    'image',
    'email',
    'password',
  ];

  /**
   * The attributes that should be hidden for arrays.
   *
   * @var array
   */
  protected $hidden = [
    'password',
    'remember_token',
  ];

  /**
   * The attributes that should be cast to native types.
   *
   * @var array
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
  ];

  public function shop()
  {
    return $this->hasOne(Shop::class, 'user_id');
  }
}

Activity icon

Replied to Spatie Permissions And Multiple Guards

My HairdresserController,UserController looks pretty much the same but in store I assign the role User


namespace App\Http\Controllers;

use App\Http\Requests\Users\HairdresserRequest;
use App\Http\Resources\Users\HairdresserResource;
use App\Models\Hairdressers\Hairdresser;
use App\Repositories\Users\HairdresserRepository;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class HairdresserController extends Controller
{

  protected $hairdresser_repo;

  public function __construct(HairdresserRepository $hairdresser_repository)
  {
    $this->hairdresser_repo = $hairdresser_repository;
    
  }
  public function signup(HairdresserRequest $request)
  {
    try {
      DB::beginTransaction();

      /*  ***Store image in disk*** */

      $image           = $request->file('image');
      $image_path_name = time() . $image->getClientOriginalName();
      Storage::disk('hairdressers')->put($image_path_name, File::get($image));

      $data = [
        'name'     => $request->name,
        'surname'  => $request->surname,
        'email'    => $request->email,
        'mobile'   => $request->mobile,
        'password' => bcrypt($request->password),
        'image'    => time() . $request->file('image')->getClientOriginalName(),
      ];

      $query = $this->hairdresser_repo->create($data)
        ->assignRole('Hairdresser');

      $hairdresser = new HairdresserResource($query);
      $body        = compact('hairdresser');

      DB::commit();

      return response()->json(compact('body'), 201);

    } catch (Exception $e) {
      DB::rollback();
      dd($e);
      $message = 'Something went wrong';
      throw new Exception($message, 500);
    }
  }

  /**
   * Update hairdresser
   *
   */

  public function update(HairdresserRequest $request, $id)
  {
    try {
      DB::beginTransaction();
      $user_id = Auth::id();
      if ($user_id == $id) {
        /*  ***Store image in disk*** */
        /* $image = $request->file('image');
        $image_path_name = time() . $image->getClientOriginalName();
        Storage::disk('users')->put($image_path_name, File::get($image));*/

        $data = [
          'name'    => $request->name,
          'surname' => $request->surname,
          'mobile'  => $request->mobile,
          //'password' => bcrypt($request->password),
          //'image' => time() .  $request->file('image')->getClientOriginalName()
        ];

        $query       = $this->hairdresser_repo->model()::find($id)->update($data);
        $hairdresser = $this->hairdresser_repo->model()::find($id);
        $hairdresser = new HairdresserResource($hairdresser);
        $body        = compact('hairdresser');

        DB::commit();

        return response()->json(compact('body'), 202);
      } else {
        return response()->json([
          'message' => 'Tienes que estar identificado',
        ]);
      }

    } catch (Exception $e) {
      DB::rollback();
      dd($e);
      $message  = 'Something went wrong';
      $errors[] = $e->getMessage();
      throw new Exception($message, 500);
    }
  }

  /**
   * Login user and create token
   *
   */
  public function login(Request $request)
  {
    $request->validate([
      'email'       => 'required|string|email',
      'password'    => 'required|string',
      'remember_me' => 'boolean',
    ]);

    $credentials = request(['email', 'password']);

    if (!Auth::attempt($credentials)) {
      return response()->json([
        'message' => 'Unauthorized',
      ], 401);
    }

    $user = $request->user();

    $tokenResult = $user->createToken('Personal Access Token');
    $token       = $tokenResult->token;

    if ($request->remember_me) {
      $token->expires_at = Carbon::now()->addWeeks(1);
    }

    $token->save();

    return response()->json([
      'access_token' => $tokenResult->accessToken,
      'token_type'   => 'Bearer',
      'expires_at'   => Carbon::parse(
        $tokenResult->token->expires_at
      )->toDateTimeString(),
    ]);
  }

  /**
   * Logout user (Revoke the token)
   *
   * @return [string] message
   */
  public function logout(Request $request)
  {
    $request->user()->token()->revoke();

    return response()->json([
      'message' => 'Successfully logged out',
    ]);
  }

  /**
   * Get the authenticated User
   *
   * @return [json] user object
   */
  public function hairdresser()
  {
    $query       = Auth::user();
    $hairdresser = new HairdresserResource($query);
    $body        = compact('hairdresser');

    return response()->json(compact('body'));
  }
}

Activity icon

Replied to Spatie Permissions And Multiple Guards

I have 2 different loginControllers since I am using HairdresserController for register and login and UserController for the same purpose but no form since I am building an API Rest and testing stuff on Postman but I have different endpoints

Activity icon

Replied to Spatie Permissions And Multiple Guards

I have the guard_name defined in my models like so:

Users Model:

protected $guard_name = 'web';

or Hairdresser Model:

protected $guard_name = 'web2';

Activity icon

Replied to Spatie Permissions And Multiple Guards

I just have a folder after Models because some folders have multiple models inside but the path is correct.

Activity icon

Replied to Spatie Permissions And Multiple Guards

Hi, yes thats the right path and they both work because if I swap them around then users doesn't work and Hairdressers does

Activity icon

Started a new Conversation Spatie Permissions And Multiple Guards

Hi guys, I am having some problems with Spatie permissions library.

I have a users table and 2 models which are User and Hairdresser using the same db table. Both have the same signup and login logic the only difference is that they will have different roles(one will have User Role and other Hairdresser Role). The problem is that when I signup the User everything works fine and the role User is assigned but with the exact same code when I signup hairdresser the role is assigned and in response I get it's role but when I try to access hairdresser in a get petition roles come empty. I believe this haves something to do with guards in auth.php but I tried everything and nothing works.

auth.php

​```

return [

'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ],

'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users',

],
'web2' => [
  'driver'   => 'session',
  'provider' => 'hairdressers',
],

'api'  => [
  'driver'   => 'passport',
  'provider' => 'users',
  'hash'     => false,
],

],

'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User\User::class, ],

'hairdressers' => [
  'driver' => 'eloquent',
  'model'  => App\Models\Hairdressers\Hairdresser::class,
],

],

'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, 'throttle' => 60, ], ],

'password_timeout' => 10800,

];

​```

Apr
30
4 months ago
Activity icon

Replied to Create Method Not Working

Thanks!!! Hours wasted in such a dumb thing.

Activity icon

Started a new Conversation Create Method Not Working

Hey, I have a simple store in db but it's not working. This is my code:

Method in controller:

public function store(ShopRequest $request): JsonResponse
  {
    try {
      DB::beginTransaction();
      $user = Auth::user();
      if ($user->can('create-shop')) {
        $data = [
          'name'    => $request->name,
          'user_id' => $user->id,
        ];
        $shop_query = $this->shop_repo->create($data);

        $shop = new ShopResource($shop_query);
        $body = compact('shop');
        return response()->json(compact('body'), 201);

      } else {
        throw (new Exception('No tienes permisos para esta acción'));
      }
    } catch (Exception $e) {
      DB::rollback();
      $errors[] = $e->getMessage();
      throw new Exception($e->getMessage());
    }

  }

Model:

namespace App\Models\Shops;

use Illuminate\Database\Eloquent\Model;

class Shop extends Model
{
  
  /**
   * The attributes that are mass assignable.
   *
   * @var array
   */

  protected $fillable = [
    'name',
    'user_id',
  ];

  public $timestamps = true;

}

In postman I get the right json response but when I check in db nothing there... :/