mdeorue

mdeorue

Member Since 3 Years Ago

Experience Points 25,910
Experience
Level
Lessons Completed 236
Lessons
Completed
Best Reply Awards 8
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

21 Sep
1 month ago

mdeorue left a reply on Delete Eloquent Relationship Data

Question, in the tables structures, you dont set the foreign key?

If you dont create the foreign key, you can use Eloquent observers to trigger some actions on delete University Model. (https://laravel.com/docs/5.7/eloquent#events)

public function deleting($university) { $university->info()->delete(); $university->academic()->delete(); }

05 Sep
2 months ago

mdeorue left a reply on How Do I Normalize This Case Into Database?

Me approach will be create a preferred_months table, that only record the preferred months, like this...

Schema::create('preferred_months', function (Blueprint $table) {
    $table->integer('country_id')->unsigned();
    $table->integer('month');
        });

So when you need to know what are the months you only need to do $country->months.

Regards.

24 Aug
2 months ago

mdeorue left a reply on Deleted_at Field In User Always Returning NULL

When you use SoftDelete, by default only return the "not deleted models" and ¿how you know if a model was deleted? Because de model has NULL in deleted_at.

If you want to get al the records you need to user withTrashed(). For example...

User::on('connection')->withTrashed()->find(x);

Regards

mdeorue left a reply on Missing Required Parameters For [Route: Users.edit]

Like it says @Artak the parameters go in an array. I only prefer name the parameters, like.


{{ route('users.edit', ['user', $user->id]) }}

/user/{user}

19 Aug
2 months ago

mdeorue left a reply on Am I Missing Something On My Delete Method ?

Medicine::truncate();

17 Aug
2 months ago

mdeorue started a new conversation Extends Parent Template

Hi guys, I want to ask your something, I'm starting to learn vue, and I want to make a basic component that extends specific component, for example, a modal component that have the ability to open and close, but the inner HTML is specific for a different component.

Example:

Modal.vue (Parent)

<button class="modal-close" @click="close">

export default{ data() { return { isOpen: false }; },
methods: {
    open: function()
    {
        this.isOpen = true;
    },
    close: function()
    {
        this.isOpen = false;
    }
}

}

And the child component,

UseModal.vue (Child)

Hello World

import Modal from './Modal';

export default { extends: Modal }

The thing is that I want to use the parent slot to put specific component HTML, but I cant see how it is possible.

Can you help me guys?

Regards!

07 Aug
3 months ago

mdeorue started a new conversation Two Form Request In One Controller

Hi guys, I want to ask for your help, I have a project that only can access by invitation for another admin user, so if I admin a team, and I want to add some user. If the user dont exists in the database, I need to create the user, and then assign to the team.

The thing is that I need to validate the request two times, for the assignation and the creation of the user.

You know an approach to this thing?

This is the algoritm for assignation...

User request assignation to a team -> Validate the assignation inputs -> Authorize the assignation -> If dosent exists User (Create) -> Assign to the team.

This is the algoritm for create...

Validate the creation inputs -> Authorize the creation -> Create User.

Regards.

06 Apr
7 months ago

mdeorue left a reply on Paginating In A View?

The pagination in Laravel is so easy to use, I recomend to use this.

public function showTestQuestions(Test $test)
{
$questions = $test->question()->paginate(5);
return view('test_questions',compact('test', 'questions'));
}

And in the view

@foreach($questions as $question)

@endforeach

{{ $questions->links() }}

If you want to do that in the view you can use de paginate method to, but I dont recomend you to do that, I prefer to mantain the meaning of the view layer.

Regards

27 Mar
7 months ago

mdeorue left a reply on Search And Skip To Next Item In Collection

You can use this snipet.

$collection = $collection->getIterator();
$current = current($collection);
$next = next($collection);

Regards

26 Mar
7 months ago

mdeorue left a reply on Where To Store Store Global Information ?

you can make a helper, or save in the session when the user login.

Regards.

25 Mar
7 months ago

mdeorue left a reply on Relationship In Relationsip In Relationship With Limit

Maybe this is a little better approuch,

return $sectors=Sector::select('id','name')
    ->with([
        'codelists' => function($query){
            $query->latest()->take(4);
        },
        'codelists.data' => function($query){
            $query->latest()->take(5);
        }
    ])->latest()->take(3)->get();

Regards

mdeorue left a reply on Eloquent Model With Condition Where,

I think the better way to do that is an accessor from the model, for example

class Example{
    
    public function getStatusAttribute()
    {
        switch($this->attributes['type'])
        {
            case(1):
                return null;
                break;
            case(2):
                return 5;
                break;
            case(3):
                ...;
            default:
                ...;
        }
    }
    
}

mdeorue left a reply on Laravel Eloquent Select From Two Tables Using Models Relationships

You can make relations in Eloquent

So if I understand a School belongs to a Country.

class School {
    public function country()
    {
        return $this->belongsTo(Country::class);
    }
}

So when you want to make your query you can do it simple

//The name of the function is an example
public function showCountry(School $school)
{
    $school->country;
}

Regards

mdeorue left a reply on Retrieving Elements Of Relationship Not Working

You can print the SQL query and know if anything was wrong with,

dd($this->orderItems()->toSql());

Regards.

24 Mar
7 months ago

mdeorue left a reply on How To Count Auth User Visit The Page

The same as @wilk_randall says, and you can make a middleware that save every page visit, like other option.

Regards.

23 Mar
7 months ago

mdeorue left a reply on How Do Invitation's Work?

When other person/company/etc... want your presence, make an invitation to you. :)

