RafaelMunoznl

RafaelMunoznl

Software developer at AllMyHomes GmbH, Berlin

Member Since 2 Years Ago

Berlin

Experience Points
27,080
Total
Experience

2,920 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
245
Lessons
Completed
Best Reply Awards
0
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 6
27,080 XP
Mar
04
4 weeks ago
Activity icon

Replied to Does It Worth To Change The Database Structure To Store Data As Arrays?

@sti3bas

  • Yes, i will need to store the openingtime of each office. So they could edit it whenever they want.
  • I suppose, when you say : $model->openingHours()->isOpen('sundays) I have to use my model: Office $office->openingHours()->isOpen('sundays)

I will have to go step by step, because it is totally new to me and basically i will need to extend the ppackage with some more specific methods like for example:

give me allOffices Openinghours

give me the Offices that open on Saturday afternoon"

give the offices that were open on Christmass last year"

So, I will have to play arounda lot with the package before i jump into this

Thanks a lot man!

Activity icon

Replied to Does It Worth To Change The Database Structure To Store Data As Arrays?

@sti3bas It is the first time I would use a package and I am confused how to go or to do.

After I installed the package by doing: composer require spatie/opening-hours all changes i have are in two files: composer.json and composer.lock I ran composer update and composer install with not further changes

The documentation starts straight to this sentence:

// Add the use at the top of each file where you want to use the OpeningHours class:

But:

  • Should I create a Model, with which attributes?
  • Should I create a database? With which structure?

I have being searching for a more extended documentation, but i did not found any. Do you know any documentation/tutorial/examples on how to Start using this package?

Mar
03
4 weeks ago
Activity icon

Replied to Does It Worth To Change The Database Structure To Store Data As Arrays?

@sti3bas I did not know the package. I think I will give it a try.

Activity icon

Started a new Conversation Does It Worth To Change The Database Structure To Store Data As Arrays?

I have following problem.

I wrote a simple app to manage the openinghours each day the week of my office. The data was stored in a simple manner like this:

    public function up()
    {
        Schema::create('openinghours', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('office_id')->unsigned()->index()->default(1);
            $table->integer('week_day');
            $table->time('open_at')->nullable();
            $table->time('close_at')->nullable();
            $table->time('pause_start')->nullable();
            $table->time('pause_end')->nullable();
            $table->timestamps();
        });
    }

Now the manager want to add more offices to this application. Each office has its own schedule. This structure works. However, I think that it would be much better if I store the data of each array. Like this:

    public function up()
    {
        Schema::create('openinghours', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('office_id')->unsigned()->index()->default(1);
            $table->string('data')->nullable();
            $table->timestamps();
        });
    }

Inside the array I should have the following attributes: week_day', 'open_at', 'close_at', 'pause_start' and 'pause_end'

The structure will be something like this:

INSERT INTO `openinghours` (`id`, `office_id`, `data`, `created_at`, `updated_at`) VALUES
(1, 2,  
     {
    (1: '', '', '', ''),                                          // <- Sunday
    (2, '09:00:00', '18:00:00', '12:00:00', '12:45:00') , // <- Monday
    (3, '09:00:00', '18:00:00', '12:00:00', '12:45:00'), // <- Tuesday
    (4, '09:00:00', '18:00:00', '12:00:00', '12:45:00'), // <- Wednesday
    (5, '09:00:00', '18:00:00', '12:00:00', '12:45:00'), // <- Thursday
    (6, '08:00:00', '13:00:00', '', ''),                // <- Friday
    (7, '', '', '', '' )                                    // <- Saturday
     }
, '2020-02-28 04:30:57', '2020-02-28 04:30:57');

I see the advantage that once an user wants to edit, it would be easier to get the whole packet of an office, edit any day and save it complete; instead editing day by day as before when it was just one office.

Weekdays I have already inside a config file.

My questions are:

  • Should office_id be a column outside of the array (easier to search) or inside the data array
  • Should stamps be inside or outside the array? keeping track of changes in each day or a packet as a whole?
  • I suppose I could serialize and de-serialize as JSON the data in a repository to save or read the data

