RafaelMunoznl

RafaelMunoznl

Software developer at AllMyHomes GmbH, Berlin

Member Since 2 Years Ago

Berlin

Experience Points
37,830
Total
Experience

2,170 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
328
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 8
37,830 XP
Jun
18
2 weeks ago
Activity icon

Replied to How To Echo Attributes Of A StdClass In Frontend

@michaloravec Thanks!

I did not see something so obvious!

Activity icon

Started a new Conversation How To Echo Attributes Of A StdClass In Frontend

After a long process I have got an array (stdClass) with following complex struture that should feed a table in a view.

$data = [
  "2020-07-01" => array:12 [
    "Marianne" => array:2 [
      0 => array:18 [
        "date_id" => 183
        "shift_id" => 99
        "employee_id" => 4
        "date" => "2020-07-01"
        "appointmentId" => 1058
      ]
      1 => array:18 []
    ]
    "Stefanie" => array:4 []
    "Angela" => "holidays"
    "Karolina" => array:1 []
    "Andrea" => array:6 []
    "Michelle" => ""

  ]
  "2020-07-02" => array:12 [
    "Marianne" => ""
    "Stefanie" => array:3 []
    "Angela" => "holidays"
    "Karolina" => array:1 []
    "Andrea" => ""
    "Michelle" => array:1 []
  ]
  "2020-07-03" => => array:12 [
    "PublicHolidays" => "Pfingsmontag"
  "2020-07-04" => array:12 []
  "2020-07-05" => "closed"
  "2020-07-06" => array:12 []
  ...

This is not ann array but an stdClass.

If I do this in my view:

@foreach($availability as $day => $row){
	@foreach($row as $employees => $appointments)
		@foreach($appointments as $appointment)

			{{ dd($appointment['date']) }} // <- Is a dd();

		@endforeach
	@endforeach
@endforeach

I get this:

"2020-07-01"

However, when I do this:

@foreach($availability as $day => $row){
	@foreach($row as $employees => $appointments)
		@foreach($appointments as $appointment)

			{{ $appointment['date'] }} // <- I echo it

		@endforeach
	@endforeach
@endforeach

I get following error: Undefined index: startDate (View: ...

If I change to object notation like this:

{{ $appointment->date }}

I get following error: Trying to get property 'startDate' of non-object (View...

Trying to json_code and json_decode like this:

json_decode(json_encode($data), true) gives me same result.

Changing everyhing to objects from eloquent is the last option (months of work).

Anyway the dd() shows me that the data is there, but I am failing to show it

Any idea what is happening here?

Jun
14
3 weeks ago
Activity icon

Started a new Conversation Extracting A List Of Keys In An Array In LIST Format, Not In Array Format.

I am working with Laravel Eloquent, so I want to make a query that return the ids that are in a list of ids. A typical query like this

->whereIn('id', $ids)

as starting point, I have the following array:

$days = [
  265 => "1"
  266 => "2"
  267 => "3"
  268 => "4"
  269 => "5"
  270 => "6"
  272 => "1"
]

So, I need to extract the keys and return then in the following format:

$ids = (265, 266, 267, 268, 269, 270, 272)

But the array_key function array_keys($days), it returns me another array. Instead a list. Like this one:

array:7 [▼
  0 => 265
  1 => 266
  2 => 267
  3 => 268
  4 => 269
  5 => 270
  6 => 272
]

Which is not what I need. How could I get a list of array_keys (in a list format, not in array format)?

Jun
07
4 weeks ago
Activity icon

Replied to Erratic Behaviour Pasing Variables From PHP To A Modal Bootstrap4

@snapey I just let one appointment in order to debug faster. All the expected attributes are there. But in the modal just arraive the name and the time, all the others don't

Activity icon

Started a new Conversation Erratic Behaviour Pasing Variables From PHP To A Modal Bootstrap4

I have this HTML that should open a modal with information changing dynamically.

I am trying to 5 variables:

  • data-employee,
  • data-time
  • data-start
  • data-shift
  • data-image

All five variables are string type.

My HTML call the modal like this:

@foreach($appointments as $appointment)

	<a  class="text-success"
		data-toggle="modal"
		data-target="#modal_createAppointment"
		data-employee="{{ $employee }}"
		data-time="{{ Carbon\Carbon::parse($appointment['startDate'])->isoFormat('dddd, DD MMMM') }}"
		data-start="{{ $starting_at }}"
		data-shift="{{ $workshift }}"
    data-image = "{{ $image }}"
		aria-pressed="true">
		{{ $appointment['starting_at'] }} <i class="fas fa-chevron-right ml-2"></i>
	</a>

@endforeach

And the modal opens:

<div id="modal_createAppointment" tabindex="-1" role="dialog" aria-labelledby="modal_createAppointment">

<div id="modal-appointments" class="modal-dialog modal-full-height modal-right modal-notify modal-info" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title">
                <span id="modal-employee"></span>
                <span id="modal-start"></span>
                <span id="modal-shift"></span>            
                <span id="modal-time"></span>
            </h4>
        </div>

        <div class="modal-body">
            <div class="modal-info">
                <form method="POST" action="{{route('frontend.company.appointment.store', $company )}}" accept-charset="UTF-8">
                    <input name="startTime" type="hidden" id="attribute_0">
                    <input name="employee_name" type="hidden" id="attribute_1">
                    <input name="image" type="hidden" id="attribute_2">
                    {{ csrf_field() }}

                         // ... More code hier
                 </form>
            </div>
        </div>
    </div>
</div>

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

$('[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');

    let count = 0;
    
    // 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 || '');
    document.getElementById('attribute_' + count).value = $target.data(attributeName);
    count++
    });

});

</script>

</div>

All four variables are present (I see all correct in the Chrome Developer tools), but just passed the data-time and data-employee. The other three are not shown.

I have changed the order with the same result.

I have not idea why is passing just 2 variables instead of five?

Obviously I am missing somthing simple, but not idea what

  • In the other hand, I would prefer to pass the object or perhaps as Array. Something like this: HTML
data-appointment = ['time' => $time, 'employee' => $employee, 'image' => $img, 'start' => '08:00', 'shift' => 'late  shift']

Unfortunatelly my knowledge about javaScript is very limited

Jun
05
1 month ago
Activity icon

Replied to Eloquent: Get A List Of DateTimes Where Model "HasNot" Or "empty

@guybrush_threepwood

Yes, I will group per day, but the result is what I wanted to have.

This was a problem I have all the time in my app (employees without avatar, clients without emails and so on that forced me to make endless loopings to assign the missing part to the collections.

Thanks a lot!!

Jun
04
1 month ago
Activity icon

Replied to Eloquent: Get A List Of DateTimes Where Model "HasNot" Or "empty

@guybrush_threepwood

I abandoned the idea of doing a temporary table. Dates are the same always, so I just populated it with a seed, like I also did with postalcodes. I run it just once and is all simpler.

But all this started because I wanted to get a list of all days with all employees regardless they have appointments or not in each day. So I could see the "empty" time for new bookings.

Now I have three tables: employees, appointments and dates that I could join like this: dates.id = appointments.dates_id and employees.id = appointments.employee_id

Now I believe I will need a FULL OUTER JOIN in order to get all the employees and all the dates regadless if the employees have appointment on a day or not.

And as far as I know there is not support in eloquent for FULL OUTER JOIN

Jun
03
1 month ago
Activity icon

Replied to Eloquent: Get A List Of DateTimes Where Model "HasNot" Or "empty

@guybrush_threepwood

I am trying to use your code but create a temporary table since I just need a three month time gap.

I am able to create the table on the fly with these hard code dates:

DB::unprepared(' CALL fill_dates("2020-06-01", "2020-09-30" )' );

But I would like to make it dynamic, so i do not have to care about updating the code. So i did this:

public static function createTemporaryTable($request)
    {

        $start = $request->month;
        $end = Carbon::parse($request->month)->addMonths(3);
      
        DB::unprepared( DB::raw("DROP TABLE IF EXISTS dates;") );

        Schema::create('dates', function (Blueprint $table) {
            $table->increments('id');
            $table->date('date')->index();
        });

        DB::unprepared('DROP PROCEDURE IF EXISTS fill_dates');

        DB::unprepared('
            CREATE PROCEDURE fill_dates(start_date DATE, end_date DATE)
            BEGIN
                DECLARE crt_date DATE;
                SET crt_date = start_date;
                WHILE crt_date <= end_date DO 
                    INSERT INTO dates(date) VALUES(crt_date);
                    SET crt_date=ADDDATE(crt_date, INTERVAL 1 DAY); 
                END WHILE; 
                END
            ');

        DB::unprepared(' CALL fill_dates("2020", ":end" )', 
            [ 'start' => $start, 'end' => $end,]
        );

        return; 
    }

But the dates do not pass into the Query. So I get table with just one row id = 1, date = 0000-00-00

I have tried also to pass the dates this way array('start' => $start, 'end' => $end also without sucess.

This is just a simple MySQL statement, but I do not get it!

Obviously I am missing domething here. But what?

Activity icon

Replied to Eloquent: Get A List Of DateTimes Where Model "HasNot" Or "empty

@guybrush_threepwood

Oh! I has been trying since about a week to get it done !

But in the other hand, creating a permanent table with dates (in a year in advance, for example); might be not such a bad idea. The main focus of my app is managing appointments for each of the employees each time a customers calls.

So, thanks

Jun
02
1 month ago
Activity icon

Started a new Conversation Eloquent: Get A List Of DateTimes Where Model "HasNot" Or "empty

In order to add new appointments to an employee, I am building a search to get the empty slots in his appointment calendar, in a given month.

Let's say Employee-A has just his first appointments booked on 2020-06-10 10:00 datetime). Of course, he will work the whole month.

Notice that my model is "Appointment" and I am looking for spaces between appointments

  • First step: get the already booked appointments:
Appointment::join('employees', 'employees.id', 'appointments.employee_id')
	->when(
		$month, function ($query, $month) {
		$query->where('appointments.startDateTime', 'like', $month . '%');
	})
	->where('appointments.startDateTime', '>', now() )
	->select(appointment.id, appointment.startDateTime, appointment.endDateTime
	->get()
	->toArray();

This query gives me just that one result. Getting the non-booked time that day is easy.

  • Second step

I need to get the empty time on days in which Employee-A has still non one single appointment booked. In this case, from June 1 to June 9 and from June 11 to the end of the month.

My question is:

How do I get the list of empty days where "DATETIME is not" ? Something like:

Appointment::join('employees', 'employees.id', 'appointments.employee_id')
	->when(
		$month, function ($query, $month) {
		$query->where('appointments.startDateTime', 'like', $month . '%');
	})
	->where('appointments.startDateTime', '>', now() )
	->whereHasNot('appointments.id')
	->groupBy( DAYS )
	->select( LIST OF DAYS)
	->get()
	->toArray();
May
29
1 month ago
Activity icon

Replied to Pass A Collection Of Objects Between Controllers Through The Session

@michaloravec It is certainly an easier solution, but it would mean I have always that list on top.

The idea was just to show the user the new items that he has just created.

P.S. But I think that I could select the itens ```where('created_at', $today). I'll think about it.

Activity icon

Started a new Conversation Pass A Collection Of Objects Between Controllers Through The Session

May problem is as follows:

  • I have a list of items in a view index.blade.php.

  • I am saving a new Item in the database and redirecting back to the same view.

  • This process could be repeated as much as the user needs. Save, back, save again, back and so on.

  • Now, back to the index view, I want to show the items on the top, apart from the rest.

This process could be repeated so at the top I am getting a new list with the Items created in the session.

That said, it seems I need to create an array of Items in which the second part of the pair is an object ['key', $object]

I did this:

The store method:


public function store(ItemRequest $request)
{
	// other code here
	$newItem = $this->ItemRepository->createItem($request);

	$request->session()->put(['newItem', $newItem]);

	return redirect()->back();
}

In the index method:

   public function index()
    {
	// other code...
		
        $items = $request->session()->pull('items');

        return view('frontend.search.results', compact('items', // other variables here));

    }

In the view results.blade.php

@foreach($items as $key => $item)
	<h4>{{$item->name}}</h4>
	
	<p>{{ $item->price }} </p>
	<p>{{ $item->quantity }} </p>
	<p>{{ $item->unit }} </p>
@endforeach

Unfortunatelly, it does not work. It is the first time I use the session for such a thing. I am not eve sure is the session could be used for that. Reading the documentation did not help me really

Could anybody explain me what am I doing wrong? How do I pass that variables (collection) back to the previous view?

May
24
1 month ago
Activity icon

Replied to Trying To Get Time Difference (gap) Between EndTime And StartTime Following Record

@kalemdzievski The query passed wih the first version

->join('appointments as appointments_b', 'appointments.id', DB::raw('appointments_b.id + 1'))

so i get a result!

The result is not right. It gives a wrong amout of minutes, but I think it should be another issue, I will have to investigate.

But the problem of the query is solved. Thanks.

Activity icon

Replied to Trying To Get Time Difference (gap) Between EndTime And StartTime Following Record

@kalemdzievski It still having a "translations problem",

This lines:

->join('appointments as appointments_b', function($join){
    $join->on(DB:raw('appointments.id = appointments_b.id + 1'))
})

are getting this resulting query:

INNER JOIN `appointments` AS `appointments_b` ON appointments.id = appointments_b.id + 1 = ''
Activity icon

Replied to Trying To Get Time Difference (gap) Between EndTime And StartTime Following Record

@kalemdzievski Thanks for the answer.

I have tried your proposal, but still getting the error:

Column not found: 1054 Unknown column 'appointments_b.id + 1' in 'on clause' (SQL: select `employees`.`id` as `employee_id`,  ... 

it does not find the column by adding one to the id 'appointments_b.id + 1' or better said, the next record. If I remove the + 1 I will get the calculation inside the appointment (its duration = endTime - starttime)

I am using MySql

May
23
1 month ago
Activity icon

Started a new Conversation Trying To Get Time Difference (gap) Between EndTime And StartTime Following Record

I have a table appointments which following columns

  • id
  • startTime
  • endTime
  • employee_id
  • client_id

In order to manage the free time of an employee, I need to get the time between one appointment and the next one. In plain words:

  • I need to join the appointment with itself: join('appointments', 'appointments.id as A', 'appointments.id + 1 as B')
  • I need to select the appointments, orderBy startTime, asc
  • Substract appointmentsB.startTime - appointmentsA.endTime of previous appointment to get the gap.

I did this:

$query = Appointment::where('employee_id', $employeeId);
   ->join('employees', 'employees.id', 'appointments.employee_id')
   ->join('appointments', 'appointments.id as A', 'appointments.id + 1 as B')
   ->where('startTime', '>', now())
   ->orderBy('appointments.startTime')
   ->select(
      'employees.id as employee_id',
      'appointments.id as appointmentId', 'appointments.startTime', 'appointments.endTime',
   )
   ->selectRaw(
      'TIMESTAMPDIFF(minute, B.startTime, A.endTime) as gap')
   ->get()
   ->groupBy('employee');

However, trying to join the table with itself give me the following error:

```SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'appointments' ```

I have tried all possible combinations to join the table with its succesor appointment.id+1

What am i doing wrong here?

May
19
1 month ago
Activity icon

Replied to Speed Up The User Experience Just With Laravel (PHP)

@wingly I did not know algolia, it looks cool. I will have a closer looks into it

Activity icon

Replied to Speed Up The User Experience Just With Laravel (PHP)

@tray2 A city in Germany could have hundreds of postalcodes. Just berlin has 190 postalcodes.

In order to do a reversed search (city->postalcode), I will have to make a two step process, i need first to know which city the user lives in in order to present a list of postalcodes to choose from.

Activity icon

Replied to Speed Up The User Experience Just With Laravel (PHP)

@rumm.an -Yes,roblem 2 is solved by using select2. -problem 1, Your assumptions are correct. I have used your query instead and I see an slightly imrpovement 900ms before and 800ms now. But anyway I have not other option I have to queryover 13k records!

It seems that a subquery is faster than a join. I need to have a alook into it since I always use JOIN

Yes, I have index in bundesland_id.

Thanks for your help

May
17
1 month ago
Activity icon

Replied to Eloquent WHEN: Add Attributes To The Query Results Depending On Column Value

@michaloravec. I trying to use as much as possible thepossibilities of MySql to avoid endless looping afterwards.

Thanks a lot

Activity icon

Replied to Eloquent WHEN: Add Attributes To The Query Results Depending On Column Value

@snapey the data directly in the database could lead to different written items or misspellings like 'Professor' , 'Prof.', 'Prof' (without end dot) for the same concept.

As I need to translate the result, the string muss be the same one always.

Until now I have just create a model a controllers and a relatuon, allowing CRUD, but in this case that would be to much

Activity icon

Started a new Conversation Eloquent WHEN: Add Attributes To The Query Results Depending On Column Value

I have a following query to select a client with its title ('Dr.' , 'Prof.', etc).

I have a title_idcolumn and all the possible titles in an array under config/titles.php

Titles.php

<?php

return [
    'titles' => [
        '1' => 'Dr.',
        '2' => 'Prof.',
    ]
];

In my query I want to achieve that IF title_id = 1 then add an attribute as title = 'Dr.' If it is 2 then 'Prof.' and so on. I want to do it in the query instead looping outside the results.

Client::select('clients.id as client_id', 'clients.firstname', 'clients.lastname')
		->when('clients.title_id' == 1, function ($query) {
			return $query->select('clients.title_id as title = `Dr.`'); })
		->when('clients.title_id' == 2, function ($query) {
			return $query->select('clients.title_id as title = `Prof.`'); })
		->first();

However, it ignores the title_id. It does not give back error. It just ignores the title_id

What am I doing wrong?

May
13
1 month ago
Activity icon

Replied to Speed Up The User Experience Just With Laravel (PHP)

@wingly That's the point, I have tried like this:

Postalcode::chunk(100, function ($postalcodes){
   foreach ($postalcodes as $postalcode) {                  
      $postalcode->join('bundeslands', 'postalcodes.bundesland_id', 'bundeslands.id')
         ->orderBy('postalcode')
         ->select(
            'postalcodes.id', 
            'postalcodes.postalcode', 
            'postalcodes.locality', 
            'bundeslands.title as bundesland')
        ->get();
      }});

But I get and error. I also made lots of combinations, with the join outside the foreach, but I do not get it to work

Activity icon

Replied to Speed Up The User Experience Just With Laravel (PHP)

@wingly I understand how bad is the user expeirnce in this case. But I think we are talking about two different problems here:

  • Firs one: It takes several seconds to query and load the view with the 13k+ postalcodes.

This is a backend problem to solve.

I have tested with and without chunk() and the time to load the final view is the same.

Debugbar shows "Request duration" around 9630ms in both cases, 3 to 4 seconds to complete rendering the view

I did this the chunk like this:

Postalcode::join('bundeslands', 'postalcodes.bundesland_id', 'bundeslands.id')
			->orderBy('postalcode')
			->select(
				'postalcodes.id',
				'postalcodes.postalcode', 
				'postalcodes.locality', 
				'bundeslands.title as bundesland')
			->get()
			->chunk(100);

I tested loading in chunk packets of 100, 500 and 1000 postalcodes with same result.

Perhaps i am using wrong the chunk() method?

  • Second one: Frontend Problem. Once the user click on the dropdown menu, it takes again several seconds to display the list and is not possible to go directly to the desired postalcode. If my postalcode is in the position 11k, I have a problem.

Problem solved with the select2 packet (https://select2.org/). It works great, the ux has improved a lot.

But still I need to speed up the query

Activity icon

Replied to Speed Up The User Experience Just With Laravel (PHP)

@wingly Giving a siple input field is not an option, because it could get to misstyped addresses or even people that do not remember which is their own postalcode introduce a false one giving a wrong address.

It seems I will have to use JS or any of thoose recommended packets

Activity icon

Replied to Speed Up The User Experience Just With Laravel (PHP)

@rumm.an I understand the concept behind the chunk() concept, But I need to get access to all the postcodes. However I have been trying to build the query without success. This is my original query

Postalcode::join('bundeslands', 'postalcodes.bundesland_id', 'bundeslands.id')
			->orderBy('postalcode')
			->select(
				'postalcodes.id', 
				'postalcodes.postalcode', 
				'postalcodes.locality', 
				'bundeslands.title as bundesland')
			->get();

This run out of memory

Postalcode::chunk(100, function ($postalcodes){
		foreach ($postalcodes as $postalcode) {                  
			$postalcode->join('bundeslands', 'postalcodes.bundesland_id', 'bundeslands.id')
				->orderBy('postalcode')
				->select(
					'postalcodes.id', 
					'postalcodes.postalcode', 
					'postalcodes.locality', 
					'bundeslands.title as bundesland')
				->get();
			}});

I have made a bunch of tests with the Join and the orderBy outside the loop and much more, but I have never get it to work.

I know it should work, but with that join i do not get it. What am I missing here?

May
12
1 month ago
Activity icon

Replied to Speed Up The User Experience Just With Laravel (PHP)

@tray2: It has already an index (foreign key), but as you said there are over 13k records in db

Activity icon

Started a new Conversation Speed Up The User Experience Just With Laravel (PHP)

I have a form to create an Address in which the user select the Zip code out of 13150 zip codes existing in Germany

I am selecting the minimum set possible from the database like this:

return Postalcode::orderBy('postalcode')->select('id', 'postalcode', 'locality')->get();

I pass this data to the view and make it available in a select input, like this:

<select name="postalcode_id" autocomplete="off" id="postalcode_id">
   <option value="">@lang('labels.general.select')</option>
   @foreach($postalcodes as $postalcode)
      <option value="{{$postalcode->id}}">{{$postalcode->postalcode}} - {{ $postalcode->locality }}</option>
   @endforeach
 </select>

However, the amount of data is so big that the select dropdown takes over three seconds to show up.

  • Question: Is there any form to speed up that experience without using JS (or Vue, Angular, or similar)?
May
09
1 month ago
Activity icon

Replied to Error: "Illegal Offset Type", When Redirect()->route()

@snapey @guybrush_threepwood

I was having a look to the home_route() method from the boilerplate and it would be a real mess if I try to rewrite or avoidto use it.

One thing is clear, the method is delivering a string that would be used as a direct redirection. Therefore I have tested the @snapey proposal of passing a generic candidate route to reach the Controller and then inside the Controller use the if statement if(auth()->user()->candidate)to decide what to do afterward.

the resulting method is also more clean and i could expand with new routes:

    function home_route()
    {
        if (auth()->check()) {
            if (auth()->user()->can('view backend')) {
                return 'admin.dashboard';
            }

            if(auth()->user()->candidate) { 
                return 'frontend.user.candidates';
            }

            if(auth()->user()->employee) { 
                return 'frontend.user.dashboard';
            }
        }

        return 'frontend.index';
    }
Activity icon

Replied to Error: "Illegal Offset Type", When Redirect()->route()

I have found the problem.

I am using the Laravel/boilerplate packet. https://github.com/rappasoft/laravel-boilerplate

After login it makes a redirection to a redirectPath() method that loooks like this:

public function redirectPath()
    {
        return route(home_route());
    }

This method It already returning a route.

and this one redirect to the helper I was trying to expand:

 function home_route()
    {
        if (auth()->check()) {
            if (auth()->user()->can('view backend')) {
                return 'admin.dashboard';
            }

// here is where I wanted to expand the the redirections
            if(auth()->user()->candidate) { 
                return redirect()->route('frontend.user.candidates.show', [auth()->user()->candidate]);
            }

            if(auth()->user()->employee) { 
                return 'frontend.user.dashboard';
            }
        }

        return 'frontend.index';
    }

So, I have to figure it out how those "magic" redirectPath method works or just eliminate it and go the conventional way

Activity icon

Replied to Error: "Illegal Offset Type", When Redirect()->route()

@guybrush_threepwood

dd(route('frontend.user.candidates.show', 1)); returns:

http://localhost/candidates/1

So. the model is there.

At this point I would think is a syntax problem in the redirect()->route()

Activity icon

Replied to Error: "Illegal Offset Type", When Redirect()->route()

@wheesnoza dd(auth()->user()->candidate->id); before the redirect returns the id of the model. In this case 1

Activity icon

Replied to Error: "Illegal Offset Type", When Redirect()->route()

@snapey Relations are as follow:

in User model

    public function candidate()
    {
        return $this->hasOne(Candidate::class);
    }

In Candidadtes

public function user()
    {
        return $this->belongsTo(User::class);
    }

This proposal

return redirect()->route('frontend.user.candidates.show', auth()->user()->candidate()->first()->id);

returned the same error

Activity icon

Replied to Error: "Illegal Offset Type", When Redirect()->route()

@guybrush_threepwood Yes, dd(auth()->user()->candidate) returns a model

Directly on the bowser it reaches the page. The problem is in the redirection

Activity icon

Replied to Error: "Illegal Offset Type", When Redirect()->route()

@wheesnoza the array give the same result

if(auth()->user()->candidate) { 
                return redirect()->route('frontend.user.candidates.show', ['candidate' => auth()->user()->candidate]);
            }
Activity icon

Replied to Error: "Illegal Offset Type", When Redirect()->route()

@guybrush_threepwood here is the Candidate model:

<?php

namespace App\Models\Candidate;

use Illuminate\Database\Eloquent\Model;
use App\Models\Auth\User;
use App\Models\Company\Company;
use App\Helpers\Helpers;

class Candidate extends Model
{
    protected $fillable = [ 'user_id',  'company_id', ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    use  Helpers;
}
Activity icon

Started a new Conversation Error: "Illegal Offset Type", When Redirect()->route()

I have this method

function home_route()
{
   if (auth()->check()) {
      if(auth()->user()->candidate) { 
         return redirect()->route('frontend.user.candidates.show', auth()->user()->candidate->id);
      }
   }

   return 'frontend.index';
}

that should redirect to the show method inside the CandidatesController:

public function show($candidate)
{ dd('hier');
	$model_name = 'candidates';
	$page_name = 'show';
	return view('frontend.company.candidates.show', compact('model_name', 'page_name', 'candidate'));
}

The dd('hier') in controller is to test if that point is reached.

Back to the home_route method, when

auth()->user()->candidate === true

the process goes inside the if, but it neves reaches the controller (notice the dd in controller). Before redirecting to the Controller it throws the following error:

Illegal offset type

I checked the routes and it exist:

| GET|HEAD | candidates/{candidate} | frontend.user.candidates.show | App\Http\Controllers\Frontend\User\[email protected] | web,auth 

defined like this:

Route::resource('candidates', 'CandidatesController');

Any idea what does it means that error?

May
08
1 month ago
Activity icon

Replied to Get Records Even If Relation Does Not Exist

@snapey You are right, that's why I needed to do a second loop in the view.

I am inserting a new column in the images table avatar of a boolean typ and make sure there is just one equals true per User

In that way I just add a ->where('imageas.avatar', true) statement in the query

Activity icon

Replied to Get Records Even If Relation Does Not Exist

@snapey I have a morph relation between user and ``´image```

User

    public function imageables()
    {
        return $this->morphMany(Image::class, 'imageable');
    }

Images

Relation::morphMap([
    'users' => 'App\Auth\User',
    'company' => 'App\Models\Company\Company',
    'clients' => 'App\Models\Client\Client',
    'pages' => 'App\Models\Page\Page',

]);

/**
 * Class ImagesRelationship.
 */
trait ImagesRelationship
{

...

    public function imageable()
    {
        return $this->morphTo();
    }
}

I made now the test using the the with() method. But it does not bring any result if the user has not image associated. but I need all users regardless they have or not uploaded an image (avatar)

Activity icon

Replied to Passing Data To All Views -> Performance Issues

@guybrush_threepwood, Now is working.

BTW, now the debugging bar is showing a reduction from about 80 queries and 200ms . That was the point

Thanks a lot!

Activity icon

Replied to Passing Data To All Views -> Performance Issues

@guybrush_threepwood I implemented your solution, but the variables are not passed through. Do I have to register anywhere this new ViewServiceProvider?

I get the following error:

Facade\Ignition\Exceptions\ViewException
Undefined variable: unseen_notification (View: C:\localhost\resources\views\frontend\user\includes\company-menu.blade.php)
Activity icon

Started a new Conversation Get Records Even If Relation Does Not Exist

I have following query;

        return User::join('images', 'users.id', 'images.imageable_id')
            ->where('images.imageable_type', 'users')
            ->select(
                'users.id',
                'users.first_name',
                'users.last_name',
                'users.email',
                'images.img_slug as img_slug'
            )
            ->get();

It will return all the users in database that has an image associated, however, I need all users, regardless they have an image (avatar) or not.

I could use the ->with('imageables') method, but, since there is a morph relation I will need to make a second looping in the frontend in order to grab the exact image of each user.

How could I get all users directly in the query?

Activity icon

Replied to Passing Data To All Views -> Performance Issues

@michaloravec I have been trying to apply that concept, but I did not succeed. Could you tell me how do you pass data from the composer to just one view?

I did these and did not work:

 public function compose(View $view)
   { 
	 $notifications = $employee->notifiables->whereNull('read_at');
        $unseen_notification = count($notifications);

	
         $view('frontend.includes.nav', ['notifications' => $notifications, 'unseen_notification' => $unseen_notifications));
   }

And a bunch of other ways but did not succed. All I find in internet is how to pass data to all views or, how to pass data toone view, but not to another view which is @include in the main view.

May
07
1 month ago
Activity icon

Started a new Conversation Passing Data To All Views -> Performance Issues

I am passing data to All views using composer.

I have build a notification system to show a badge in the top of the user menu, showing the number of non-read messages that the user has in his user area.

Very user friendly, however, the debugging bar is showing me that most of the queryes in any view are not related with building that view itself but checking the notifications of the user.

Is there any other way to make those queries upfront and saving the results in a way that could be reachable from every view instead of making those queries each ttime that user changes the view?

Any way to make the user aware that he has an unread message/notification without sharing it to all views? (of course emailig the user would be an option, but it does not shows it in the application)

May
03
2 months ago
Activity icon

Replied to False Positive With OrWhere And NULLABLE

@michaloravec Thanks for the answer.

I had to make a small change to make it work. I have to make explicit the comparison with NULL after the WHEN and add this ->when($request->phone != 'null',

return $this->model

->when($request->phone != 'null', function ($query, $phone) {
   return $query->where('phone', $phone); })

->when($request->mobile_phone != 'null', function ($query, $mobile_phone) { 
   return $query->orWhere('mobile_phone', $mobile_phone); })
                    
->when($request->slug != 'null', function ($query, $slug) { 
   return $query->orWhere('slug', $slug);  })
                    
->when($request->email != 'null', function ($query, $email) {
   return $query->orWhere('email', $email); })
 
->exists();
Activity icon

Started a new Conversation False Positive With OrWhere And NULLABLE

in order to avoid duplicated records I need to check if a client exist in data base before I create a new one.

The clients table have unique emails, phone, mobile_phone and slug.

But mobile_phone, emails and phone are also nullable.

I am doing this:

public function checkIfClientExist($request)
{
    return $this->model->where('phone', $request->phone)
                    ->orWhere('mobile_phone', $request->mobile_phone)
                    ->orWhere('slug', $request->slug)
                    ->orWhere('email', $request->email)
                    ->exists();
}

But because some of the check columns are NULLABLE it gives me a false positive. For example:

  • After the first client with mobile_phone == NULL all the request->mobile_phone == NULL are meeting this criteria

->orWhere('mobile_phone', $request->mobile_phone)

How could I avoid that NULL is taken as a value and avoid the False positive?