mteb/FreshStackRetrieval huggingface dataset:
I developed a web application with React frontend and Laravel for stateless API.
I would like to access to the frontend with the url "http://localhost/my-application" and the backend's API with the url "http://localhost/api/my-application/".
I created the folder "www/api/my-application" and here I put a symlink of public index.php of my Laravel backend.
The problem is that to call the APIs, I have to put this url "http://localhost/api/my-application/api/login".
As you can see I have to repeat "/api" because Laravel APIs have that default url. Also, if I try to just access to just "http://localhost/api/my-application/" I get a page with 500 Server Error, and the log says

ERROR: View [welcome] not found. {"exception":"[object] (InvalidArgumentException(code: 0): View [welcome] not found.

This is because it tries to access to the view. But I don't have any views, I would like that my Laravel project has just API stuff
How to clean the project so that I just have to access to "http://localhost/api/my-application/" to access to the APIs? So the "login" API, should be here: "http://localhost/api/my-application/login" and not here "http://localhost/api/my-application/api/login"
I have dispatched a job and the the job is added to the database on the specified table, e.g. "Jobs. The jobs are not being processed, even though the jobs are added to the database. No log neither failed_job.
I have tried to create a new simple job with only Logger suspecting that I have errors in the handle code, still not working.
I'm Using Laravel 10 I'm trying to get Random Record Without Duplication  using inRandomOrder But It Giving Duplicate Record Some Time.
help me to Solve It
My Controller Code
$Question = Question::inRandomOrder()->limit(50)->get();
I have this route defined:
Route::match(['get', 'post'], '/{class}/{function}/', [OldBackendController::class, 'apiV1']);

If I do this request:
POST /api/v2_1/wishlist/archive

Laravel enters int the OldBackendController, and the value of $class variable (in the controller), is this:
api/v2_1/wishlist

Why? It shouldn't enter in the controller, cause the request does not contains 2 variables, but 4.
The strange thing is if in the controller I print $request->segments() value, I get all 4 segment:
Array
(
    [0] => api
    [1] => v2_1
    [2] => wishlist
    [3] => archive
)
I am attempting to integrate Laravel 11 with React.js for data retrieval and transmission between the two. However, I cannot locate the routes/api.php file in the latest version of Laravel.
I have searched for others experiencing the same issue, but I have yet to find any similar cases since Laravel 11 was only released a week ago.
This is Laravel 11 + Fortify + Sanctum. I'm using Laravel for my API backend. Front-end is a 1st-party SPA.
I was just testing my login endpoint (POST) using Thunder Client (XHR). When login call succeeds once, any subsequent calls to login endpoint issue a redirect to root url instead of returning a JSON response telling that the user is already authenticated. This means the caller will get a 405 (Method Not Allowed) as final response since there is no POST endpoint on root url.
In the past, we were able to control this buggy behavior by modifying RedirectIfAuthenticated middleware and redirecting only if this was not an XHR. In Laravel 11, they have moved these middleware into the framework itself. I also hear that they have fixed the problem itself, so there is no need to edit the middleware anymore, but I'm still seeing the bug.
I also tried the new helper method of Laravel 11 to override redirection behavior like this (in bootstrap/app.php):
$middleware->redirectUsersTo(function() {
    if(request()->wantsJson()) {
        return response()->json(['result' => 'success'], 200);
    } else {
        return '/home';
    }
});

But this results in other unrelated problems. Am I missing something here?
Update
I have found that adding the following to RedirectIfAuthenticated middleware's handle function fixes the problem:
if ($request->expectsJson())
  return response()->json(['message' => 'authenticated.'], 200);

This problem and this fix appears to be well known for many years. However, the fact that this middleware is now part of the framework in Laravel 11 and lives in vendor directory means I have to add this line manually to deployment and also take care of it not getting overwritten during updates. Can't see why Laravel haven't added this simple check over the past several major versions.
I am using the Cknow/Money package to handle money values in models.
I have this model event that validates a value before saving to prevent wrong data from being entered due to a common scenario:
I have this laravel 10 saving event:
    static::saving(function (self $order) {
        if ($order->refunded_amount->greaterThan($order->total_amount)) {
            // Can't refund more than the order total.
            $order->refunded_amount = $order->total_amount;
            dd($order->refunded_amount); // This is still the original refunded_amount value instead of the new total_amount value
        }
    });

If I check the value of $order->refunded_amount after it is set to $order->total_amount, the value is still the wrong refunded amount as if the assignment didn't work somehow.
On the model, these are both cast:
protected $casts = [
    'total_amount'    => MoneyIntegerCast::class.':currency',
    'refunded_amount' => MoneyIntegerCast::class.':currency',
];

I have a mutator which sets the value on the model:
public function setRefundedAmountAttribute(Money $value): void
{
    if ($this->currency instanceof Currency && $value->getCurrency()->getCode() !== $this->currency->getCode()) {
        throw new InvalidMoneyException(
            "{$value->getCurrency()->getCode()} does not equal existing currency {$this->currency->getCode()}"
        );
    }

    $this->attributes['currency'] = $value->getCurrency();
    $this->attributes['refunded_amount'] = $value->getAmount();
}

I've tried removing the mutator to see if that is the problem, but that does not help.
I can assign a value outside of the saving event and no issues:
$someMoney = Money::USD(10.00);
$order = new Order();
$order->refunded_amount = $someMoney;
$order->save();

This only happens with objects within the Eloquent models. If I were to have something like refund_count and total_count and both are integers, then the result would be that refund_count would now equal total_count as expected.
To be clear, this isn't just happening with these money objects. It is also happening with dates that Laravel has cast to Carbon objects.
protected $casts = ['renewed_at' => 'datetime'];

static::saving(function (self $order) {
    $order->renewed_at = now();
    dd($order->renewed_at); // The renewed_at value will still be what it was originally set to instead of now()
});

If I refresh the model after saving, it will show the updated timestamp values from the saving event, but it won't show them if I add a dd() right after the value is set within that event. This implies there is some sort of caching within the model going on after the accessor is first called.
This isn't the case with the money objects. They don't change within the saving event and they don't change after a refresh.
Is there some sort of model level caching introduced in Laravel after v8? I don't remember this being an issue in earlier versions but it is happening in v10.
I'm attempting to implement basic authentication functionality for testing purposes. I'm testing via Postman, so before logging in, I make a GET request to /sanctum/csrf-cookie. After that, I hit the /login endpoint and am able to receive data (if this part $request->session()->regenerate(); is commented out). However, if I try to access a protected route, I receive an error. Despite following the documentation closely, I'm encountering an issue when a user attempts to sign in. I receive an error when $request->session()->regenerate(); this is not commented out:
"message": "Session store not set on request."

Here's my bootstrap/app.php:
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        using: function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(function () {
                    // routes/api.php is not included here
                    require base_path('routes/Api/V1/Auth/routes.php');
                });
        },
        web: __DIR__ . '/../routes/web.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->statefulApi();
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Here's my login:
public function login(object $request)
    {
        // Validate user credentials
        if (!Auth::attempt($request->only(['username', 'password']))) {
            return $this->failedRequest('', 'Invalid email address or password', 400);
        }

        // Regenerate the user's session to prevent session fixation
        $request->session()->regenerate();

        // Sign in user
        Auth::login(Auth::user());

        // Return data
        return $this->successfullRequest(Auth::user(), 'User successfully logged in', 200);
    }