And the most important question:

  • Does it worth do something like this? I am afraid that the code will be much more complex:

is there any tutorial where I could see a solution like this?

Activity icon

Replied to Delete Files From Storage

@sti3bas Oh! Thanks. now it works. Thanks a lot

Activity icon

Replied to Delete Files From Storage

@sti3bas In my data base I just store this string:

avata_location = 'avatars/misi1-1583236599.jpg'

The full URL is in the $request variable.

When I click on the submit button I get the $requestvariable like this:

    #parameters: array:7 [▼
      "_token" => "6pQ4rchK4KrrO2O85T1bse3ZC1FejA0lggWXNp1v"
      "_method" => "PUT"
      "avatar_type" => "gravatar"
      "client_id" => "1"
      "email" => "[email protected]"
      "avatar_location" => "http://violeta-app.test/storage/avatars/misi1-1583236599.jpg"`// <- url
      "company_id" => "2"
    ]
  }

and that is what I want to delete when I do: Storage::disk('public')->delete($request->avatar_location);

Should I not use the full url to delete whe I use Storage facade?

Activity icon

Replied to Delete Files From Storage

@sti3bas the output is:

https://mydomain.com/storage/avatars/avatar-1583231825.png

the file exist in that position. i can see and download it

Activity icon

Replied to Delete Files From Storage

@sti3bas No before, but I tested it now.

It does not work

Activity icon

Started a new Conversation Delete Files From Storage

I am using the storage directory to uploa the avatars of my users.

The structure is like this: storage/app/public/avatars/file.jpg

I am able to upload avatars without problem, but when the user decides to change the avatar, I need of course, to delete the previous avatar. i have been trying to implement the method described here: https://laravel.com/docs/5.8/filesystem#deleting-files.

I did this:

<?php

namespace App\Models\Client\Traits\Method;

...
use Illuminate\Support\Facades\Storage; // <- Call the facade
...


trait ClientMethod
{

    public static function getPicture($request, $size = false)
    {  

        Storage::delete($request->avatar_location); //<- here I intend to delete the file in https://mydomain.com//storage/avatars/rasputin-1583231825.png
        
       // more code here
    }
}

The file exist in that location. I can download it. Everything looks like the documentation, but it does not get deleted.

Am I missing something?

Feb
21
1 month ago
Activity icon

Replied to 500 Error: Cannot Serve Directory - No Matching DirectoryIndex Found

@sinnbeck

After accessing to the laravel.log file I found this:

[2020-02-21 15:48:39] local.ERROR: SQLSTATE[HY000]: 

General error: 1364 Field 'id' doesn't have a default value

 (SQL: insert into `ledgers` (`user_id`, `user_type`, `context`, `event`, `recordable_id`, `recordable_type`, `properties`, `modified`, `extra`, `url`, `ip_address`, `user_agent`, `created_at`, `updated_at`,
`pivot`, `signature`) 

values 

(4, App\Models\Auth\User, 4, updated, 4, App\Models\Auth\User, {"id":4,"uuid":"83e5a26f-813c-4933-95df-112e7bd95f48","first_name"
:"Marianne","last_name":"smith","email":"[email protected]","avatar_type":"storage","avatar_location":"avatars\/... and so on.

As far as I see, the SQL query is not sending the id Field that the database expects.

The Laravel boilerplate uses ledger package in order to track all users related events (logged in, logged out, confirmed and so on).

That's why I get the error every time users upload an image, or log in or log out.

I think at the moment the only solution is get rid of the package

Activity icon

Replied to 500 Error: Cannot Serve Directory - No Matching DirectoryIndex Found

@sinnbeck I have used the Laravel boilerplate. But it is giving me more troubles than I expected. The documentation does not mention any solution about this

Activity icon

Started a new Conversation 500 Error: Cannot Serve Directory - No Matching DirectoryIndex Found

I have deploy an app fully working in Localhost but in the production server, every time I log in I get a 500 error.

After I refresh the page, the user is logged in.

I could visit all pages, but I can not upload images (change from avatar to the uploaded image). I get the 500 error again.

Looking at the logs I get this:

[Fri Feb 21 11:00:10.620900 2020] [autoindex:error] [pid 1579]
[client 46.189.69.156:51442] AH01276: Cannot serve directory /home/363286.cloudwaysapps.com/bkbqeheexz/public_html/public/storage/: No matching DirectoryIndex (index.php,default.php,index.html,default.html) found, and server-generated directory index forbidden by Options directive, referer: http://phplaravel-363286-1171349.cloudwaysapps.com/admin/dashboard 

I followed all needed steps in the deployment: https://support.cloudways.com/deploy-laravel-on-cloudways/?utm_source=Platformkb&utm_medium=kbsearch


I also did this:

  • I generated the necessary key: php artisan key:generate
  • php artisan clear-compiled
  • php artisan cache:clear
  • php artisan route:clear
  • php artisan view:clear
  • php artisan config:clear
  • composer dumpautoload -o
  • php artisan storage:link

But now I am still having the 500 Error every time I visit a page with images (user images)

It seems to be a problem with the storage linking, but I have not idea, what to do.

Any help would be appreciated

Feb
20
1 month ago
Activity icon

Replied to Laravel-boilerplate - RuntimeException: A Facade Root Has Not Been Set.

@sinnbeck That was the issue. I forgot to run the composer install, and the key generator in the server as well. Now it works as expected. Thanks a lot

Activity icon

Replied to Laravel-boilerplate - RuntimeException: A Facade Root Has Not Been Set.

@sinnbeck yes, there is not vendor folder in server I will run the composer install

Activity icon

Replied to Laravel-boilerplate - RuntimeException: A Facade Root Has Not Been Set.

Composer install in the servet you mean?

Activity icon

Replied to Laravel-boilerplate - RuntimeException: A Facade Root Has Not Been Set.

@sinnbeck yes, I use version control. I pull directly from git

Activity icon

Replied to Laravel-boilerplate - RuntimeException: A Facade Root Has Not Been Set.

@sinnbeck but I just deployed another app without boilerplate in the same server last month and works out ofthe box. That is the beauty if one button deployment in cloudways

Activity icon

Replied to Laravel-boilerplate - RuntimeException: A Facade Root Has Not Been Set.

@sinnbeck yes, I have developed the whole app. And works locally The problem appears once I deployed it. I got a blank page online

Activity icon

Started a new Conversation Laravel-boilerplate - RuntimeException: A Facade Root Has Not Been Set.

I have used the boilerplate ion my app and everything was fine until I tried to deploy it using Cloudways

I get a blank page and the logs show the following error:

[Thu Feb 20 07:42:43.864771 2020] [proxy_fcgi:error] [pid 11114] [client 46.189.69.156:32802] AH01071: Got error 'PHP message: PHP Fatal error: Uncaught RuntimeException: A facade root has not been set. in /home/363286.cloudwaysapps.com/dujbzkuhwg/public_html/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:236\nStack trace:\n#0 

/home/363286.cloudwaysapps.com/dujbzkuhwg/public_html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(407): Illuminate\Support\Facades\Facade::__callStatic('replaceNamespac...', Array)\n#1 

/home/363286.cloudwaysapps.com/dujbzkuhwg/public_html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(384): Illuminate\Foundation\Exceptions\Handler->registerErrorViewPaths()\n#2 

/home/363286.cloudwaysapps.com/dujbzkuhwg/public_html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php(295): Illuminate\Foundation\Exceptions\Handler->renderHttpException(Object(Symfony\Component\HttpKernel\Exception\HttpException))\n#3 

/home/363286.cloudwaysapps.com/dujbzkuhwg/public_html/vendor/laravel/framework/src/Illuminate/Foundation/Ex...\n' 

I have been searching the Internet and trying in my application without success.

I have deployed a fresh Laravel install with the boilerplate with the same results which makes me believe it is not an issue related to my code.

Any idea how to proceed?

Feb
16
1 month ago
Activity icon

Replied to Mapping An Array And A Collection Together

@bobbybouwmann I agree, I don't think it is easier to read or shorter.

Activity icon

Started a new Conversation Mapping An Array And A Collection Together

I have following Collection that holds the employees data of a Company

Collection {#610 
  #items: array:2 [
    10 => Employee {#639 
      #attributes: array:4 [
        "id" => 4     
        "first_name" => "Marianne"
      ]
    }    
    11 => Employee {#639 
      #attributes: array:4 [
        "id" => 7     
        "first_name" => "Andrea"
      ]
    }
  ]
}

And this array that holds the interviews finished for each employee in one day:

array:8 [
  "Marianne" => 5
  "Stefanie" => 9
  "Angela" => 9
  "Andrea" => 17
  "Michelle" => 9
  "Ivonne" => 9
  "Martina" => 9
  "Karolina" => 9
]

I want to add the results of the day to each employee in the collection like this.

Collection {#610 
  #items: array:1 [
    10 => Employee {#639 
      #attributes: array:4 [
        "id" => 4     
        "first_name" => "Marianne"
         "count" => 5   // <--- Count of the day
      ]
    }    
    11 => Employee {#639 
      #attributes: array:4 [
        "id" => 7     
        "first_name" => "Andrea"
        "count" => 17   // <--- Count of the day
      ]
    }
  ]
}

One note is that the collection and the array not necessarily have the same length. No employees works everyday, sick leave, holidays, etc.

Until now I am doing a nested loop like this:

        foreach($all_employees as $ki => $employee) {
            $employee->appointmentsCount = 0;
        }
        foreach($counting as $key => $count) {
            foreach($all_employees as $ki => $employee) {
                if($key === $employee->first_name) {
                     $employee->count = $count; 
                }
            }
    }

Since I am using this method all over the place, I wonder if there is a more Laravel shorter way using Collection mapping so, at least the syntax is shorter.

Feb
11
1 month ago
Activity icon

Replied to Constant Vs Model

@cjj I will have a look if the Post has something like an API

Feb
10
1 month ago
Activity icon

Started a new Conversation Constant Vs Model

In my app I want to help the users to build their address. Just by giving their Zip code I will populate the Locality name and the state. I am living in Germany and it means 16 states (Bundesland) but also 13000 zip codes (theoretically could get until 100k).

At the moment I keep all those data in two tables in the database. It means over 13k foreign keys and join table to determine which zip code belongs to which state.

It works, however since that data never change and is not the center of my business, I wonder if there is any other more efficient method that speed up the app.

I would go for a Constant but it means giant arrays, foreachs or array_maps.

My question is what is faster, a query or a search inside an arraybof constants? Is there any other option?

Feb
07
1 month ago
Activity icon

Replied to Calling A Route And Show The Response In A Modal.

@robstar Good to know it is possible. I am using Bootstrap 4. I will search for it

Activity icon

Started a new Conversation Calling A Route And Show The Response In A Modal.

I am building an application that makes heavy use of modals. Essentially a grid (employee/timeSlots) in which each cell fires a modal. Each modal shows tons of information that at the moment I am uploading upfront. It slows down the app.

My question is: Is it possible to retrieve information concerning each modal from the database in the moment that it is fired (if possible without JavaScrip, Ajax)?

I have tried like this, but it does not work:

<a  data-toggle="modal" 
            data-target="#modal_showAppointment"
            data-appointment="{{ {{route('appointments.show', $appointment->id }}">
            Show
</a>

Essentially what I am trying to make is to call a route and show the response in a modal. Is that possible?

Jan
27
2 months ago
Activity icon

Replied to When Routes Collide

@jove @snapey I got it! I rearrange the order and it works. Thanks

Activity icon

Replied to When Routes Collide

@jove I am not sure I understand what you mean with "Place it at the end".

Yes, all my routes are dynamic. I just add a new page in the data base and it will get rendered in front end. For example, if I add now a faq page, I will have a https://myapp.com/faq page in frontend

Activity icon

Replied to When Routes Collide

@snapey I edited the question.

I have these two options: I make the pages in the HomeController in order to have a clean URL

Route::get('/', '[email protected]')->name('main.index');
Route::get('/{page}', '[email protected]')->name('main.show');

It gives a nice and clean url: http://myapp.com/contact-us but it collides with the ListingsController because http://myapp.com/listing/ will be understood as a page and gives a 404 back.

Or I move the pages to a second Controller:

Route::resource('pages/{page}', 'PagesController');

But I will have an URL like this: http://myapp.com/pages/contact-us which is not nice

Activity icon

Started a new Conversation When Routes Collide

My app had the following routes

Route::resource('/', 'HomeController');

Route::resource('listings', 'ListingsController');

Now I need to add some pages like Imprints, Contact, About US. So, I created a Pages Controller

Route::get('/page', '[email protected]')->name('main.show');

In order to have:

Problem is that after introducing this, the http://myapp.com/listings became a 404 error because this is a "page" that does not exist.

Provided that I will have a blog in the future, I could change the pages to a new PagesController :

Route::resource('pages/{page}', 'PagesController');

But I will have :

But being honest, I do not think it is very elegant and I would like to have a clean structure like this:

Is there any way I could make that Route::resource('listings', 'ListingsController'); and Route::resource('/', 'HomeController'); coexist with each other?

Rerouting or something like that?

Jan
21
2 months ago
Activity icon

Replied to Different Variables Behaviour In Localhost Vs Deployed

@snapey Added in each @include is definitively not good.

But anyway, I have a long way in front of me making refactors and so on.

That my (first) app is working online as expected is already a big step for me. Thanks for your help

Activity icon

Replied to Different Variables Behaviour In Localhost Vs Deployed

@snapey Thanks for your explanation. Based on it, I just eliminated the code from the controller and buidl the same logic in a ViewComposer in the AppServiceProvider like this:

 public function boot()
    {


        View::composer('*', function ($view) {
            if (Auth::user()) {
                $user = Auth::user();
                $employee = $user->employee;
                $role = $user->role->slug;
                $company = $user->company;
                $view->with('signed_in', Auth::check());
                $view->with('user',  $user);
                $view->with('employee',  $employee);
                $view->with('role',  $role);
                $view->with('company',  $company);
            }
        });
    }

And now it works everything as expected

Jan
20
2 months ago
Activity icon

Replied to Different Variables Behaviour In Localhost Vs Deployed

@snapey once I try to log in I get the following error:

Undefined variable: user (View: /home/363286.cloudwaysapps.com/ccsnbfpybb/public_html/resources/views/partials/menues/employee.blade.php) ...

As I understand, I am not able to log in

To your last comment: I am adding that code just once in the Controller.php.

Activity icon

Replied to Different Variables Behaviour In Localhost Vs Deployed

@snapey Yes, Cookies are set in my Browser. I see the laravel session cookie:

laravel_session : "eyJpdiI6IjNSZGpub0lXYlo3RW03RHhE..... "

Yes, I am running apache in Cloudways (I think)

Activity icon

Replied to Different Variables Behaviour In Localhost Vs Deployed

@masumluf sorry i do not understand what you mean.

This exact code works in Localhost but not deployed. How do I make available a variable globally in my appliation? (Controller and views)

Activity icon

Started a new Conversation Different Variables Behaviour In Localhost Vs Deployed

In my application I need to make globally available four variables: $user, $employee, $role and $company

In order to show different menu options and landing views after login.

I do this in my Controller.php

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            if (Auth::user()) {
                $user = Auth::user();
                $employee = $user->employee;
                $role = $user->role->slug;
                $company = $user->company;
                view()->share('signed_in', Auth::check());
                view()->share('user',  $user);
                view()->share('employee',  $employee);
                view()->share('role',  $role);
                view()->share('company',  $company);
            }
            return $next($request);
        });
    }
}

This work as expected in my development local enviroment (Localhost).

Now I deployed my app (first time I deploy a Laravel app) in CloudWays and it does ont work as expected.

It turns out that Auth::user() is empty (not defined and therefore it breaks the app.

I double checked the login info (email and password) and they are right.

It is the same code, that I pushed to git and deployed from there.

Any idea, why Auth::user() is never defined? What Am I missing?

Jan
16
2 months ago
Activity icon

Started a new Conversation Refactoring For Speed. Foreach Vs Maps

I am almost ready building a Web app for a small company that keeps track of appointments from each employee in hourly and daily basis. It means 1 employee x 8hour = 10 slots/day. Each slot has a bunch of data associated. (productivity, prices, clients and so on).

I have to recurrently map collections to each other. Collections like: companyOpeningtime, employeeWorkingTime, publicHolidays, workablesDays, employees, clientsHistory, ClientsPaymentMethods. I hope names are self-explanatory.

In few words: Each new employee added makes it about 300 miliseconds slower. So I have to refactor.

Following advice this link: https://stackoverflow.com/questions/18144782/performance-of-foreach-array-map-with-lambda-and-array-map-with-static-function I map two Collections with nested loops like this:

foreach( Collection1 as key1 => $element) {
    foreach(Collection2 as key => $item {
        If (any condition) {
            Do something;
        }
    }
}

However, since the post has a couple of years I wonder if still two nested loops are faster than using PHP Maps functions.

Is there any “magic method” in Laravel that permit map two collections in a faster way or we have to rely on pure PHP methods and speed?

Jan
06
2 months ago
Activity icon

Replied to Allow To Load Relations In An Infinite Circle: $appointment->client->appointments

Client.php

    public function appointments()
    {
        return $this->hasMany('App\Appointment')->orderBy('startDateTime', 'DESC');
    }

Appointment.php

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

AppointmentsController

public function index(Company $company)
    {
    …
        $appointments = Appointment::where('company_id', $company->id)->get();
        …

        return view('appointments.index', compact('appointments'));
    }

Index.view

foreach( $appointments as $appointment)
{
    {{ $appointment->client->fullname }}
    {{ $appointment->date }} 
            {{ $appointment->time }}
            {{ $appointment->notes }}

    <h3>Previous appointments</h3>
        foreach($appointment->client->appointments as $clientAppointments)
        {
                {{ $clientAppointment->date }} 
                {{ $clientAppointment->time }}
                {{ $clientAppointment->notes }}
        }
}

I get the error: Trying to get attribute of non object in the second foreach. clients->appointments does not work as a second level

Activity icon

Replied to Allow To Load Relations In An Infinite Circle: $appointment->client->appointments

@tisuchi that's the way it is if you make two different calls.

$appointments->clientwill give you a collection like this:

  • Appointment1
    • Client1
  • Appointment 4
    • Client2

$client->appointments;will give back following collection structure:

  • Client1
    • Appointment2
    • Appointment3
  • Client2
    • Appointment4
    • Appointment4

But what I need here is to get a Collection with one level deeper

  • Appointment1
    • Client1
      • Appointment2
      • Appointment3
  • Appointment 4
    • Client2
      • Appointment 4
      • Appointment5

Something like: $appointment->client->appointments but this results in a kind of circle and the second level is never load

Activity icon

Started a new Conversation Allow To Load Relations In An Infinite Circle: $appointment->client->appointments

I have the following model structure:

  • Appointment hasOne Client
  • Client hasMany Appointments

Now I have a calendar with all appointments foreach($appointments as $appointment)

  • Appointment10 (client 1)
  • Appointment11 (client 2)
  • Appointment 09 (client1)
  • etc

When I click on one of the coming appointments I open a modal (no a new view). That makes me to load all the data of each appointment in advance which I recognize is a huge performance stress, but it is a better UX.

The point here is that now in the Appointment details modal, I want to show all the appointments that the client has in the pass. His history: like this:

- Appointment 10 (February2020)
    - Client 1
        - Appointment 3 (December 2019)
        - Appointment 4 (November 2019)
        - Appointment 5 (October 2019)


In the modal I do this:

    {{ $appointment->client->full name }}

    foreach($appointment->client->appointments as $clientAppointments)
    {
        {{ $clientAppointment->date }} // December 2019
        {{ $clientAppointment->time }}
        {{ $clientAppointment->notes }}
    }

And I get an error:

Trying to get attribute of non object

It seems like Laravel does not allows to load an almost “infinite circle” here:


$appointment->client->appointments

Is there any way to tell Laravel, that I need at least this one more level down of relations?

Jan
03
2 months ago
Activity icon

Replied to Pass A Javascript Variable To PHP Using A HTML Form

After a lot of tests I have got the solution. I post here the answer in case it is useful to anyone in the future (including myself)

I already had the value of each field in each iteration in the Javascript variable: $target.data(attributeName)

So I added a counter to the loop and saved each value:

$('[data-toggle="modal"]').on('click', function (e) {
    var $target = $(e.target);
    var modalSelector = $target.data('target');

    let count = 0;  // <- The counter

    ATTRIBUTES.forEach(function (attributeName) {
    var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
    var dataValue = $target.data(attributeName);
    $modalAttribute.text(dataValue || '');
    document.getElementById('attribute_' + count).value = $target.data(attributeName); // <- save the value in a variable
    count++
    });
});

After that, I just set an id to each input field equal to the name of the variable:

<form...
<input name="appointment_time" type="hidden" id="attribute_0" value="">
<input name="employee_name" type="hidden" id="attribute_1" value="">
// and as much variables as I have in the loop
...</form

The hidden fields are passed through with the form once I hit the submit button

Activity icon

Started a new Conversation Pass A Javascript Variable To PHP Using A HTML Form

I have the following code that builds a several tables besides each other with the name of each employee on top

@foreach($all_calendars as $name => $employee)
    @foreach($employee->appointments as $key => $appointment)
        <tr>
            <td>
                <h4 class="free-appointment text-center">
                    <a data-toggle="modal" data-target="#modal_addAppointment" data-time="{{ $key }}"
                        data-employee="{{ $name }}" class="btn btn-link" role="button" aria-pressed="true"><i
                            class="fas fa-plus"></i>
                    </a>
                </h4>
                <div id="modal_addAppointment" tabindex="-1" role="dialog"
                    aria-labelledby="exampleModalLabel" aria-hidden="true">
                    @include('salon.includes.modal_create_appointment')
                </div>
            </td>
        </tr>
    @endforeach
@endforeach

data-time and data-employee pass two variables to the modal: $name (of the employee) and $key (time of the appointment).

In order to show then in the modal I used Javascript like this. Otherwise it will only pass the name of the last employee and last time:

<script>
    // data-* attributes to scan when populating modal values
var ATTRIBUTES = ['time', 'employee'];

$('[data-toggle="modal"]').on('click', function (e) {
// convert target (e.g. the button) to jquery object
var $target = $(e.target);
// modal targeted by the button
var modalSelector = $target.data('target');

// iterate over each possible data-* attribute
ATTRIBUTES.forEach(function (attributeName) {
// retrieve the dom element corresponding to current attribute
var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
var dataValue = $target.data(attributeName);

// if the attribute value is empty, $target.data() will return undefined.
// In JS boolean expressions return operands and are not coerced into
// booleans. That way is dataValue is undefined, the left part of the following
// Boolean expression evaluate to false and the empty string will be returned
$modalAttribute.text(dataValue || '');

});
});

</script>

And it allows to show the results in HTML like this:

<h2>Appointment on <span id="modal-time"> </span> with <span id="modal-employee"></span></h2>

where <span id="modal-employee"></span> contains the name of the employee. Time works in a similar way.

Now, my problem is that I have a form in the modal that submits, among others, that name and that time variablesas hidden fileds. But I have the following problem:

<form method="POST" action="{{route('appointments.store', $company)}}" accept-charset="UTF-8">
@include('partials.errors')
<input name="employee_name" type="hidden" value="<span id="modal-employee"></span>"> // <-- this does not work
...

This does not work:

<input name="employee_name" type="hidden" value="<span id='modal-employee'></span>">

So I need to store the content of <span id="modal-employee"></span> in a variable

The question is: how do I store the value of that variables on the fly directly in the HTML modal?

Dec
14
3 months 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
3 months 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
3 months 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
4 months 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
4 months 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
4 months 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