mdeorue left a reply on Search Database With Multiple Filters

You can do something like this.

public function search()
{
    model = Model::query();
    if(request()->filled('query'))
    {
        $model->where('text', request()->query);
    }
    //And if you have some filters
    if(request()->has('filter1'))
    {
        $model->where('filter1',request()->filter1;
    }
    return $model->get();
}

mdeorue left a reply on Change Blade View From Create To Edit Form When Button Is Triggered

If you use vue, you can use v-if. And when the button is clicked emit a event that this view listen and change v-if parameter.

Regards.

mdeorue left a reply on Page For Non-users.

Maybe create a Middleware replacing auth is your solution, like this.

´´´

20 Mar
7 months ago

mdeorue left a reply on SEARCH AND ORDER IN RELATED MODELS

You want to order by an One To Many relation the whole Collection, or you want to order the cards for any guest?

Regards

18 Mar
7 months ago

mdeorue left a reply on Operation In Eloquent ORM

The @Snapey approach is greate, for 5 mins change the 30 for 5.

$messages = Message::where('created_at' ,'>=',Carbon::now()->subMinutes(5))->get();

mdeorue left a reply on Take By Group And Item Both

Hi @arctushar, You want the last registered 03 users?

If this is the case, this is my approach,

Searching by Country name: ''' User::with([ 'post' => function($query){ $query->latest()->limit(5); } ])->join('country', function ($join) { $join->on('countries.id', '=', 'users.country_id') ->where('countries.name', '=', $countryName); })->latest()->limit(3)->get(); '''

Search by Country id: ''' User::with([ 'post' => function($query){ $query->latest()->limit(5); } ])->where('country_id', $countryID)->latest()->limit(3)->get(); '''

Regards

27 Feb
8 months ago

mdeorue left a reply on How To Find Nearest Cities From Latitude And Longitude

If you use google maps api?

https://maps.googleapis.com/maps/api/geocode/json?latlng=lat,long

Reponse:

json
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "277",
               "short_name" : "277",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Bedford Avenue",
               "short_name" : "Bedford Ave",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Williamsburg",
               "short_name" : "Williamsburg",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Brooklyn",
               "short_name" : "Brooklyn",
               "types" : [ "sublocality", "political" ]
            },
            {
               "long_name" : "Kings",
               "short_name" : "Kings",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "New York",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "11211",
               "short_name" : "11211",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "277 Bedford Avenue, Brooklyn, NY 11211, USA",
         "geometry" : {
            "location" : {
               "lat" : 40.714232,
               "lng" : -73.9612889
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.7155809802915,
                  "lng" : -73.9599399197085
               },
               "southwest" : {
                  "lat" : 40.7128830197085,
                  "lng" : -73.96263788029151
               }
            }
         },
         "place_id" : "ChIJd8BlQ2BZwokRAFUEcm_qrcA",
         "types" : [ "street_address" ]
      },

