mteb/FreshStackRetrieval huggingface dataset:
I'm trying to block certain IP addresses from accessing my website using laravel 11.3.0, all the solutions i.m coming across suggest the method were you register the middleware in kernel.php but the version of laravel i'm using does not have kernel.php. So how do i go about this?
i have tried registering it in app.php
<?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) {
        $middleware->web(append: [
            \App\Http\Middleware\HandleInertiaRequests::class,
            \Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
        ]);
        $middleware->alias([
            'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
            'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
        ]);

         
        
        return $middleware;
    })

    ->withMiddleware([
        \App\Http\Middleware\BlockIpMiddleware::class,
    ])
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })
    ->create();


ERROR
PHP Fatal error:  Uncaught TypeError: Illuminate\Foundation\Configuration\ApplicationBuilder::withMiddleware(): Argument #1 ($callback) must be of type ?callable, array given, called in C:\xampp\htdocs\swamsite2\Swarmsite\Daniel\telegram\bootstrap\app.php on line 29 and defined in C:\xampp\htdocs\swamsite2\Swarmsite\Daniel\telegram\vendor\laravel\framework\src\Illuminate\Foundation\Configuration\ApplicationBuilder.php:227
Stack trace:
#0 C:\xampp\htdocs\swamsite2\Swarmsite\Daniel\telegram\bootstrap\app.php(29): Illuminate\Foundation\Configuration\ApplicationBuilder->withMiddleware(Array)
#1 C:\xampp\htdocs\swamsite2\Swarmsite\Daniel\telegram\artisan(12): require_once('C:\xampp\htdocs...')
#2 {main}
thrown in C:\xampp\htdocs\swamsite2\Swarmsite\Daniel\telegram\vendor\laravel\framework\src\Illuminate\Foundation\Configuration\ApplicationBuilder.php on line 227
I am looking to implement a search function, that optionally includes the various fields that I have for my users to search on.
My code thusfar:
        $categories = $request->input('category'); // array(int)
        $textSearch = $request->input('text'); // string

        $query = Product::query();

        if(!is_null($categories)){
            //$query->selectSub();
            foreach($categories as $catId){
                $category = ShopCategory::find($catId);

                $query = $query->whereBelongsTo($category);//TODO
            }
        }
        if(!is_null($textSearch)){
            $query = $query->whereAny([
                'name',
                'description',
                'shortDescription',
            ],
                'like', '%'.$textSearch.'%');
        }

        $searchResults = $query->paginate(36);

My goal is to reach an SQL statement equivalent to:
SELECT * FROM products WHERE (shop_category_id = ? OR shop_category_id = ?) AND (/* text search LIKE */)
But thusfar, I end up with more of a :
SELECT * FROM products WHERE shop_category_id = ? AND shop_category_id = ? AND (/* text search LIKE */)
Where each of the category id's are ANDed as part of the overall query instead of ORed in a group.
I am aware of or*() query methods, but it is unclear how to properly group them for the desired effect instead of just ORing them along with the text search.
Edit: Based on the accepted answer, I landed on this:
            $mainQuery->where(function($query) use ($categories) {
                foreach ($categories as $catId) {
                    $category = ShopCategory::find($catId);
                    $query->orWhereBelongsTo($category);
                }
            });
I have the following routes in my web.php file
Route::resource('/tenants', TenantControler::class);

The command  php artisan route:list shows all the resource routes with model name

tenants/{tenant}

I want a prefix, so I created a route group
Route::name("tenants.")->prefix("tenants")->group(function () {
    Route::resource('/', TenantControler::class);
});

now if I try php artisan route:list the route list does not show model name in
routes but empty braces {}

tenants/{}

why its missing the model in the route?
When I tried to access the ID of a model (JenisSurvey) within the show method of the JSController, the ID is always null, even though the model is correctly retrieved. Interestingly, I have other controllers in my application where similar operations work perfectly fine. For example, if I use the User model in a different controller, I can access the ID without any issues.
I've already checked the route configuration, model binding, auto-loaded files, controller logic, and the data with the searched ID exists in the database. Everything seems to be in order, and the logic mirrors that of other controllers where similar operations work.
Here's a simplified version of the show method in the JSController:
public function show(JenisSurvey $jenisSurvey)
{
    dd($jenisSurvey->id); // This always returns null

    if (!$jenisSurvey) {
        return response()->json(['error' => 'Data not found.'], 404);
    }
    return new JSResource($jenisSurvey);
}


