RafaelMunoznl

RafaelMunoznl

Software developer at AllMyHomes GmbH, Berlin

Member Since 1 Year Ago

Berlin

Experience Points
22,240
Total
Experience

2,760 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
208
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.

Level 5
22,240 XP
Dec
14
21 hours ago
Activity icon

Replied to Memory Exhausted After So Much Loops. Back To Eloquent

@willvincent the reason I want a hour as a key is that in the frontend I need to put all those apointments in a calendar and the best way to sort them is to loop through the hour (the key). I am doing it already, but it means looping until the memory got exhausted.

Dec
13
1 day ago
Activity icon

Started a new Conversation Memory Exhausted After So Much Loops. Back To Eloquent

I have been working for a while in a application which turned very slow. The reason is that I have been manipulatig the results of a query to get the data in the needed structure to pass it to the front end. I mean tons of looping and conditionals.

The point is that need to transfor this, that got this from the Database:

Collection {#5810 ▼
  #items: array:1 [▼
    "Marianne" => Collection {#5809 ▼
      #items: array:6 [▼
        0 => Appointment {#4742 ▼
          ...
          #attributes: array:16 [▼
            "id" => 190
            "company_id" => 2
            "employee_id" => 4
            "client_id" => 71
            "offer_id" => 8
            "startDateTime" => "2019-12-04 09:00:00"
            "endDateTime" => "2019-12-04 10:00:00"
            "created_at" => "2019-12-10 19:49:34"
            "updated_at" => "2019-12-10 19:49:34"
          ]
          ....
        }
        1 => Appointment {#4743 ▶}
        ...
        35 => Appointment {#4747 ▶}
      ]
    }
  ]
}

Into this:

array:1 [▼
  "Marianne" => array:5 [▼
    "09:00" => Appointment {#6050 ▼
            ...
          #attributes: array:16 [▼
            "id" => 190
            "company_id" => 2
            "employee_id" => 4
            "client_id" => 71
            "offer_id" => 8
            "startDateTime" => "2019-12-04 09:00:00" // I use this hour "09:00:00" as array key.
            "endDateTime" => "2019-12-04 10:00:00"
            "created_at" => "2019-12-10 19:49:34"
            "updated_at" => "2019-12-10 19:49:34"
            ...
          ]
        ...
    }
    "10:00" => Appointment {#6052 ▶}
    "13:00" => Appointment {#6054 ▶}
    "14:00" => Appointment {#6055 ▶}
    "15:00" => Appointment {#6056 ▶}
  ]
]

Notice that there is not other difference than using the hour in startDateTime as key of the array.

In order to get that hour as key I was looping trough all the appointments of each employee of each company , each day, extracting the hour from the carbon, with several condictionals in between until I have got the error

"memory exhausted".

My second Approach is to try to get that structure directly from the database using MySQL and eEoquent. After making literally hundreds of intends without success, the closest I got is using PLUCK.

I wonder if I could do something like pluck('time', function). And this is my "solution".

        $query = Appointment::join('employees', 'employees.id', 'appointments.employee_id')
            ->join('users', 'users.id', 'employees.user_id')
            ->join('offers', 'offers.id', 'appointments.offer_id')
            ->join('clients', 'clients.id', 'appointments.client_id')
            ->where('appointments.company_id', $companyId)
            ->whereDate('startDateTime', 'like', '%' . $datum . '%')
            ->orderBy('appointments.employee_id')
            ->orderBy('appointments.startDateTime')
            ->pluck('appointments.startDateTime', function($query)
                {
                    select(
                        'appointments.*',
                        'offers.title As offer',
                        'clients.lastname as client',
                        'users.firstname as employee'
                    )
                )->get()->groupBy('employee');

However againn I got an error:

stripos() expects parameter 1 to be string, object given

But this time I have not idea what does that error means, where is the object,

Could anybody tell me what am I doing wrong in that query?

Dec
07
1 week ago
Activity icon

Started a new Conversation Policies Returning To Different Views Instead Trowing A 403

Hi there,

I have implemented several policies to filter different actions. For example:

  • User deleted himself its profile
  • User was suspended
  • User still didn't confirm his email address
  • User has not been reactivated for the admin after a suspension

In all those cases the User is not allowed to visit the profile page, but for different reasons.

But policies just throw the same message: This action is unauthorized. which is not very user friendly.

So my desire is to redirect the user to a different page in each case giving a differnt reason why he can't visit the page.

So I did this in a UserDeletedPolicy file:

    public function view(User $user, Profile $profile)
    {
        if ($profile->status === 'deleted') {
             $message = "Profile deleted. Please contact the admin if you think it is an error";
            return view('errors.profile_deleted', compact('user', 'profile', 'message'));
        } 
        else if {
           $message = "You have to confirm your email."
            return view('errors.confirm_email', compact('user', 'profile', 'message'));
       } else {
     // hier the case of suspension 
       }
    }

but it does not work.

Any idea how could I achieve sometihng like this?

Dec
01
1 week ago
Activity icon

Replied to "Joint" Tables And Get All Even If It Does Not Meet The Conditions

@bobbybouwmann thanks for the answer. I suppose that is why I was trying for a while without success

Activity icon

Started a new Conversation "Joint" Tables And Get All Even If It Does Not Meet The Conditions

I have this query:

Appointment::join('employees', 'employees.id', 'appointments.employee_id')
            ->join('users', 'users.id', 'employees.user_id')
            ->join('offers', 'offers.id', 'appointments.offer_id')
            ->join('clients', 'clients.id', 'appointments.client_id')
            ->where('appointments.company_id', $companyId)
            ->whereDate('startDateTime', 'like', '%' . $datum . '%')
            ->orderBy('appointments.employee_id')
            ->orderBy('appointments.startDateTime')
            ->select(
                'appointments.*',
                'offers.title',
                'clients.lastname',
                'users.lastname',
                'employees.*'
            )
            ->get()
            ->groupBy('employee_id');

It gives me back the appointment per day, grouped per employee, like this:

Collection {#3158 ▼
  #items: array:7 [▼
    4 => Collection {#3163 ▼
      #items: array:5 [▼
        0 => Appointment {#1108 ▶}
        1 => Appointment {#1107 ▶}
        2 => Appointment {#1053 ▶}
        3 => Appointment {#1109 ▶}
        4 => Appointment {#1111 ▶}
      ]
    }
    5 => Collection {#3200 ▶}
    6 => Collection {#3599 ▶}
    7 => Collection {#3135 ▶}
    8 => Collection {#3162 ▶}
    9 => Collection {#3133 ▶}
    11 => Collection {#3157 ▶}
  ]
}

Is fine, but the list have just 7 employees and the company has eight employees. The employee with id = 8 does not have any appointment in that given day (sick, holidays, whatever).

So, If one employee does not have appointments, it wont be shown in tis results. In this case the employee with id "8" is not in the collection.

This is not a bug because the JOIN joints the columns that meet that condition, but...

How could I make happens that all employees get in the collection? Even if they do not have appointments. If the employee does not have appointment I want to get something like:

...
8 => Collection {#3163 ▼
      #items: array:0 [▼
        0 => []
      ]
    }

I have tried, but I do not know how to get it

Nov
28
2 weeks ago
Activity icon

Replied to Add Time Data Format To Date Time Format

@snapey NO, I did not have control over it. But I did implemented a very similar solution that @bobbybouwmann was explaining in the first answer. Thanks you both

Nov
27
2 weeks ago
Activity icon

Replied to Add Time Data Format To Date Time Format

@sinnbeck no, duration is not a date. It is a time data type formatted like: 00:30:00

Activity icon

Replied to Add Time Data Format To Date Time Format

@snapey I have added "duration" to the date array.

    protected $dates = ['deleted_at', 'duration'];

It is a Time format data.

Is it not correct to add it to the $dates array?

Activity icon

Started a new Conversation Add Time Data Format To Date Time Format

I have a carbon instance in the variable $startTime:

 Carbon @1574958600 {#781 ▼
  date: 2019-11-28 16:30:00.0 UTC (+00:00)
}

I have in the column "duration" of table OFFERS in the DB (time format) 30 minutes in this format: 00:30:00

Now I want to add those 30 minutes to the $startTime.

I get the data from DB:

$offer = Offer::select('duration')->where('id', $offerId)->first();

It works correctly. and I try to store that value into a variable $duration

$duration = $offer->duration;

and I get this error: Unexpected data found. Unexpected data found. Data missing

I supposed I have to format this stringto Carbon, so I did:

$duration = Appointment::setDateAttribute($offer->duration);

I got again the error: Unexpected data found. Unexpected data found. Data missing

And now I am lost.

I just wanted to make a simple addition:

$endTime = $startTime + $offer->duration;

But I am stock with this since hours.

Any idea what am I doing wrong?

Another though was:

Is it possible to make this operation in a query and add the 30 minutes 'on the fligh' while I get the duration? Somehow pass the variable $startTime to the query and do something like:

$duration= Offer::where('id', $offerId)
->whereHas('duration', function ($query) {
                $query->get('duration', 'and add the $startTime variable here'); // <- make the calculation here
            })
->select('duration as duration', 'endTime') // endTime would be the calculated data
->first();

Either one or another solution. But at the moment I am stock with this

Nov
23
3 weeks ago
Activity icon

Replied to Pack A Selected Date From The Datepicker In A Variable And Send It To The Controlle

@snapey Great! It worked just with a little twick. In order to work the route should be POST, not GET

Route::post('{company}', '[email protected]')->name('salon.show'); 
Activity icon

Replied to Pack A Selected Date From The Datepicker In A Variable And Send It To The Controlle

@tray2 but 'date' is still a string. I am not getting the date type format from the picker. That is my problem. I am sending a variable named $company and a string: 'date'.

Activity icon

Started a new Conversation Pack A Selected Date From The Datepicker In A Variable And Send It To The Controlle

I have never worked with datepickers before and I am struggling with something that might be very simple

I am building a calendar and I want to allow users to navigate to any given day chosen in a datepicker.

My code is like that:

The method in the controller:

    public function show(Company $company, $date = null)
    {
        $date = Carbon::parse($date);
    }

The route:

Route::get('{company}/{date?}', '[email protected]')->name('salon.show');   

The form in HTML

<form action="{{route('salon.show', [$company, 'date'])}}" method="GET">
    {{ csrf_field() }}
    {{ method_field('GET') }}
    <label class="input tag form-control">
        <input name="date" type="date" value="date" id="date">
        <button class="btn heute text-center" type="submit">Senden</button>
    </label>
</form>

Let's say I select the Nov. 27, 2019 in the date picker. The I see the URL something like this:

http://project.test/company/date?_token=wlUxABTbnZy6jeAbAwxDVVs9JdxkycUx7GBTx4GE&_method=GET&date=2019-11-27

Note that 'date' is passed in the URL, behind the company, so the routing is working properly sending $company and 'date'.

But I get the following error:

DateTime::__construct(): Failed to parse time string (date) at position 0 (d): The timezone could not be found in the database

It is logic since I'm pasing a string in the form. Here -> <form action="{{route('salon.show', [$company, 'date'])}}" method="GET">

But if I change to a variable $date. That variable does not exist and I get an error.

The question is.

How do I pack the selected date from the datepicker in a variable and send it to the controller?

Nov
20
3 weeks ago
Activity icon

Replied to GroupBy After Or Before GET()

@nakov , Thanks I will test. Thanks for your help @rodrigo.pedra. Thanks also for the explanantion. I did not know that.

Activity icon

Replied to GroupBy After Or Before GET()

@nakov Yes, I removed the select and it worked as expected. But in that way I am getting all the columns of the columns. Eventually I will need to join another couple of tables, so at the end I am getting a huge amount of data that I won't use.

Is there not possibility to fliter down the columns?

Activity icon

Started a new Conversation GroupBy After Or Before GET()

I want to group the results of a query per employee:

This work (groupBy after get() ):

$newDay = Appointment::when($employeeId, function ($query, $employeeId) {
                $query->where('employee_id', $employeeId);
            })
                ->where('company_id', $companyId)
                ->whereDate('startDateTime', 'like', '%' . $datum . '%')
                ->orderBy('employee_id')
                ->orderBy('startDateTime')
                ->select('company_id', 'employee_id', 'client_id', 'startDateTime', 'endDateTime')
                ->selectRaw('appointments.*, TIMESTAMPDIFF(minute, startDateTime, endDateTime) as duration, TIMESTAMPDIFF(minute, startDateTime, endDateTime) / 15 as rows')
                ->get()
                ->groupBy('employee_id');

This does not work (groupBy before get() ):

$newDay = Appointment::when($employeeId, function ($query, $employeeId) {
                $query->where('employee_id', $employeeId);
            })
                ->where('company_id', $companyId)
                ->whereDate('startDateTime', 'like', '%' . $datum . '%')
                ->orderBy('employee_id')
                ->orderBy('startDateTime')
                ->select('company_id', 'employee_id', 'client_id', 'startDateTime', 'endDateTime')
                ->selectRaw('appointments.*, TIMESTAMPDIFF(minute, startDateTime, endDateTime) as duration, TIMESTAMPDIFF(minute, startDateTime, endDateTime) / 15 as rows')
                ->groupBy('employee_id')
                ->get();

I get following exception:

Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'friseur-oktober.appointments.company_id' which is not functionally dependent on columns in GROUP BY clause;

I would go with the second approach, but, as I understand this grouping is made AFTER fetching data from the database, not done by the database server. Which could lead to performance issues.

However, "the right way" does not work. The question is why? Am I doing something wrong?

Nov
18
3 weeks ago
Nov
17
3 weeks ago
Activity icon

Replied to Calculate Time Difference In Eloquent Query

@tykus Thanks a lot! It wors perfect!

What do you mean with "adding it as Global Scope"?

Activity icon

Started a new Conversation Calculate Time Difference In Eloquent Query

I have a Collection with the following structure;

Collection {#6467 ▼
  #items: array:7 [▼
    0 => Appointment {#6459 ▼
    ...
      #attributes: array:9 [▼
        "id" => 1092
        "company_id" => 2
        "employee_id" => 5
        "client_id" => 31
        "notes" => "Fugiat reprehenderit cumque rerum error quia aliquam ut autem dolor doloremque adipisci est fugiat quia dolorum ut voluptates itaque qui impedit enim nobis."
        "startDateTime" => "2019-11-18 11:00:00"
        "endDateTime" => "2019-11-18 12:00:00"
        "created_at" => "2019-11-15 18:55:55"
        "updated_at" => "2019-11-15 18:55:55"
      ]
      #original: array:9 []
      ....
     
    1 => All other appointments...

In frontend I need the duration of the appointment. At the moment I am making a foreach loop gping through each appointment, calculate the duration like this:

foreach( $appointments as $appointment)
    $duration = $appointment->endDateTime - $appointment->startDateTime
    //Add to the appointment
    $appointment->duration = $duration
}

It works but since I have potentially hundreds of Appointments (10 per day per each employee per each company) this process slows down the app.

So I wonder if I could calculate the duration (endDateTime - startDateTime) in the query and add it to the collection. So I did this:

$newDay = Appointment::>whereDate('startDateTime', 'like', '%' . $datum . '%')
  ->orderBy('startDateTime')
  ->select(
     'appointments.*',
     'duration',
          function ($q) {
               $q->raw('appointment->endDateTime' - 'appointment->startDateTime');
          }
     )
  ->get();

But I do get the following error:

stripos() expects parameter 1 to be string, object given

What am I doing wrong?

Nov
15
4 weeks ago
Activity icon

Replied to Call To Undefined Method Carbon\Carbon::isoFormat()

@nakov thanks I will have to update.

Activity icon

Replied to Call To Undefined Method Carbon\Carbon::isoFormat()

@sinnbeck I did now composer install and got the following answer:

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for doctrine/lexer 1.1.0 -> satisfiable by doctrine/lexer[1.1.0].
    - doctrine/lexer 1.1.0 requires php ^7.2 -> your PHP version (7.1.23) does not satisfy that requirement.
  Problem 2
    - doctrine/lexer 1.1.0 requires php ^7.2 -> your PHP version (7.1.23) does not satisfy that requirement.
    - egulias/email-validator 2.1.11 requires doctrine/lexer ^1.0.1 -> satisfiable by doctrine/lexer[1.1.0].
    - Installation request for egulias/email-validator 2.1.11 -> satisfiable by egulias/email-validator[2.1.11].

So, if I understand right, the PHP version (7.1.23) in that particular computer does not meet the required version (7.2).

Correct?

Activity icon

Replied to Call To Undefined Method Carbon\Carbon::isoFormat()

@sinnbeck yes I ran composer dump-autoload

@nakov thanks I will change it.

Activity icon

Started a new Conversation Call To Undefined Method Carbon\Carbon::isoFormat()

It might sound stupid, but is a fact:

I am building an App at home. I have tested it in two different Windows computers. It works perfectly.

The same app in a MAC computer throws following errors:

Call to undefined method Carbon\Carbon::isoFormat()

then I change isoFormat against just format() and a new error arises:

Method Illuminate\Support\Carbon::translatedFormat does not exist.

I do the same operation changing all those functions against plain format() and the app starts.

However, since I am working with German date format and 'locale' => 'de', the app does not work properly.

Is there any place or config that I have to change

Nov
13
1 month ago
Activity icon

Replied to Best Practice To Avoid Three Almos Identical Controllers?

Ok, if I understand well, I pack all the repetitive task out of CompaniesController (and the two others) into the new XController? Does this new XController has a "return" ( variables or views)?

I will try it!

Thanks

Activity icon

Started a new Conversation Best Practice To Avoid Three Almos Identical Controllers?

I have three very similar controllers: EmployeesController and Companiescontroller and RegionsController

They have almost not logic at all. All what they do is to calls a lot of methods in different services and models, get the results and pass then each to a different views. All those But these calls are all identical, like this:

    public function show(Company $company, User $user,  $date = null)
    {
        if (Auth::user()->email !== $user->email) {
            return view('errors.not_allowed');
        }
        $page_name = 'users';
        $index = 'show';
        $element = $user;

// From this point onwards the calls are identicals 
        $today = substr(today(), 0, 10);
        $employees = User::getEmployees($company->id);
        $date ? $currentDay = $date : $currentDay = today();
        $openingHours = Openinghour::getOpenings($company->id);
        $element->completeName = $user->getCompleteNameAttribute();
        $daysView = Appointment::daysView($company->id, $currentDay, $user->id);
        $futureAppointment = Appointment::futureAppointment($company->id, $currentDay, $user->id);
        $calendar = Appointment::organizeAppointment($daysView['currentDay']['appointments'], $employees, $openingHours);
/// end of identical calls here

return view( ‘the-particular-view-here’, compact(‘variables here’)  );

The point is that I am repeating in three times the same calls. Since I am still coding, each time I change something, I have to do it three times (or it breaks somewhere else).Is there any best-practice approach to such a situation? Perhaps a super-controller passing to a view with a condition (IF loop)?

Nov
12
1 month ago
Activity icon

Started a new Conversation Is Possible To Build Eloquent Queries With Optional Parameters?

I am running two queries that are pretty much the same, one for ALL users and given the ID one for an specific user.

Instead using two methods that would be practically the same, I am using just one and passing the ID as option like this:

public function otherDay($date, $employeeId = null)
   { … 

But now I want to hold the appointments from the previous day and the next day. And the issue repeats itself. I am passing a flat $str that could be previous or next. My method looks now like this:

   public static function otherDay($date, $str, $employeeId = null)
   {

Then I sort all the condictions using IF statements:

$str == 'previous' ? $datum = ($date)->subDays(1) : $datum = ($date)->addDays(1);
$datum = substr($str->translatedFormat('d M Y'), 0, 10);

if (isset($employeeId)) {
 $newDay = Appointment::where('employee_id', $employeeId)->whereDate('date', 'like', '%' . $datum . '%')->get();
} else {
 $newDay = Appointment::whereDate('date', 'like', '%' . $datum . '%')->get();
}

I am publishing here a simplification of much longer queries. In real life they are much longer. I use with, select and where all over the place

They are in fact the same with the only difference of this statement:

where('employee_id', $employeeId)

My question is: Is it possible to pass optional subqueries and get rid of the IF statement and run just one query dynamically. Something like this:

$subq = “->where('employee_id', $employeeId)”

And then make:

$newDay = Appointment:: . $subq . ->whereDate('date', 'like', '%' . $datum . '%')->get();

I am having the similar problem everywhere in my App. I have to choose between:

  • all users or one user
  • previosday or nextday
  • manager or employee
  • client or superclient

Therefore, I would almost cut my methods or queries to the half.

Any suggestion?

Nov
06
1 month ago
Activity icon

Replied to Loop Inside A Loop. Continue At The Index+1 Where The Intern Loop Stop

The problem with making it in the database is that I will have to join several tables ising DB facade and I won't be able to compare dates in Carbon format. I will get this error:

Call to a member function format()

when I try:

{{ $appointment->date->format('H:i') }}
Activity icon

Replied to Loop Inside A Loop. Continue At The Index+1 Where The Intern Loop Stop

@shez1983 I am reading the appointment from the DB. The second (Intern) if just add a link to add a new appointment.

  • I can pass as much as I can to the controller, but at the end I will have to loop through the resulting collection/array in the frontend. (or I think)
Activity icon

Started a new Conversation Loop Inside A Loop. Continue At The Index+1 Where The Intern Loop Stop

This is a kind of twit togue, but I try to explain as good as I can.

I have a loop inside a loop as you could see here:

@for($i = 8; $i <= 17; $i++) // These are the hours. From 8:00 hour to 17:00 hour (German hour format)

    @foreach($employee->appointments as $appointment) // I take the appointment of each employee
    
        @if( $appointment->date->translatedFormat('D j M') != today()->translatedFormat('D j M')) 
            
            @continue //if the appointment is not from today, continue
            
        @else
            @if( $appointment->date->format('H') != $i )
                <h3> <a href="link_to_create_appointment_form">Add an appointment</a></h3>
                // insert a link to create a new apppointment
            @else
                // insert the Appointment
            @endif
            
        @endif
    @endforeach
@endfor

My problem is as follow:

  • After the first appointment is inserted (Appointment == today && now()), the foreach goes to next appointment, but start from the beginning.

  • At the end if I have an appointment at 9:00 and another at 10:00 I get the following:

8:00 - add an appointment
9:00 - APPOINTMENT 1
8:00 - add an appointment  // <---- the ouside loop started from the beginning of the day
9:00 - add an appointment
10:00 - APPOINTMENT 2

You could see an image in the following link: http://severus.es/wp-content/uploads/2019/11/termin-plan.png

The question is:

  • How could I force the following loop of the foreach to start in the (index + 1) of the previous loop (where the previous appointemnt was inserted)?

I have tried the whole day using @loop, @index, but with not success.

Any idea?

Nov
05
1 month ago
Activity icon

Replied to Trying To AddHours Using Carbon I Get: Unexpected Data Found.

I have changed the data type from TIMME to DATETIME and it works. I do not need the day. month and year, but it makes it anyway.

Thanks

Activity icon

Replied to Trying To AddHours Using Carbon I Get: Unexpected Data Found.

@tykus: Sorry I let a wrong answer before.

The problem islike you said: the data type of open_at and close_at are not in format: '2019-11-05 12:34:56' because they are TIME data type. It stores the opening time of the store, there for is just '09:00:00'

Does it means that Carbon needs the DATETIME data type in order to add onr hour?

Activity icon

Replied to Trying To AddHours Using Carbon I Get: Unexpected Data Found.

@tykus: Sorry I let a wrong answer before.

The problem islike you said: the data type of open_at and close_at are not in format: '2019-11-05 12:34:56' because they are TIME data type. It stores the opening time of the store, there for is just '09:00:00'

Does it means that Carbon needs the DATETIME data type in order to add onr hour?

Activity icon

Replied to Trying To AddHours Using Carbon I Get: Unexpected Data Found.

@sinnbeck : Yes, you are right. I did a mistake when I was posting it in Laravel. In the app is ok

Activity icon

Replied to Trying To AddHours Using Carbon I Get: Unexpected Data Found.

I get a collection like this:

Collection {#15822 ▼
  #items: array:5 [▼
    0 => Openinghour {#15816 ▼
      #fillable: array:5 [▶]
      ...
      #original: array:8 [▼
        "id" => 1
        "company_id" => 2
        "working_day" => "dienstag"
        "open_at" => "09:00:00"
        "close_at" => "17:00:00"
        "pause" => "12:00:00"
        "created_at" => null
        "updated_at" => null
      ]
      ...
    }
    1 => Openinghour {#15817 ▼
      #fillable: array:5 [▶]
      ...
      #attributes: array:8 [▼
        "id" => 2
        "company_id" => 2
        "working_day" => "mittwoch"
        "open_at" => "09:00:00"
        "close_at" => "17:00:00"
        "pause" => null
        "created_at" => null
        "updated_at" => null
      ]
      ...
    }
    2 => Openinghour {...}
    3 => Openinghour { ...}
    4 => Openinghour {...}
  ]
}

Of course there are a lot more stuff. I just have cut it in order to show it here

Activity icon

Started a new Conversation Trying To AddHours Using Carbon I Get: Unexpected Data Found.

I have the following Model "Openinghour" wich has following attributes:

    protected $fillable = [
        'company_id', 'open_at', 'close_at', 'working_day', 'pause'
    ];

I am using Carbon (imported at the top): use Carbon\Carbon;

and declaring: protected $dates = ['open_at', 'close_at', 'pause'];

Now I want to get a collection with hours per day like this:

[
    monday => { "09:00:00", "10:00:00", "11:00:00", "12:00:00", "13:00:00", "14:00:00", "15:00:00", "16:00:00", "17:00:00"}
    tuesday => {....}
    wednesday => {....}
    thursday => {....}
    friday => {....}
    saturday => {"09:00:00", "10:00:00", "11:00:00", "12:00:00", "13:00:00"}
]

For that I did:

    public static function getOpenings($id)
    {
        $openingHours = Openinghour::where('company_id', '=', $id)->get();

        $data = [];
        $weekday = [];
        foreach ($openingHours as $day) {
            array_push($weekday, $day->working_day);
            for ($t = $day->open_at; $t < $day->close_at; $t->addHour()) {
                $weekday[count($weekday - 1)] = $t;
            };
        }
        
        return $openingHours;
    }
}

But I get the following error: Unexpected data found. Unexpected data found. Data missing

What am I missing?

Activity icon

Started a new Conversation Get Resulte WHEREHAS Is A Condition In A Related Table/model

Hi there,

I have a three models/tables: Users, Employee and Appointments

The relations are : User hasOne Employee Employee hasMany Appointments User hasManyThrough Appointments

Appointments table has a 'date' column which is a DATETIME type data.

I manually seeded the database with one appointment for user.id = 1 on today '2019-11-05 09:00:00'

I am trying to get the Appointments of the day of every employee and each employee. So I did:

        $todayAppointments = User::where('user_id', '=', $user->id)
            ->with('appointments')
            ->with('employee')
            ->whereHas('appointments', function ($query) {
                $query->where('appointments.date', '=', today());
            })
            ->get();

But the results in $todayAppointments comes empty. If I delete the whereHas statement, I get the one appointment and the rest of the appointmnets in other days.

I could use DB::table('users')->join.... but I would lose the advantage of the Eloquent relations, which I am using all around in my application.

Am I missig something?