Home > other >  How to properly achieve this scenario?
How to properly achieve this scenario?

Time:10-25

I have a route:

Route::get('/', [FrontController::class, 'index']);

In this Controller I get the weather for the next 5 days for the city of the authenticated user. The users table has a column "city" and the api request is based on that city.

if (auth()->user()) {
    $cityName = auth()->user()->city;
    $apiKey = config('services.api.key');

    // get the weather based on the provided city

    $weatherResponse= Http::get("...");

    return view('front.index', [
        'weatherRespons' => $weatherRespons->json(),
    ]);
} else {
    return view('front.index');
}

In the index view

@guest

    <h1>login/register to show your city weather</h1>

@else

    <h1>Weather in {{ $weatherResponse['city'] }}</h1>

    <x-weather :weatherResponse="$weatherResponse" />

@endguest

This component x-weather has some styles to show the weather for the 5 days.

Now I want to have an input on this view to allow the user to enter the name of a city click in a button and after that the component x-weather should update with the weather for that searched city. However, the page should not refresh, because if page refreshes it will appear the weather based on the city of the authenticated user.

Do you know how to approach this properly in terms of architecture? Thanks!

CodePudding user response:

According to my understanding of the question, your problems are as below:

  1. Showing the weather of logged in user on page load

  2. then once they input desired location the system then display that location without refreshing the page.

Not sure this solution works for you but I came up with some ideas and hope they can be useful to you.

Controller:

  1. For logged in user, the controller passes user location to view.

  2. Create another function for simple calling weather api which is for your input.

View:

  1. The input for logged in user auto shows the current location weather which calls the controller api function on document ready. (or you can hide it if you want by using javascirpt)

  2. Ajax, When user inputs the desired location then use ajax to pass the location to controller calling the api function. When return value is succeed, then you can clear orginal content then add whatever you want to the page without refreshing it.

Not going into coding details at this moment but I am sure you get the idea.

Take a look at ajax

  • Related