Interestingly, I have other controllers in my application where similar operations work perfectly fine. For example, if I use the User model in a different controller (UserController), I can access the ID without any issues. Here's a simplified version of the show method in the UserController for comparison:
public function show(User $user)
{
    dd($user->id); // This returns the correct ID
    return new UserResource($user);
}

Additionally, when I switch the model and resource in the UserController to JenisSurvey, it works as expected.
// UserController but with jenis survey model and resource
public function show(JenisSurvey $user)
{
    dd($user->id); // This returns the correct ID
    return new JSResource($user);
}

Here are the routes:
Route::group(['namespace' => 'App\Http\Controllers', 'middleware' => 'auth:sanctum'],function () {
    Route::apiResource('users', UserController::class)->middleware(['auth','verified','role:admin']);
    Route::apiResource('js', JSController::class)->middleware(['auth','verified','role:admin|nasabah']);
});

Here are the screenshots below.
JSController(Jenis Survey Controller):

UserController using user's model and resource:

UserController using JenisSurvey's model and resource:

JSController (var dumping the whole model):
photo
UserController (with Jenis Survey model and resource):
photo
Given that the issue seems to be specific to the JSController (Jenis Survey Controller) file, I suspect there might be something unique about its setup or environment. Any insights or suggestions on how to troubleshoot this issue further would be greatly appreciated.
I'm having trouble with pagination in Laravel 10. I have generated 13 data from my database and I'm on page 1, so I'm expecting to see something like

"Showing 1 to 8 of 13 results"

but instead, my code is displaying the message

"Showing 1 to 13 of 13 results"

what am I doing wrong? any help is appreciated.
this is my code:
    public function index(Request $request)
    {
        $client = new \GuzzleHttp\Client();

        $perPage = $request->query('per_page') ? : 8;
        $page = $request->query('page') ? : 1;

        $url = "http://localhost/api/culinary?page=$page&per_page=$perPage";

        $response = $client->request('GET', $url);

        $json = json_decode((string)$response->getBody(), true);

        $paginatedResult = new LengthAwarePaginator(
            $json, // the data to be paginated
            count($json), // total count of the data
            $perPage, // number of data shown per page
            $page, // current page number
        );

        $view_data = [
            'title' => 'Browse Culinary',
            'data' => $paginatedResult,
        ];
        return view('culinary.index', $view_data);
    }

and I'm using this code in the index.blade.php to show the pagination part
{{ $data->withQueryString()->withPath('/culinary')->links() }}
i use Laravel11 sanctum session (not token)
Login and logout (endpoints) are working correctly when called from postman
but when I call  other api end points it  gives me 401 unauthorized
Could someone help me out please?aaa
I have watched several videos and read some related tutorials about customization of the register form of Laravel/JetStream registration system. All I found is something like this:
//resources/views/auth/register.blade.php

<div class="mt-4">
    <x-label for="gender" value="{{ __('Gender') }}" />
    <x-dropdown id="gender" class="block mt-1 w-full" name="gender" :value="old('gender')" required>
        <x-slot name="content">
            <option value="0">Select Gender</option>
            <option value="1">Female</option>
            <option value="2">Male</option>
        </x-slot>
    </x-dropdown>
</div>

However I want to populate the genders dropdown from a database table, say "genders".
For this I have created a model Genders.
All I need to do is adding the following line
//this line will be in a file but which one?
$genders = Genders::all();

Then I will be able to list the items in the view, as follows:
<div class="mt-4">
    <x-label for="gender" value="{{ __('Gender') }}" />
    <x-dropdown id="gender" class="block mt-1 w-full" name="gender" :value="old('gender')" required>
        <x-slot name="content">
            <option value="0">Select Gender</option>
            @foreach ($genders as $gender)
                <option value="{{$gender->id}}">{{$gender->name}}</option>
            @endforeach
        </x-slot>
    </x-dropdown>
</div>

I have added the following code into app/Providers/FortifyServiceProvider.php
<?php

namespace App\Providers;

use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Actions\Fortify\UpdateUserPassword;
use App\Actions\Fortify\UpdateUserProfileInformation;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Laravel\Fortify\Fortify;
use App\Models\Gender;

class FortifyServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //I have added this but no change ):

        Fortify::registerView(function () {
            $genders = Gender::all();
            return view('auth.register', ['genders' => $genders]);
        });
    }

