mdeorue

Experience

23,010

7 Best Reply Awards

  • Member Since 3 Years Ago
  • 215 Lessons Completed
  • 0 Favorites

6th April, 2018

mdeorue left a reply on Paginating In A View? • 2 months ago

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

27th March, 2018

mdeorue left a reply on Search And Skip To Next Item In Collection • 2 months ago

You can use this snipet.

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

Regards

26th March, 2018

mdeorue left a reply on Where To Store Store Global Information ? • 2 months ago

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

Regards.

25th March, 2018

mdeorue left a reply on Relationship In Relationsip In Relationship With Limit • 2 months ago

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, • 2 months ago

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 • 2 months ago

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 • 2 months ago

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

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

Regards.

24th March, 2018

mdeorue left a reply on How To Count Auth User Visit The Page • 2 months ago

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

Regards.

23rd March, 2018

mdeorue left a reply on How Do Invitation's Work? • 2 months ago

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

mdeorue left a reply on Search Database With Multiple Filters • 2 months ago

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 • 2 months ago

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. • 2 months ago

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

´´´

20th March, 2018

mdeorue left a reply on SEARCH AND ORDER IN RELATED MODELS • 3 months ago

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

Regards

18th March, 2018

mdeorue left a reply on Operation In Eloquent ORM • 3 months ago

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 • 3 months ago

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

27th February, 2018

mdeorue left a reply on How To Find Nearest Cities From Latitude And Longitude • 3 months ago

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 • 3 months ago

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...) • 3 months ago

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

mdeorue left a reply on How Can I Use Flash Message After Axios Post? • 3 months ago

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? • 3 months ago

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...) • 3 months ago

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 • 3 months ago

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 • 3 months ago

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? • 3 months ago

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...) • 3 months ago

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? • 3 months ago

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

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

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

19th February, 2018

mdeorue left a reply on Issue Related With Pivot Tables • 4 months ago

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'));

´´´

23rd January, 2018

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

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 • 4 months ago

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 • 4 months ago

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

22nd January, 2018

mdeorue started a new conversation Register In Multiple Channels Laravel Echo • 4 months ago

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.

9th January, 2018

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

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.

3rd January, 2018

mdeorue left a reply on How To Use Some Php Constants In Laravel • 5 months ago

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...

27th November, 2017

mdeorue left a reply on Realtion In Pivot Table • 6 months ago

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 • 6 months ago

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.

21st August, 2017

mdeorue left a reply on GroupBy Not Work In Laravel But Work In Mysql Console • 10 months ago

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

12th July, 2017

mdeorue started a new conversation Eager Loader Pivot Use Case • 11 months ago

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

23rd June, 2017

mdeorue left a reply on Delete All Records Except Latest 1000 • 11 months ago

Or maybe this.

´php

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

});

´

22nd June, 2017

mdeorue left a reply on Delete All Records Except Latest 1000 • 11 months ago

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

DB::

2nd May, 2017

mdeorue left a reply on Child Relation Data • 1 year ago

I love you!

mdeorue started a new conversation Child Relation Data • 1 year ago

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.

23rd April, 2017

mdeorue left a reply on InvalidPayloadException: 5 When I Use ShouldQueue • 1 year ago

Hi guys, can you help me pls?

I tried a lot of things, but none worked.

Regards.

19th April, 2017

mdeorue started a new conversation InvalidPayloadException: 5 When I Use ShouldQueue • 1 year ago

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');
    }
}

6th April, 2017

mdeorue left a reply on Eager Load A Relation With Parameters • 1 year ago

Perfect, I see this, but if I want to eager load two periods (I know that is very special), but for example.

´´´php

public function someFuntion(BillingPeriod $actualPeriod, Group $group) { $previousPeriod = $actualPeriod->before(); $users = $group->users() ->with([ 'actualPeriodConsumption' => function ($query) use ($period) { $query->where('billing_period_id', $actualPeriod->id); }, 'previousPeriodConsumption' => function ($query) use ($period) { $query->where('billing_period_id', $previousPeriod->id); }, ]); }