My routes:
Route::group(['prefix' => 'v1/auth'], function () {
    Route::post('register', [AuthController::class, 'register']);
    Route::post('login', [AuthController::class, 'login']);
    Route::post('logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
});

If I remove this part, I basically receive Unauthenticated message when I try to hit .../logout

$request->session()->regenerate();

sanctum.php -> stateful:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
        env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : '',
        env('FRONTEND_URL') ? ',' . parse_url(env('FRONTEND_URL'), PHP_URL_HOST) : ''))),

my env file:
APP_URL=http://localhost:5000
FRONTEND_URL=http://localhost:3000
I want to add service provider in laravel 11, but i am not sure how to add it using laravel 11. As previous version of laravel, it is added in config/app.php file, but in laravel 11 it needs to be added in packageServiceProvider file within providers folder.
Below is my code, please tell me if i am wrong somewhere..
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class PaytmWalletServiceProvider extends ServiceProvider
{

    /**
     * All of the container bindings that should be registered.
     *
     * @var array
     */
    public $bindings = [
        ServerProvider::class => Anand\LaravelPaytmWallet\PaytmWalletServiceProvider::class,
    ];

    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        //
    }
}
Before Laravel 11, I used to bind listeners to events inside the App\Providers\EventServiceProvider provider class, for example:
<?php