I could not find where should I put the code $genders = Genders::all(); and pass $genders to view register.blade.php? This could simple for a few options but what if I want to list countries for example?
After run composer create-project laravel/laravel:^11.0 project-name then going to my project folder cd project-name after that i should run php artisan serve but i got an error at this step that seems vendor folder not found in my project
Please note: If i using laravel 8 it's work fine but i need to use laravel 11
Help me, Thank!
My php version is 8.2.10
Try to using laravel 11 but can't, On the other hand laravel 8 works find.
PLease note that I'am try to run composer install and composer update and remove composer cache
Full error message: "PHP Warning:  require(/home/ahmedelmoslmany/Laravel-demo/example-app11/vendor/autoload.php): Failed to open stream: No such file or directory in /home/ahmedelmoslmany/Laravel-demo/example-app11/artisan on line 9
PHP Fatal error:  Uncaught Error: Failed opening required '/home/ahmedelmoslmany/Laravel-demo/example-app11/vendor/autoload.php' (include_path='.:/usr/share/php') in /home/ahmedelmoslmany/Laravel-demo/example-app11/artisan:9
Stack trace:
#0 {main}
thrown in /home/ahmedelmoslmany/Laravel-demo/example-app11/artisan on line 9"
I'm trying to work with Laravel 11, and deleted all migrations and created my own migrations, even deleted the database from mysql (which is a waste, I could use the old data with the new app in Laravel 11), but is not working at at all. It gives the error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydatabase.sessions' doesn't exist

Why that table still exists and its being called from code, even if I didn't create?
I have a User model and a Blocklist model, Now when I call User::all() I only want to return Users who are not related based on records in the block list table.
For instance:
user Table



id
...




1
...


2
...


3
...


4
...


5
...



blocklist Table



id
user_id
blockable_id
blockable_type




1
1
2
\App\Models\User


2
1
3
\App\Models\User


2
5
1
\App\Models\User



User Model
...

public function blocklist()
{
    return $this->hasMany(Block::class);
}


Blocklist Model
...

public function blockable(): MorphTo
{
   return $this->morphTo();
}


UserController
...
$users = \App\Models\User::whereDoesntHave('blocklist', function (Builder $query) {
    $query->where('user_id', auth('sanctum')->id());
    $query->orWhere(function (Builder $query) {
       $query->where('blockable_id', auth('sanctum')->id());
       $query->where('blockable_type', User::class);
    });
})->all();

The idea is that, if user: 1 is making this request they should not see user: 2 and user: 3 whom they have blocked and they should also not see user: 5 who has also blocked them, but this is not how it works, whatever I do all the users are still returned.
I was working on adding localization to my Laravel 11 project, and I created a middleware called SetLocale that consists of the codebase similar to below:
public function handle(Request $request, Closure $next): Response
    {
        App::setLocale(session()->get('locale'));
        return $next($request);
    }

I added it to my bootstrap/app.php file like this:
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__ . '/../routes/web.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(SetLocale::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

In my LocalizationController, I set the session like this:
public function setLocalization(string $locale): RedirectResponse
{
    session()->put('locale', $locale);
    App::setLocale($locale);
    return back();
}

My route in web.php looks like this:
Route::get('/locale/{locale}', [LocalizationController::class, 'setLocalization'])->name('locale.switch');

Here's what I tried:

Used the Session facade throughout the codebase, but it didn't work.
Used back()->with('locale', $locale); when returning in the setLocalization() function in the LocalizationController, but it didn't work.
Tried various changes, but I couldn't retrieve the 'locale' session data in my middleware.

The only way I got it to work was by wrapping the middleware around the route like this:
Route::prefix('localization')->middleware([SetLocale::class])->group(function() {
   Route::get('/locale/{locale}', [LocalizationController::class, 'setLocalization'])->name('locale.switch');
});

Is my use of global middleware incorrect, or did Laravel change how it handles sessions for global middleware?
Just an FYI, Laravel has now moved its middleware to elsewhere. Now it's a clean file located in the bootstrap/app.php file.
Thanks for your help.
I have tried to search for tutorial to move the public folder, but from all the guide it seems like the code is different than version 11. The folder structure I want to move will be like:

public (public folder is here)
program (all the other files to be stored inside this folder)

I have modified the public/index.php file to be:
<?php

use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../program/storage/framework/maintenance.php')) {
    require $maintenance;
}

// Register the Composer autoloader...
require __DIR__.'/../program/vendor/autoload.php';

// Bootstrap Laravel and handle the request...
(require_once __DIR__.'/../program/bootstrap/app.php')
    ->handleRequest(Request::capture());

However, when I try to run php artisan serve, I get the error
   Symfony\Component\Process\Exception\RuntimeException

  The provided cwd "C:\wamp64\www\my-project\program\public" does not exist.