mdeorue left a reply on Sum On Multiple Columns In A Row

Ow, maybe you can use the same but with the 7 columns

->selectRaw('client, project, task, sum(mon_hrs) as mon_hrs, sum(tue_hrs) as tue_hrs, ...')
->groupBy('client', 'project', 'task')

But if you want to sum everything I will prefer us a Accesor

class TimesheetEntry{

public function getWeekHoursAttribute()
{
    return $this->mon_hrs + $this->tue_hrs + ...;
}

}

Regards

mdeorue left a reply on Relationship (again...)

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

mdeorue left a reply on How Can I Use Flash Message After Axios Post?

Yes but the flash message isnt a return its a session store for example.

session()->flash('message', $message);
return response('success', 204);

Regards

mdeorue left a reply on How Can I Use Flash Message After Axios Post?

In the controller,

/online/booking/user/${this.currentUser}

When your trigger this, before you return the response you can flash a message and in the next request, you can use.

mdeorue left a reply on Relationship (again...)

The order is wrong.

$pics = Picture::where('collection_id', $coll->id)->with('artist')->paginate(9);

mdeorue left a reply on Sum On Multiple Columns In A Row

You can do it, in the model side or controller side, for example

Eloquent query builder: ´´´ $entries = TimesheetEntry::with('project', 'client', 'timesheetTask') ->whereHas('project', function ($q) use ($client_id) { $q->where('client_id', '=', $client_id); }) ->whereBetween('updated_at', [$start, $end]) ->selectRaw('client, project, task, sum(hours) as task_hours') ->groupBy('client', 'project', 'task'); ´´´

Controller ´´´ $entries = TimesheetEntry::with('project', 'client', 'timesheetTask') ->whereHas('project', function ($q) use ($client_id) { $q->where('client_id', '=', $client_id); }) ->whereBetween('updated_at', [$start, $end]) ->get(); $clientProjectTasks = $entries->groupBy(['client', 'project', 'task']); And then when you need to show a table with the total hours you can do this.