namespace App\Providers;

use App\Events\MyEvent;
use App\Listeners\MyListener;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Http\Client\Events\ResponseReceived;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event to listener mappings for the application.
     *
     * @var array<class-string, array<int, class-string>>
     */
    protected $listen = [
        MyEvent::class => [
            MyListener::class
        ]
    ];
}

In Laravel 11, this binding isn't necessary at all since Laravel auto-discovery feature auto-discovers the listeners from the app/Listeners directory. How can I instruct Laravel to auto-discover listeners from a different directory such as app/Domain/Listeners ?
I have a route that serves as a webhook endpoint that gets called by a remote service, but the calls that the service makes to the webhook always fail.
After some inspection of the service logs, I learned that the service is getting an HTTP error code 419.
I used to add exceptions inside the $except property of the App\Http\Middleware\VerifyCsrfToken middleware, However, I'm on Laravel 11 and I can't find this middleware anymore. What is the solution to this problem?
I'm on Laravel 10, and new to it too. Im trying to submit a form to a check() function that does some basic checks in db. Then it redirects the user to another route with $_GET data in the URL and to prevent the "POSTDATA warning because the refresh function wants to resend previous POST form data." warning on the check() function page.
here is the friendly url with the $_GET data {from?} and {search_string?}
Route::group(['middleware' => ['web']], function () {
  Route::post('/check', [SampleController::class, 'check'])->name('sample.check');
  Route::get('/order/{from?}/{search_string?}', [SampleController::class, 'order'])->name('sample.order');
}

this is my check() function
 public function check(Request $request) : RedirectResponse
    {

        $search_string = strtoupper(trim($request->search_string));
        $from = strtolower(trim($request->data_from));
        ...
        ...

        //if success redirect
        return redirect()->to(route('sample.order'), ['from' => $from, 'search_string' => $search_string]);
    }

and here is the order function
public function order(Request $request) 
    {
        $validator = Validator::make($request->route()->parameters(),[
            'from' => [
                'required',
                'string',
                'in:uk,us,id'
            ],
            'search_string' => [
                'required',
                'string',
                'max:255'
            ]
        ]);

        if ($validator->fails())
        {
            //abort(404, $validator->errors()); //this shows the json error message, how to make it show
            return view('samples::order')->withErrors($validator->errors());
        }

        
        return view('samples::order', ['from' => $request->from, 'search_string' => $request->search_string]);
    }

question is:

is this the "laravel way" to validate the parameters in the url?
is this how to to prevent the "POSTDATA warning" without using ajax?
i want to make the project data saved in history page after a project finished and also for the soft delete function in the same page. but it's only shows the data with status done
class HistoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $projects = Project::where('status', 'Done') //select data with done status only
                    ->orWhereNotNull('deleted_at') // shows soft deleted data
                    ->orderBy('id', 'desc')
                    ->paginate(5);

        // Pass the merged projects to your view
        return view('history', compact('projects'));
    }
}