What are the things needed to modify to get it works?
I am working on this beginner Laravel tutorial. In this example, why is the variable $incomingFields required?
class userController extends Controller
{
public function register(Request $Request) {
  $incomingFields = $Request->validate({
     'name' => 'required',
     'email' ='required',
     'password' => 'required'
  ]);
  return 'Hello from our controller';
  }
}

Link to tutorial
I removed the variable and it works.
I created a new laravel 11 app running on php 8.3.7 and i want to exclude some paths from csrf validation
after carefully reading the documentation https://laravel.com/docs/11.x/middleware#registering-middleware
i edited my app.php inside the bootstrap folder like this
<?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) {
        $middleware->append([
            App\Http\Middleware\VerifyInstallation::class,
            Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
            App\Http\Middleware\TrimStrings::class,
            Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
            App\Http\Middleware\TrustProxies::class
        ]);

        $middleware->web(append: [
            App\Http\Middleware\SelectLanguage::class,
            App\Http\Middleware\CorsMiddleware::class,
            App\Http\Middleware\GameCdnMiddleware::class
        ]);

        $middleware->web(replace: [
            Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class =>App\Http\Middleware\CustomVerifyCsrfToken::class,
        ]);

        $middleware->api(append: [
            App\Http\Middleware\UseApiGuard::class,
            'throttle:60,1',
            'bindings'
        ]);


    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

and my custom middleware
<?php
    namespace App\Http\Middleware {
        class CustomVerifyCsrfToken extends \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken
        {
            protected $except = [
                '/profile/contact'
            ];
        }
    
    }

in debugger i noticed that the $except array is empty and my request returns 419,
i tried all the variations according to the documentation but non works, the middleware is invoked even if i dont specify it at all (by the way my route is specified in web.php)
GET|HEAD        blogs ..................................................................................... blog.index › Blog\BlogController@index  
  POST            blogs ..................................................................................... blog.store › Blog\BlogController@store  
  GET|HEAD        blogs/create ............................................................................ blog.create › Blog\BlogController@create  
  GET|HEAD        blogs/{} .................................................................................... blog.show › Blog\BlogController@show  
  PUT|PATCH       blogs/{} ................................................................................ blog.update › Blog\BlogController@update  
  DELETE          blogs/{} .............................................................................. blog.destroy › Blog\BlogController@destroy  
  GET|HEAD        blogs/{}/edit ............................................................................... blog.edit › Blog\BlogController@edit  

Hello, I am trying to make an blog feature in my site. And I have created an migration table without soft delete feature. and then i have created A model and then i have created a controller using php artisan make:controller Blog/BlogController --model=Blog --resource.
// __________Route for blogs
Route::prefix('blogs')->name('blog.')->group(function () {
    Route::resource('', BlogController::class);
});

That's how i called the route. Everything was working well. The index, create, store method. But as you can see there is parameter passing inside the store route. and giving me 404 error if I call the route also. Please help if anybody knows about the problem.
I have tried to invoke the show method from controller via resource route like <a href="{{ route('blog.show', $blog) }}" class="btn btn-secondary">Read More</a>. but rising 404
PHP: 8.2
Laravel Framework: 11
MySQL
We have roughly the following code on our website to represent the overall problem.
Post.php
class Post extends BaseModel
{
    public function blocks(): MorphMany
    {
        return $this->morphMany(Block::class, 'blockable');
    }
}

Block.php
class Block extends Model
{
    public function blockable(): MorphTo
    {
        return $this->morphTo();
    }

    public function alt(): string
    {
        $alt = '';

        if ($this->caption) {
            $alt = $this->caption;
        } else if ($this->blockable->title) {
            $alt = 'Block from ' . $this->blockable->title;
        }

        return $alt;
    }
}

PostController.php
$posts = Post::where('status_id', 1)
    ->with('blocks')
    ->get();

This code works correctly and returns the expected result. But by calling $this->blockable within the alt function, it produces extra (duplicate) MySQL queries to find the parent, even though it is already queried and present. Is there a way to let Laravel know that blockable has already been queried as the parent?
One quick solution we found was the following, but we feel there is a more eloquent way of achieving this.
public function alt(Post $blockable): string
{
    $alt = '';

    if ($this->caption) {
        $alt = $this->caption;
    } else if ($blockable->title) {
        $alt = 'Block from ' . $blockable->title;
    }

    return $alt;
}
We are recently migrating old data to our new database. We are first exporting all the tables from the old database and importing it to our local database. Then after customizing some fields we are re-exporting them and importing the tables and contents to our new database.
However, after importing even though there are all the tables, (jobs, failed_jobs, job_batches) present in the database, laravel throws error when running jobs. It says, Base table or view 'new_db.jobs" doesn't exist.
We cannot find any solution for this.