class Property{ public function consumptions() { return $this->hasMany('App\Consumption'); }

public function actualPeriodConsumption()
    {
        return $this->hasOne('App\Consumption');
    }

public function previousPeriodConsumption()
    {
        return $this->hasOne('App\Consumption');
    }

}

´´´

I dont want to make three equals methods. Is any way to do this, or I'm asking nonsense.

Regards

mdeorue started a new conversation Eager Load A Relation With Parameters • 1 year ago

Hi guys,

First, sorry for my english, is very bad. I will try to express myself well.

I have a group that have many users that have differents types of expenses, for example, consumptions, and the consumptions have billing_periods, so in differentes billing_periods I have differents consumptions for any user so

class Consumption{

    $columns = ['amount', 'user_id', 'billing_period_id'];

}

With this I have a billing period and the group, and I want to get all the users with the consumptions of this period.

class User{

    public function consumptions()
    {
        return $this->hasMany('App\Consumption');
    }

    public function periodConsumption(BillingPeriod $period)
    {
        return $this->hasOne('App\Consumption')->where('billing_period_id', $period->id);
    }

Can I eager load the periodConsumption relation? How can I pass the parameter to the eager load relation?

I want to do this...

class UserController{

    public function someFuntion(BillingPeriod $period, Group $group)
    {
        $users = $group->users()->with('periodConsumption($period)')->get()
    }

Thank you very much for all the help.

Regards.

27th March, 2017

mdeorue left a reply on Where Are You All From? • 1 year ago

Santiago, Chile

9th February, 2017

mdeorue started a new conversation Pass A Model In Custom Package Through Constructor • 1 year ago

I guys,

I need your help, I create a custom package (I am a noob in this), and I need to pass through the constructor of this package a Model, this package calculate different KPI of the Model.

For Example...


class CustomPackage{

    protected $model;   

    public function __construct(Model $model)
    {
        $this->model = $model;
    }
}

class CustomPackageServiceProvider extends ServiceProvider
{
    public function boot()
    {
    //
    }

    public function register()
    {
        $this->app->bind('custompackage',function(){
            return new CustomPackage(new \App\Model);
        });
    }
}

class ModelController extends Controller
{
    public function getKPI(Model $model)
    {
        $package = new \CustomPackage($model);
    }
}

When I dd the $package, I return a model attribute null.

Can you help me with this please, I can resolve this with a Package method that set the Model, but I think that is a better way.


class CustomPackage{

    protected $model;   

    public function setModel(Model $model)
    {
        $this->model = $model;
    }
}

Thanks for your help, Regards.

mdeorue left a reply on Multiple Form Request In The Same Controller Method • 1 year ago

Perfect, I had not thought that.

You know any way to "fake" a FormRequest, to send via Controller?

I tried,

´´´php

$user->newUser(new StoreUser($request->all());

´´´

but it dosnt work.

Thank you very much from Chile.

8th February, 2017

mdeorue started a new conversation Multiple Form Request In The Same Controller Method • 1 year ago

Hi guys,

First, sorry for my english, is very bad, but I need your help, please.

I have a method that search if a given user exists, if do not exists I need to create. In a form the user (of the app), enter all the inputs of a User, but if exist the name, use the created user.

For this I want to use two Form Request, the first validate if the search value exists and if minimun 4 characters, and the seconds validate all the user data to create.

But I cant instantiate the second Form Validation, because I have a dismatch between the second Form Request with the First one.

First Form Request: ExistUser Second Form Request: StoreUser

public function assignUser(ExistUser $request, Community $community)
{
    $user = User::findByName($request->name);
    if(!$user)
    {
        $user = $this->newUser($request);
    }
    ...
}

public function newUser(StoreUser $request)
{
    return User::create($request->all());
}

This is an abstract of the code, by explain that I have to do.

I appreciate your help.

Regards.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.