i tried to have 2 variable then merges it. it does work but it makes the pagination doesn't work. i also try this but it result the same
public function index()
    {
        $projects = Project::withTrashed()
                            ->where('status', 'Done')
                            ->orderBy('id', 'desc')
                            ->paginate(5);

        // Pass the merged projects to your view
        return view('history', compact('projects'));
    }

is it possible to do this?
I'm creating a policy for model todo to authorize the user role and then set custom access for model functions like create(), update(), etc. As written in Laravel Documentation, we can create a policy for the todo model with php artisan make:policy todoPolicy --model=todo.
When we use modelname + Policy for our policy name that is located in App\Policies folder, Laravel automatically register them for the model, as we used todoPolicy for todo Model.
Also, to check if this Policy works or not, I had set return true; for the create() function in the todoPolicy file, and I'm calling $this->authorize('create,' todo::class); in add function of component for testing it.
But it always returns 403, not an authorized page. What's the problem with my code?
Component / Controller
namespace App\Livewire\Elements\Todolist;

use Livewire\Component;
use App\Models\todo;

class Todolist extends Component
{
    public $description;

    public function done($id) {
        sleep(0.5);
        todo::where('id',$id)->first()->update([
            'is_done' => true,
        ]);
    }

    public function restore($id) {
        sleep(0.5);
        todo::where('id',$id)->first()->update([
            'is_done' => false,
        ]);
    }

    public function delete($id) {
        sleep(0.5);
        todo::where('id',$id)->first()->delete();
    }

    public function add(todo $todo) {
        $this->authorize('create',$todo);
        
        $this->validate([
            'description' => ['required','max:128'],
        ]);
        sleep(0.5);
        todo::create([
            'user_id' => session('user_id'),
            'description' => $this->description,
        ]);
        $this->reset();
    }

    public function render()
    {
        return view('livewire.elements.todolist.todolist',[
            'todos' => todo::orderBy('is_done','ASC')->orderBy('created_at','DESC')->get(),
        ]);
    }
}

TodoPolicy
namespace App\Policies;

use App\Models\User;
use App\Models\todo;
use Illuminate\Auth\Access\Response;

class todoPolicy
{
    /**
     * Determine whether the user can view any models.
     */
    public function viewAny(User $user): bool
    {

    }

    /**
     * Determine whether the user can view the model.
     */
    public function view(User $user, todo $todo): bool
    {

    }

    /**
     * Determine whether the user can create models.
     */
    public function create(User $user): bool
    {
        return true;
    }

    /**
     * Determine whether the user can update the model.
     */
    public function update(User $user, todo $todo): bool
    {
        //
    }

    /**
     * Determine whether the user can delete the model.
     */
    public function delete(User $user, todo $todo): bool
    {
        //
    }

    /**
     * Determine whether the user can restore the model.
     */
    public function restore(User $user, todo $todo): bool
    {
        //
    }

    /**
     * Determine whether the user can permanently delete the model.
     */
    public function forceDelete(User $user, todo $todo): bool
    {
        //
    }
}

I have tried registering policies manually, but it didn't change anything.
I am encountering the following error in my new installation of Laravel 11 and Vue.js when I try to submit a form, in this case, the Register form.

419 | PAGE EXPIRED

I have checked this question and yes, I do have @csrf in my register form and
<meta name="csrf-token" content="{{ csrf_token() }}">

Steps to reproduce

I installed a fresh instance of Laravel 11:

composer create-project laravel/laravel test
cd test/


I added the laravel/ui package

composer require laravel/ui


I added the Vue.js and Auth UI

php artisan ui vue --auth

It gave me a warning:

The [Controller.php] file already exists. Do you want to replace it? (yes/no) [yes]

I typed yes then [Enter].

I installed the npm packages and initialized vite