foreach($clientProjectTasks as $clientProjectTask){ $clientProjectTask->sum('hours); } ´´´

Regards

mdeorue left a reply on Where Condition Returns Null

If you use $p = $this->where('id', '<', $this->id)->exists(); or count? $this->where('id', '<', $this->id)->count();

I use created_at column for this.

$this->where('created_at', '<', $this->created_at);

mdeorue left a reply on Multiple Language, Where To Start?

I save this language in the session, and with a middleware change the locale language in every request. I dont identify other solution yet. But its work for me.

Regards.

mdeorue left a reply on Relationship (again...)

If you got the id of the picture, you can do this.

$picture = Picture::find($idPicture); $artistFirstName = $picture->artist->firstname; $artistLastName = $picture->artist->lastname;

Greatings.

mdeorue left a reply on Save Some Data In Session To Avoid Db Requests?

Store: session(['key' => $value]);

Get: session()->get('key');

Delete: session()->forget('key);

19 Feb
8 months ago

mdeorue left a reply on Issue Related With Pivot Tables

Hi, sorry my english is very bad, but I if I understand, you want to save the tags of a post, that the user select in the create form.

If this is the case,

´´php

App/Post

public function setTags($tagsArray) { $this->tags()->attach($tagsArray],false); }

´´´

´´php

PostController

request()->validate([
        'title' => 'required',
        'content' => 'required',
        'date' => 'required',
        'image' => 'nullable|image'
    ]);
    $post->add($request-> except(['tags']));
    $post->setTags($request->input('tags'));

´´´

23 Jan
9 months ago

mdeorue left a reply on Need Help Getting The Last Post From Two Tables In My Database

I needed the same function before and finally what I did was add a column in the Post table, called last_activity (its a Carbon instance), so every time someone answers a Post I update that column, and when I create a post, I also update that column.

So when I want to sort by the last activity is like,

$forums = Forum::with([ 'subforums.threads' => function($query){ $query->latest('last_activity'); } ])->get();

I know this isnt the perfect response, but it is the approach that I was able to achieve :(

Regards

mdeorue left a reply on How To Convert A Json Data From API To Array And Store In Database

if you got the json string in a variable, as @bobbybouwmann say to you use json_decode, and magic.

$jsonArray = json_decode($jsonString);

Regards.

mdeorue left a reply on Policy Always True

Hi @LBOTTONI, the thing is that you need to use the $project variable, to compare with the user, this type of Policy is for create a Model.

When you put in the authorization method a "empty" model like $user->can('view', Project::class), in the policy is like.

Policies/ProjectPolicy

public function create(User $user)

So you need to use the $project variable, that you mencioned before.

$user->can('view', $project);

public function view(User $user, Project $project) {return $user->id === $project->user->id;}

Regards

22 Jan
9 months ago

mdeorue started a new conversation Register In Multiple Channels Laravel Echo

Hi guys, how are you?

I have a question and I dont found an answer that satisfied me.

I have an app of Soccer Teams, and a user can join multiple teams, so I want to send notifications when a action in a team occurs, for example, when a match is scheduled, I want to notify to the user.

I have channels like this.

new PrivateChannel('team.'.$this->team->id);

But I dont know how to register a User in multiple channel when its logged in.

The question is, I need to register to the channel of every team that the user belongs?

for($user->teams as $team){ Echo.private('team.'.$team->id) }

Or exists any other way that I can register the user to his channels?

Thank you very much, for your help, is very usefull for me.

09 Jan
10 months ago

mdeorue left a reply on Laravel Echo: Best Practices To Listen On Multiple Broadcast Channels

Hi guys, I want to ask you something about this. How Echo know the userID?

I need to put this id in a global variable? Or It came from Broadcast::channel authorization?

Regards.

03 Jan
10 months ago

mdeorue left a reply on How To Use Some Php Constants In Laravel

I put this in the model, like

const DRAFT = 1; const PUBLISHED = 2; ...

and in the Controller I use,

$post = new Post(); $status = $post::DRAFT;

or the scopes in the model,

public function published($query) { return $query->where('status', self::PUBLISHED); }

etc...

27 Nov
11 months ago

mdeorue left a reply on Realtion In Pivot Table

Hi, thanks for the reply, I actually do this, but the player_position is a related table to team_positions.

The team_positions table has... id | description

So I want to take this...

return $this->belongsToMany('App\Model')->withPivot('player_position')->with('position);

So for any team, I can take all the players and the position description in the team.

Thanks again.

mdeorue started a new conversation Realtion In Pivot Table

Hi guys,

I need your help, first sorry for my english, is too bad.

Well, I have 2 tables, teams and players, so I got a Many to Many relation, player_team, but in a team some players have different positions, like captain, etc... I made a column in player_team pivot table, that indicates the player position, captain, trainer, etc... And this column has a relation with player_positions.

I need that when I use belongsToMany relation I got the player_position relation eager load. So when I want the players of a team, I got there position too.

Thank you a lot for your help.

21 Aug
1 year ago

mdeorue left a reply on GroupBy Not Work In Laravel But Work In Mysql Console

Hi, sorry my english is too bad, but what do you want, ai ask you because if you want to group By in Mysql, this means that you need an aggregation. If you want to group all the results I will prefer use groupBy in the Collection.

So I will use $messages = Message:all() and then $groupedMessages = $messages->groupBy('column')

Regards

12 Jul
1 year ago

mdeorue started a new conversation Eager Loader Pivot Use Case

Hi guys, (first, my english is too bad) I got a use case that I been think but can resolve in a way that I like.

I have 3 tables of a soccer app...

Teams

  • id
  • description

Players

  • id
  • name

Player_Team

  • id_player
  • id_team
  • position

I need to add a new attribute "captain", so I think two ways...

  1. Put 'is_captain' (boolean) column in player_team pivot table.
  2. Put 'captain_id' foreign key in team table.

I think that the better way is the first. But when I eager load captain relation I have a Collection that only have one item (or null). So when I need to print this, I allways need to use first().

Is any way that you see that I can make a hasOne relation using the pivot table has a parameter.

This is what I got

Team model

public function captain() { return $this->belongsToMany('App\Player')->where('player_team.is_captain', true); }

AppController

$teams = Team::with('captain)->get()

Blade View

@foreach(teams as team) {{ team->captain->first()->name }} @endforeach

23 Jun
1 year ago

mdeorue left a reply on Delete All Records Except Latest 1000

Or maybe this.

´php

$deleteUs = Table::latest()->take($count)->skip(1000)->each(function($row){
$row->delete();

});

´

22 Jun
1 year ago

mdeorue left a reply on Delete All Records Except Latest 1000

In my opinion you want to use skip. Something like this.

DB::

02 May
1 year ago

mdeorue left a reply on Child Relation Data

I love you!

mdeorue started a new conversation Child Relation Data

Hi guys,

I ahve a question that I want to discuss with you. In my projects, a lot of time, I need to get the data of a relation of a realtion Model (I named it Child Relation).

The context, I have 3 tables, the first has a relation hasMany with the second, and the second has a relation hasMany with the third.

| Table 1 | ---> | Table 2 | ---> | Table 3 | | | | table_1_id | | table_2_id |

I want to get the third table data but only with the table 1 model. I made two things, but no one make me proud, so I want to ask you how you solve this theme in your projects.

First method (foreach): ´´´php

table1Controller
{
    public function someMethod(Table1 $table1)
    {
        $table2Data = $table1->table2()->with('table3')->get();
        $collection = new ...\Collection();
        foreach($table2Data as $data)
        {
            $collection->push($data->table3);
        }   
    }
}

´´´

Second method (fake relation): ´´´php

table1Controller {

    public function someMethod(Table1 $table1)
    {
        $table3Data = $table1->table3;
    }

}

table1Model {
    
    public function table3()
    {
        $table2IDs = $table1->table2()->pluck('id');
        return Table3::whereIn('table_2_id', $table2IDs);
    }

}

´´´

Regards.

23 Apr
1 year ago

mdeorue left a reply on InvalidPayloadException: 5 When I Use ShouldQueue

Hi guys, can you help me pls?

I tried a lot of things, but none worked.

Regards.

19 Apr
1 year ago

mdeorue started a new conversation InvalidPayloadException: 5 When I Use ShouldQueue

Hi guys,

I want to ask you some thing, I got a listener that when is trigger sync its works perfect, but when I use Illuminate\Contracts\Queue\ShouldQueue implementation I got this exception, Illuminate\Queue\InvalidPayloadException: 5. The problem is that the handle method in my listener is empty.

When I put something like a Info log, sync works perfectly, but queued give me that exception.

Maybe I made something wrong than I do not see.

this is the code of the listener.

namespace App\Listeners;

use App\Events\PeriodWasBilled;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use App\Mail\BillWasCreated as BillWasCreatedMail;

class SendBillNotificationToUser implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  PeriodWasBilled  $event
     * @return void
     */
    public function handle(PeriodWasBilled $event)
    {

        Log::info('Hi');
    }
}