npm install && npm run dev


Iniatilized the dev server and tried to register

php artisan serve

Edit
There are additional steps that were done on the same repo. We work with mongodb hence we added the MongoDB configurations as well.

Installed the laravel/mongodb package

composer require mongodb/laravel-mongodb


Added the configurations in config/database.php as below:

'mongodb' => [
    'driver' => 'mongodb',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE', 'assets'),
    'username' => env('DB_USERNAME', ''),
    'password' => env('DB_PASSWORD', ''),
    'options' => [
        'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'),
    ],
],


Updated .env file as shown below:

DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=27017
DB_DATABASE=testdb
DB_USERNAME=
DB_PASSWORD=

I am hoping there's someone with a solution.
NB I tried to install Laravel 10 and do the same processes and it works perfectly. What has changed in Laravel 11? Any help is appreciated.
Edit
Below is the contents of my bootstrap/app.php.
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

and register.blade.php
<form method="POST" action="{{ route('register') }}">
  @csrf
    <div class="row mb-3">
    // Rest of code
table bayarlanjas
| tglbayar   | bayarlanja |user_id|
| ---------- | ---------- |-------|
| 2024-01-05 |     10     |   1   |
| 2024-02-06 |     20     |   1   |
| 2024-03-07 |     30     |   1   |
| 2024-04-08 |     40     |   1   |

table zakats
| tglawalhaul| tglakhirhaul |user_id|
| ---------- | ------------ |-------|
| 2024-01-01 |  2024-02-25  |   1   |
| 2024-03-01 |  2024-04-25  |   1   |


which I tried
SELECT
  zakats.*,
  bayarlanjas.user_id,
  sum(bayarlanja) AS total_bayar
FROM
  `zakats`
  LEFT JOIN `bayarlanjas` ON `bayarlanjas`.`user_id` = `zakats`.`user_id`
WHERE
  `bayarlanjas`.`tglbayar` BETWEEN zakats.tglawalhaul
  AND zakats.tglakhirhaul
  AND `zakats`.`user_id` = 1
GROUP BY
  `bayarlanjas`.`user_id`


But Error:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated

What I want

| tglawalhaul| tglakhirhaul |total_bayar|user_id|
| ---------- | ------------ |-----------|-------|
| 2024-01-01 |  2024-02-25  |     30    |   1   |
| 2024-03-01 |  2024-04-25  |     70    |   1   |
Laravel 11 does not come with a middleware file and the kernel.php file has been removed altogther. So, when I create a custom middleware, how do I register it?
I do not know where to register middleware. Laravel 11 has been very confusing.
The upgrade notes for Laravel 11 say:

The float column type now creates a FLOAT equivalent column without total digits and places (digits after decimal point), but with an optional $precision specification to determine storage size as a 4-byte single-precision column or an 8-byte double-precision column. Therefore, you may remove the arguments for $total and $places and specify the optional $precision to your desired value and according to your database's documentation:
$table->float('amount', precision: 53);


However, the database documentation doesn't provide any explanation for what the precision argument might represent or why it defaults to 53. What effect will changing the value have on the resulting column?
My program is like this =
$listreq2 = OutboundRequest::with('outboundmaterialrequest')
->whereIn('id', $outboundIds)
->whereHas('outboundmaterialrequest', function ($query) use ($ids) {
    $query->whereIn('id', $ids);
})->get();

Why is my data filter on ->whereHas('outbound material request', function ($query) use ($ids) { doesn't work the contents of $ids for example are = 2,3
but all of the outboundmaterialrequest data appears
image
This is the admin side, when on the home page the theme of the web is white and it is fine there, I'm guessing it's because it is assigned to multiple css tag influencing the same part but I dont know here the files are or what even the name of the file is, how do I fix it
The only part I know that is attached to is a tag <x-app-layout>  </x-app-layout>, it's empty like this but it adds the dropdown menu