I'm currently working on a project using Laravel Filament v3, and I want to implement a feature where a sound plays when a database notification is received. I've successfully set up database notifications using Filament's built-in features, but I'm unsure about how to trigger a sound when a notification is received.
I've searched for solutions online but haven't found a clear, up-to-date guide specifically for Laravel Filament v3. Could someone provide guidance on how to achieve this sound notification feature in Laravel Filament v3?
Here's what I've done so far:
I've set up database notifications for my application.
I have a notification system that works with the Laravel notification system, and I can send notifications to users.
What I'm missing is the ability to play a sound when a notification is received. I'd like to know how to integrate this audio notification feature into my Laravel Filament v3 project.
Any code examples or step-by-step instructions would be greatly appreciated. Thanks in advance for your help!


I'm facing problem in fetching data from controller to blade.php file they give an error of undefined variable $plans.
DalyTaskPlanController.php
public function dailyTaskPlan()
    {
        $plans = $this->plans = DailyTaskPlan::select(
        'projects.project_name',
        'daily_task_plans.*',
        'tasks.heading',
        'users.id')
            ->leftJoin('projects', 'daily_task_plans.project_id', '=', 'projects.id')
            ->leftJoin('tasks', 'daily_task_plans.task_id', '=', 'tasks.id')
            ->join('users','daily_task_plans.user_id', '=','users.id')
            ->take(4)
            ->get();
        return view('dailytaskplan::dashboard', compact('plans'));
}

in view file they give an error undefined variable
  @foreach ($plans as $plan)

              {{ $plan->project_name }}
              {{ $plan->heading }}
              {{ $plan->date }}
              {{ $plan->estimate_hours }} hrs {{ $plan->estimate_minutes }} mins
              {{ $plan->memo }}

  @endforeach

Additional question; how can I merge Laravel module route with project route because when I use module route they override project route?
i tried to make traits folder and give another route for module in other route they working fine. but in main route it's not working.


I'm a beginner with Laravel and inertia.
I use Laravel 10 with Inertia and react.
When I go to the index page, the field "$this->typeEducation->title" is filled, but when I click edit, the field is empty. I then get the error message: "Attempt to read property "title" on null"
The model:
class Education extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'education_type_id',
        'is_active',
        'start_date',
        'end_date',
    ];

    public function typeEducation() {
        return $this->belongsTo(EducationType::class, 'education_type_id', 'id');
    }
}

The resource:
class EducationResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'type' => $this->typeEducation->title,
            'isActive' => $this->is_active,
            'startDate' => $this->start_date,
            'endDate' => $this->end_date,
            'educationTypes' => EducationTypeResource::collection($this->whenLoaded('educationTypes'))
        ];
    }
}

The Controller
class EducationController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): Response
    {
        return Inertia::render('School/Education/EducationIndex', [
            'education' => EducationResource::collection(Education::all())
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Education $education): Response
    {
        $education->load(['typeEducation']);
        return Inertia::render('School/Education/Edit', [
            'education' => new EducationResource($education),
            'educationTypes' => EducationTypeResource::collection(EducationType::all())
        ]);
    }
}

What am I doing wrong?


I am building a laravel project with filament.
Everything worked normally, but after working on translations in Laravel, the Fillament translations stopped working.
Has anyone ever experienced this?
I published fillament and laravel translation files already. Also published fillament views but could not find/replace the labels to test.
Maybe I need to override Laravel translations to Filament translations? Is that even possible to do and not break the project?
I will insert the before and after images.


I already have this app/Http/Middleware/Authenticate.php
<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request): ?string
    {
        return $request->expectsJson() ? null : route('home');
    }
}

The problem is that sometime Laravel in case user is not authenticated is traveling trought this:
vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler .php: 570
 protected function unauthenticated($request, AuthenticationException $exception)

    {

        return $this->shouldReturnJson($request, $exception)

                    ? response()->json(['message' => $exception->getMessage()], 401)

                    : redirect()->guest($exception->redirectTo() ?? route('login'));

    }

Where can I override this!?! I have no 'login' named route ! I need to return to route named 'home'.


I have been working on rest api and now I am working on some tests, but since I want to use slug on my model as primary key (usual setup with getKeyName) I have strange behaviour. For example for this create method:
$modelInstance = Model::create([
    'title' => 'Old Title',
    'slug' => Str::slug('Old Title'),
    'description' => 'Old description',
    'rating' => 4.2,
]);

I get these results when dump test:
#original: array:6 [
  "title" => "Old Title"
  "slug" => 9
  "description" => "Old description"
  "rating" => 4.2
  "updated_at" => "2023-11-17 08:45:08"
  "created_at" => "2023-11-17 08:45:08"
]
#changes: []
#casts: []
#classCastCache: []
#attributeCastCache: []

Then when I comment this:
public function getKeyName(): string
{
    return 'slug';
}

part in my model and run the same test I get this:
#original: array:7 [
  "title" => "Old Title"
  "slug" => "old-title"
  "description" => "Old description"
  "rating" => 4.2
  "updated_at" => "2023-11-17 08:47:31"
  "created_at" => "2023-11-17 08:47:31"
  "id" => 9
]
#changes: []

I haven't worked much with Laravel 10 lately, but is there something I am missing and I should be aware of?


Using Laravel's Lumen 9.1.6
I am following the documentation but still have a problem with an optional trailing route parameter defined like this:
routes/web.php
$router->group(['prefix' => 'question'], function() use($router) {
    $router->get('log/{eid}/{uid}[/{year}]', ['middleware' => 'api.auth', 'uses' => 'QuestionController@getLogs']);
});

and then in QuestionController.php
public function getLogs($eid, $uid, $year = null, Request $request) {
  ....
}

If I then call
api.tld/question/log/1/2/2021 - it works fine, however
api.tld/question/log/1/2 - throws Unable to resolve dependency [Parameter #2 [  $year ]] in class App\Http\Controllers\QuestionController
Lumen docs are very sparse on this (although I believe I've followed the syntax correctly). Any ideas?


I have an items json array column in a Catalog eloquent model that contains itemable_type and itemable_id properties, it looks like this [{"itemable_id": 1, "qty": 1, "itemable_type":"\\App\\Models\\Food"}], can I use this information to manually initialize a One To Many Polymorphic relationships?
Basically my database looks like this:

ID
items
...

Int
Json (Eg. [{"itemable_id": 1, "qty": 1, "itemable_type":"\App\Models\Food"}])
...

I am able a make a regular Eloquent Collection with something like this:

class VendorCatalog extends Model
{
   public function catalogable(): \Illuminate\Database\Eloquent\Builder
   {
       $items = \Illuminate\Database\Eloquent\Collection::make();

       $models = $this->items
           ->filter(fn ($i) => !empty($i['type']))
           ->filter(fn ($i) => class_exists(str("\\App\\Models\\")->append($i['type'])->toString()))
           ->groupBy('type')->map(function ($items, $group) {
              $class = str("\\App\\Models\\")->append($group)->toString();
              return $class::whereIn('id', $items->pluck('id'))->get();
           });

       return $items->merge($models->flatten())->toQuery();
   }
}

This works, but considering that the relationship might contain unrelated models, a One To Many Polymorphic relationship would be better suited.
So it possible or should I go ahead and just add every item as a distinct record instead of storing IDs and types?
I know this is a complex requirement, but hey! Who doesn't want a little challenge? Also, this will make my database structure a little less cluttered and more manageable.
EDIT
Also, I realised that if I call the getQuery() method on the catalogable I get this error Unable to create query for collection with mixed types
$catalogable = VendorCatalog::first()->catalogable()->getQuery();


This is the Model where I insert, am I doing it correctly?
public static function insertPlotDetails($data){
    $PlotDetails = array();
        $PlotDetails['L_Name'] = $data['Plot'];
        $PlotDetails['L_Owner'] = $data['Owner'];
        $PlotDetails['L_Spice'] = $data['Spice'];
        $PlotDetails['L_AreaAcre'] = $data['Area'];
        $PlotDetails['L_AreaHa'] = 0;
        $PlotDetails['L_ProducedAmt_Kg'] = $data['PdAmount'];
        $PlotDetails['L_District'] = $data['District'];
        $PlotDetails['L_Block'] = $data['Block'];
        $PlotDetails['L_Village'] = $data['Village'];
        $PlotDetails['lat'] = $data['Latitude'];
        $PlotDetails['lng'] = $data['Longitude'];
        $PlotDetails['img'] = $data['ImageUpload'];
        $PlotDetails['PdArea_JSON'] = json_encode(["'TotalProduction': {'PlotName': '".$data['Plot']."','Area':[{'Name': 'Main','Variant':[{'IISR_Varada': ''".$data['IISR_Varada']."'','IISR_Mahima': '".$data['IISR_Mahima']."','Nadia_Nagaland': '".$data['Nadia_Nagaland']."','Nadia_Odisha': '".$data['Nadia_Odisha']."','Karbi': '".$data['Karbi']."','Local': '".$data['Local']."' } ] },{'Name': 'Trial','Variant': [ {'IISR_Varada': '".$data['T_IISR_Varada']."','IISR_Mahima': '".$data['T_IISR_Mahima']."','Nadia_Nagaland': '".$data['T_Nadia_Nagaland']."','Nadia_Odisha': '".$data['T_Nadia_Odisha']."','Karbi': '".$data['T_Karbi']."','Local': '".$data['T_Local']."' } ] } ]} }"]);

        try {

            $PlotDetails_response =  DB::table('locationdb')->insert($PlotDetails);

          } catch (\Exception $e) {

              return $e->getMessage();
          }
    //

    return $PlotDetails_response;

}

This is how I get The Data and try to access the JSON.
public function GetJsonTest()
{
    $data= MapModel::GetJsonTest();

   $json = $data[0]->PdArea_JSON;
   $array = json_decode($json, true);
   dd($json->TotalProduction->);

}

My Intention was to be able to read the index of like 'Name' and 'Variety'. It is outputting as string and I cannot find a way to convert it back to array or Object so that I can read and display.
["'TotalProduction': {'PlotName': 'TestJson','Area':[{'Name': 'Main','Variant':[{'IISR_Varada': ''10'','IISR_Mahima': '12','Nadia_Nagaland': '13','Nadia_Odisha': '14','Karbi': '15','Local': '16' } ] },{'Name': 'Trial','Variant': [ {'IISR_Varada': '11','IISR_Mahima': '12','Nadia_Nagaland': '13','Nadia_Odisha': '14','Karbi': '15','Local': '16' } ] } ]} }"]


I'm using Laravel 10, this code is in my web.php file
...
Route::resource('photos', PhotoController::class);
....

and it produce this list of routes:
photos ............................ photos.index › Admin\PhotoController@index
photos ............................ photos.store › Admin\PhotoController@store
photos/create ..................... photos.create › Admin\PhotoController@create
photos/{photo} .................... photos.show › Admin\PhotoController@show
photos/{photo} .................... photos.update › Admin\PhotoController@update
photos/{photo} .................... photos.destroy › Admin\PhotoController@destroy
photos/{photo}/edit ............... photos.edit › Admin\PhotoController@edit

it all works fine. Now, I want to protect with authentication all this page, and i use this code
Route::prefix('admin')->middleware('auth')->group(function () {
   Route::get('photos', PhotoController::class);
});

I got this error:
  Target class [PhotoController] does not exist.

so i add:      ->namespace('App\Http\Controllers\Admin')
Route::prefix('admin')->namespace('App\Http\Controllers\Admin')->middleware('auth')->group(function () {
   Route::resource('photos', PhotoController::class);
});

now the site works, but the command php artisan route:list says:
 Class "PhotoController" does not exist

I have to specify:
use App\Http\Controllers\Admin\PhotoController;

The question is.. which is the correct way? use namespace or indicate it with ->namespace()?


Using Laravel 10 and VS Code this line was considered error:
Auth::routes();

VS Code says:
Undefined type 'Auth'.intelephense(P1009)

But no problem in the webapp.
I've already tried to do:
CTRL + SHIFT + P --> digit "Index workspace" --> Enter

but it doesnt work


I am using Laravel 10 with Livewire v3. I have a method that accepts array as one of the parameter. If the parameter is just an array then the method will behave differently, if the parameter is associative array then the method will use the keys and values both and behave differently. The passed associative array can have sequential keys as shown in the code below.
Below is the extracted logic and I don't want it to detect $associative_sequential array as a sequential array. What do I need to add/change for that to happen because I don't want $sequential array to be identified as associative array either.
public function doSomething($passedArray) {
    if (is_array($passedArray)) {
        if ($passedArray == array_values($passedArray)) {
            echo "The passed array is a sequential array.\n";
        } elseif (array_keys($passedArray) == array_filter(array_keys($passedArray), 'is_int')) {
            echo "The passed array is an associative array with integer keys.\n";
        } else {
            echo "The passed array is an associative array with non-integer keys.\n";
        }
    } else {
        echo "The passed variable is not an array.\n";
    }
}

$sequential = array("apple", "banana", "cherry");
$associative_sequential = array(0 => "apple", 1 => "banana", 2 => "cherry");
$associative_non_sequential = array(10 => "apple", 20 => "banana", 25 => "cherry");
$strict_associative = array("fruit1" => "apple", "fruit2" => "banana", "fruit3" => "cherry");

doSomething($sequential);
doSomething($associative_sequential);
doSomething($associative_non_sequential);
doSomething($strict_associative);

Outputs:
// This is what I am getting
The passed array is a sequential array.
The passed array is a sequential array.
The passed array is an associative array with integer keys.
The passed array is an associative array with non-integer keys.

// This is what I want to happen
The passed array is a sequential array.
The passed array is an associative array with integer keys.
The passed array is an associative array with integer keys.
The passed array is an associative array with non-integer keys.


In a Laravel unit test we are testing and mocking ReCaptcha\ReCaptcha (and NZTim\Mailchimp\Mailchimp). The working test code is as follows:
$this->mock(\ReCaptcha\ReCaptcha::class, function ($mock) use ($mock_response) {
            $mock->shouldReceive('make')
                ->once()
                ->andReturn($mock);
            $mock->shouldReceive('verify')
                ->once()
                ->andReturn($mock_response);
        });

In the controller, we have:
$recaptcha = app(ReCaptcha::class)->make();

To get this to work, as the ReCaptcha class requires a constructor variable, we created the following factory:
// ReCaptchaFactory.php

public function make()
{
     $secret = config('services.recaptcha.secret');
     return new ReCaptcha($secret);
}

Without the required constructor variable, we can accomplish this with 1 line and remove the extra factory and AppServiceProvider updates:
$recaptcha = app(ReCaptcha::class);

Something like the following?
$recaptcha = resolve(ReCaptcha::class, ['param1'=>config('services.recaptcha.secret'));

It just feels like we have a lot of extra unnecessary code.


When I try to access an endpoint in my Laravel API, Jetstream redirects to the dashboard page. I am already logged in, and when I go to my endpoint from the dashboard, it goes back to the dashboard. I made my application without Jetstream, then I made a new project and copied my code to it (controllers, models, policies, etc.) I am using Laravel 10 and Jetstream 4. Here is my web.php:
Route::get('/', function () {
    return view('welcome');
});

Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified',
])->group(function () {
    Route::get('/dashboard', function () {
        return view('dashboard');
    })->name('dashboard');

});

api.php (I am trying to get to the assets route)
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::group(['namespace' => '\App\Http\Controllers\Api', 'middleware' => 'auth:sanctum', config('jetstream.auth_session'),
'verified',], function() {
    Route::apiResource('users', UserController::class)->names('users');
    Route::apiResource('assets', AssetController::class)->names('assets');
    Route::apiResource('events', EventController::class)->names('events');

    Route::post('assets/bulk', ['uses' => 'App\Http\Controllers\Api\AssetController@bulkStore']);
});

I added the config('jetstream.auth_session') part because it's used in web.php. It didn't seem to make any difference.
Here is part of the page with the link that I tried to click on (resources/views/navigation-menu.blade.php)

                    <x-nav-link href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
                        {{ __('Dashboard') }}
                    </x-nav-link>

                    <x-nav-link href="{{ route('assets') }}" :active="request()->routeIs('assets')">
                        {{ __('Assets') }}
                    </x-nav-link>

I don't know what other files are relevant to this issue. I don't have much experience with Laravel, and this is my first time using Jetstream. I read an article about how to redirect to a different route, but I don't want to do that. How do I make it go to my API endpoint without redirecting?
I tried clicking on the "Assets" link in the navigation menu at the dashboard route. I was expecting it to show a blank page, but it just redirected back to the dashboard. I also tried php artisan route:clear and doing Empty Cache and Hard Reload in Chrome, but I got the same result. Here is what the network tab of my developer tools looks like:
There's a 302 response on assets and login.The one on login comes from the assets endpoint. THere's a 200 on dashboard coming from login.


I'm trying to run Laravel but I get this error "Target class [set_locale] does not exist.". This problem appeared when transferring from Laravel 7 to 10. What could this be related to? What files need to be provided to make it clear what the problem is?
routes web.php
use App\Http\Controllers;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Auth::routes([
    'reset' => false,
    'confirm' => false,
    'verify' => false,
]);

Route::get('locale/{locale}', 'MainController@changeLocale')->name('locale');
Route::get('currency/{currencyCode}', 'MainController@changeCurrency')->name('currency');
Route::get('/logout', 'Auth\LoginController@logout')->name('get-logout');

Route::middleware(['set_locale'])->group(function () {
    Route::get('reset', 'ResetController@reset')->name('reset');

    Route::middleware(['auth'])->group(function () {
        Route::group([
            'prefix' => 'person',
            'namespace' => 'Person',
            'as' => 'person.',
        ], function () {
            Route::get('/orders', 'OrderController@index')->name('orders.index');
            Route::get('/orders/{order}', 'OrderController@show')->name('orders.show');
        });

        Route::group([
            'namespace' => 'Admin',
            'prefix' => 'admin',
        ], function () {
            Route::group(['middleware' => 'is_admin'], function () {
                Route::get('/orders', 'OrderController@index')->name('home');
                Route::get('/orders/{order}', 'OrderController@show')->name('orders.show');
            });

            Route::resource('categories', 'CategoryController');
            Route::resource('products', 'ProductController');
            Route::resource('products/{product}/skus', 'SkuController');
            Route::resource('properties', 'PropertyController');
            Route::resource('merchants', 'MerchantController');
            Route::get('merchant/{merchant}/update_token', 'MerchantController@updateToken')->name('merchants.update_token');
            Route::resource('coupons', 'CouponController');
            Route::resource('properties/{property}/property-options', 'PropertyOptionController');
        });
    });

    Route::get('/', 'MainController@index')->name('index');
    Route::get('/categories', 'MainController@categories')->name('categories');
    Route::post('subscription/{skus}', 'MainController@subscribe')->name('subscription');

    Route::group(['prefix' => 'basket'], function () {
        Route::post('/add/{skus}', 'BasketController@basketAdd')->name('basket-add');

        Route::group([
            'middleware' => 'basket_not_empty',
        ], function () {
            Route::get('/', 'BasketController@basket')->name('basket');
            Route::get('/place', 'BasketController@basketPlace')->name('basket-place');
            Route::post('/remove/{skus}', 'BasketController@basketRemove')->name('basket-remove');
            Route::post('/place', 'BasketController@basketConfirm')->name('basket-confirm');
            Route::post('coupon', 'BasketController@setCoupon')->name('set-coupon');
        });
    });

    Route::get('/{category}', 'MainController@category')->name('category');
    Route::get('/{category}/{product}/{skus}', 'MainController@sku')->name('sku');
});

kernel.php
namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'is_admin' => \App\Http\Middleware\CheckIsAdmin::class,
        'basket_not_empty' => \App\Http\Middleware\BasketIsNotEmpty::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'set_locale' => \App\Http\Middleware\SetLocale::class,
    ];

    /**
     * The priority-sorted list of middleware.
     *
     * This forces non-global middleware to always be in the given order.
     *
     * @var array
     */
    protected $middlewarePriority = [
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authorize::class,
    ];
}

Controllers > middleware SetLocal.php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $locale = session('locale');
        App::setLocale($locale);
        return $next($request);
    }
}


hello I'm new for livewire 3 I have table inside form, data table having  radio button for yes or no
after selecting yes or no I'm going to submit that form that time I want to store fetch detail like id and name along this. now I'm any getting radio button value, me to solve
form page

my code form

    <form wire:submit.prevent="Save" autocomplete="off">

                SL
                ID No
                NAME
                YES
                NO

 @foreach ($UserDetail as $key=>$UserDetails)
 @php $ID = 0+$key @endphp

                {{ $key + 1  }}

                {{ $UserDetails->id }}

                {{ $UserDetails->name }}

                  <input type="radio" wire:model="TableInput.{{$ID}}.data" class="custom-control-input" name="TableInputs[{{$ID}}]" id="sv2-preference-fedev{{$ID}}" value="YES" required>

<input type="radio" wire:model="TableInput.{{$ID}}.data" class="custom-control-input" name="TableInputs[{{$ID}}]" id="sv2-preference-uxdis{{$ID}}" value="NO" required>

      @endforeach

        <button type="submit" class="btn btn-md btn-primary">SAVE  </button>

    </form>

Controller
class StudentAttendance extends Component
{
public $name;
public $id;
public $TableInput = [];

public function mount()
{
  $this->User       = User::all();
}

public function Save()
{
    $bel = Data::create([

        'Id'                     => $value['Id'],
        'name'                   => $value['name'],
        'data'                   => $value['data'],
    ]);
}
}

}


I am trying to set up localization on my Laravel Inerita (Vue.js). I know about https://github.com/mcamara/laravel-localization, but this does not support Inertia (at least I was not successful with running this on my Vue.js file) {{ __("text") }} does not work in inertia error: TypeError: _ctx.__ is not a function.
Anyway, I am using a different localization package called laravel-vue-i18n.
I am successful in using this on Vue.js, but I am having problems when setting the locale based on URL. How do I set my routes/middleware to use a nullable locale (en as default)?
File web.php
// Can be nullable locale?
Route::middleware(['setLocale'])->prefix('{locale?}')->group(function () {
  Route::resource('posts', PostController::class);
  Route::resource('comments', CommentController::class);

});

File SetLocaleMiddleware.php
class SetLocaleMiddleware
{
    public function handle($request, Closure $next, $locale = 'en')
    {
        \Log::info($locale); // Always logs as 'en' even if I add 'ja' in the URL
        \Log::info($request->route('locale')); // Locale or whatever is the text after localhost/ for some reason

        if (!in_array($locale, ['en', 'ja'])) {
            abort(400);
        }

        App::setLocale($locale);

        return $next($request);
    }
}

File app/Kernel.php
protected $middlewareAliases = [
    'setLocale' => \App\Http\Middleware\SetLocaleMiddleware::class,
];

Expected results:
// Set application language to Japanese
http://localhost/ja
http://localhost/ja/posts
http://localhost/ja/comments

// Set application language to English as default
http://localhost
http://localhost/posts
http://localhost/comments

Note: it does not have to be middleware.


I am having a issue hitting an endpoint in my API and getting the correct JSON response in a firefox.
I am attempting to hit https://...locationtypes/1 and getting this JSON response:
{
    "data": {
        "id": null,
        "name": null
    }
}

Here is a response from hitting https://...locationtypes:
{
    "data": [
        {
            "id": 1,
            "name": "Event"
        },
        {
            "id": 2,
            "name": "Vendor"
        },
        {
            "id": 3,
            "name": "Utility"
        }
}

LocationType.php:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class LocationType extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $fillable = [
        'name'
    ];

    public function locations() {
        return $this->hasMany(Location::class);
    }

public function resolveRouteBinding($value, $field = null)
    {
        return $this->where('id', $value)->firstOrFail();
    }
}

LocationTypeController.php (show and store method):
public function store(StoreLocationTypeRequest $request)
    {
        return new LocationTypeResource(LocationType::create($request->all()));
    }

public function show(LocationType $locationType)
    {
        $includeLocations = request()->query('includeLocations');

        if ($includeLocations) {
            return new LocationTypeResource($locationType->loadMissing('locations'));
        }
        return new LocationTypeResource($locationType);
    }

LocationTypeResource.php:
class LocationTypeResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'locations' => LocationResource::collection($this->whenLoaded('locations'))
        ];
    }
}

api.php:
Route::group(['prefix' => 'v1'], function () {
    // CRUD
    Route::apiResource('events', EventController::class);
    Route::apiResource('info', InfoController::class);
    Route::apiResource('locations', LocationController::class);
    //Route::apiResource('locationtypes', LocationTypeController::class);
    Route::get('locationtypes', [LocationTypeController::class, 'index']);
    Route::get('locationtypes/{id}', [LocationTypeController::class, 'show']);

    // Bulk POST
    Route::post('events/bulk', ['uses'=>'EventController@bulkStore']);
    Route::post('info/bulk', ['uses'=>'InfoController@bulkStore']);
    Route::post('locations/bulk', ['uses'=>'LocationController@bulkStore']);
    Route::post('locationtypes/bulk', ['uses'=>'LocationTypeController@bulkStore']);

});

I apologize if I have forgotten something, I am new to Laravel still. Also, this is Laravel 10. To clarify the problem, I cannot figure out why the id endpoint is spewing null back at me.
EDIT: I was able to use Route::get(locationtypes/{locationType}) to obtain the desired output by using the 'name' field but I am still unable to use the 'id' field and get null as output. I edited the above code to display my changes.


I'm trying to get groupBy value and it giving successfully, after this I'm need only group list array
how to archive that.
my Code
$this->StudentList = Student::get();
$data =  $this->StudentList->sortBy('date', SORT_NATURAL)->groupby('date');

($data);

GroupBy Result
array:14 [▼
  "2024-01-01" => Illuminate\Database\Eloquent\Collection {#1977 ▶}
  "2024-01-02" => Illuminate\Database\Eloquent\Collection {#1978 ▶}
  "2024-01-03" => Illuminate\Database\Eloquent\Collection {#1979 ▶}
  "2024-01-04" => Illuminate\Database\Eloquent\Collection {#1980 ▶}
  "2024-01-05" => Illuminate\Database\Eloquent\Collection {#1981 ▶}
]

need this group date like this in array
array:14 [▼
  "2024-01-01"
  "2024-01-02"
  "2024-01-03"
  "2024-01-04"
  "2024-01-05"
]

laravel get groupBy name list


I have following models in Laravel:

User Model
Team Model
Company Model

And DB tables:
users
- id

company
- id

teams
- id
- company_id  (team can only belong to one company)

// pivot tables
company_user
- user_id
- company_id

team_user
- team_id
- user_id

I'm trying to create relationship on User Model that will get Company With teams that only belongs to that user. I can make it with joins, but I would like to have a relationship. I have tried different packages, but still can't figure it out. It's just sad 8 hours.


I have two models, List and Item, with a many-to-many relationship. Since I don’t care about getting the lists an item is in (just the items in the list), my models only define half the relationship.
class App\Models\List extends Model
{
    protected function items(): Illuminate\Database\Eloquent\Relations\BelongsToMany
    { /*...*/ }
}

Then I have a route, Route::post('/list/{item}', [ListController::class, 'item']) to which a form submits an item and some other data. The controller is responsible for retrieving the correct List model and storing the relationship & details.
class App\Http\Controllers\ListController extends Controller
{
    public function item($request, App\Models\Item $item)
    {
        /* request validation */

        $list = self::current();

        $list->items()->detach($item->id);
        $list->items()->attach($item->id, [/* other data */]);

        $list->save();

        return back();
    }

    static function current(): App\Models\List
    { /*...*/ }
}

But whenever I post to the route, I get an error saying the static items() method is not defined:

Call to undefined method App\Models\List::items()

Checks

Dumping the result of ListController::current() shows an instance of App\Models\List. This instance does have data from the database (where available).

I have verified that BelongsToMany is the correct relationship type to return.

I can return Item instances from a List instance without accessing the pivot table directly, meaning my table schema matches my model definitions.

I have verified that the request and route are passing data into the controller as expected.

I started with ->syncWithoutDetaching(), but it returns the same error. I switched to ->attach() and ->detach() for simplicity.


When using contextual information if logging in Laravel v10 (https://laravel.com/docs/10.x/logging#contextual-information), the contextual information doesn't get merged when specifying the channel name.
e.g.: This works fine:
Log::info(
   'User {user} created Thing {id}',
   [
      'user' => auth()->user()->id,
      'id' => $thing->id
   ]
);

...produces:
[2024-01-31 08:44:23] local.INFO: User 1 created Thing 3 {"user":1,"id":3}

However, this doesn't work:
Log::channel('mychannel')->info(
   'User {user} created Thing {id}',
   [
      'user' => auth()->user()->id,
      'id' => $thing->id
   ]
);

...as it produces:
[2024-01-31 08:36:15] local.INFO: User {user} created Thing {id} {"user":1,"id":2}

Any idea what I'm doing wrong?


I am using PHPStan within a Laravel 10 app and have set this to quite a high level (good practice I guess) - I have run into a few errors and i'm trying to figure out the best way to resolve them.
 ------ ------------------------------------------------------------------------------------------
  Line   app/Actions/Reports/SetReportStatusAction.php
 ------ ------------------------------------------------------------------------------------------
  17     Property App\Models\Report::$succeeded_at (Carbon\Carbon|null) does not accept int|null.

<?php

declare(strict_types=1);

namespace App\Actions\Reports;

use App\Models\Report;
use Stripe\Reporting\ReportRun;

class SetReportStatusAction
{
    public function __invoke(Report $report): void
    {
        /** @var ReportRun $stripeObject */
        $stripeObject = $report->getStripeObject();
        $report->status = $stripeObject->status;
        $report->succeeded_at = $stripeObject->succeeded_at ?? null;
    }
}

Report.php
<?php

namespace App\Models;

// use statements hidden from view

class Report extends Model implements Transitionable
{
    use HasFactory, HasStates, HasStripeObject;

    protected $fillable = [
        'stripe_id',
        'report_type',
        'status',
        'parameters',
        'expires_at',
        'succeeded_at',
    ];

    protected $casts = [
        'parameters' => 'json',
        'expires_at' => 'datetime',
        'succeeded_at' => 'datetime',
    ];
}

The data succeeded_at comes from a webhook event and will be in the format similar to this - a timestamp
"succeeded_at": 1706786551

Expected outcome -
PHPStan to detect no errors with the two files in question
Actual outcome -
Recieve a phpstan error 'Property App\Models\Report::$succeeded_at (Carbon\Carbon|null) does not accept int|null.'


I have this function in a controller in laravel 10
public function change($id)
{

    DB::beginTransaction();
    try{
        $current_period=Period::where('current',true)->first();
        $current_period->current=false;
        $current_period->save();
        $new_period=Period::findOrFail($id);
        $new_period->current=true;
        $new_period->save();

        //set person's memberSince and pay_mode to what is in the person_period pivot table
        $persons=Person::all();
        $persons->each(function ($person,$key){
            global $new_period;
            //dd($new_period->id);
            $pivot=$person->periods()->where('period_id',$new_period->id)->first();
            $person->memberSince=$pivot? $pivot['memberSince']:null;
            $person->pay_mode=$pivot?$pivot['pay_mode']:null;
            $$person->save();
        });
        DB::commit();
        $result=[];
        $ps=PersonResource::collection(Person::all());
        array_push($result, $ps);
        $pr=PeriodResource::collection(all());
        array_push($result,$pr);
        return $result;

    }catch (\Exception $e) {
        DB::rollBack();
        throw $e;
    }
}

it returns an error

message   'Attempt to read property "id" on null'

on the line just behind the presently commented line
//dd($new_period->id)

when I uncomment the line it returns the same error.
When I place the uncommented line outside the each loop, it returns the correct id of $new_period confirming that outside the each loop the $new_period exists.
What am I missing here?


I'm building an admin section for a Laravel 10 app using the boilerplate Breeze routes and templates (for now) and I have a group of prefixed routes that I want to return a 404 error for in the following cases:

there is NO signed in user
if there IS a signed in user, they are not an admin

In other words, the ONLY time the prefixed routes should produce anything substantial is if the authenticated user is an admin. Otherwise, I want it to appear as the routes don't even exist.
I am at my wits end trying to return the 404 error view and status code from the middleware. I have been tinkering with the code and reading documentation for HOURS now to no avail, and yet I get the feeling the answer is right in front of me but I'm missing something.
This is code I have in the web.php routes file:
Route::prefix('admin')->middleware(['admin'])->group(function() {
    Route::get('/', [AdminDashboardController::class, 'index'])->name('admin');
});

And here's what I have in the handle() function for the admin middleware:
public function handle(Request $request, Closure $next): Response
{
    if ($request->user() === null || $request->user()->role !== 'admin') {
        return response('This page cannot be found', 404, []);
    }

    return $next($request);
}

This code works just fine. BUT, I want to return the 404 page and HTTP 404 status code rather than a plain text page with the response message. If I try to return anything EXCEPT the above it just seems to skip right on to the next bit of middleware. As in, it attempts to render the Breeze dashboard component as if the user was signed in, even though the user isn't signed in.
Could anybody please guide me on how I can return the 404 error page and status code in place of the current response above?


My application has Users and Groups. They are related with a pivot table. The pivot table has nullable "joined" and "left" datetimes.
How do I use Logical Grouping on a pivot table?
I've tried:
$this->belongsToMany(User::class)->wherePivot(function ($query) use ($time) {
    $query->where('joined', null)->orWhere('joined', '<=', $time);
})
// and "left"
;

and
$this->belongsToMany(User::class)->where(function ($query) use ($time) {
    $query->wherePivot('joined', null)->orWherePivot('joined', '<=', $time);
})
// and "left"
;

but neither work. The first complains about passing a function as an argument that's expected to be a string, and the second complains about wherePivot not being defined.
Am I missing something obvious?


I have the following Models and relationships.
App\Subscriber.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Grosv\LaravelPasswordlessLogin\Traits\PasswordlessLogin;

class Subscriber extends Authenticatable
{
    use Notifiable, PasswordlessLogin;

    public function customFieldValues()
    {
        return $this->morphMany(CustomFieldValue::class, 'customFieldValueable');
    }
}

App\CustomField.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Campaign;

class CustomField extends Model
{
    protected $fillable = [
        'name',
        'key',
        'type',
        'field_options'
    ];

    public function customFieldValues()
    {
        return $this->hasMany(CustomFieldValue::class);
    }
}

App\CustomFieldValues.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CustomFieldValue extends Model
{
    use HasFactory;

    protected $fillable = ['custom_field_id', 'value', 'custom_field_valueable_id', 'custom_field_valueable_type'];

    public function customField()
    {
        return $this->belongsTo(CustomField::class);
    }

    public function customFieldValueable()
    {
        // If you are using custom column names, specify them here. Otherwise, ensure they match the migration.
        return $this->morphTo(null, 'custom_field_valueable_type', 'custom_field_valueable_id');
    }
}

App\Campaign.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\CustomField;

class Campaign extends Model
{
    protected $dates = [
        'imported_at'
    ];

    protected $casts = [
        'imported_at' => 'datetime',
        'exported_at' => 'datetime'
    ];

    protected $fillable = [
        'uuid',
        'name',
        'slug',
        'client_id'
    ];

    public function customFieldValues()
    {
        return $this->morphMany(CustomFieldValue::class, 'customFieldValueable');
    }
   }

App\Newsletter.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Newsletter extends Model
{

    protected $fillable = [
        'uuid',
        'name',
        'brand_id',
        'active',
        'create_send_list_id',
        'last_imported'
    ];

    public function brand()
    {
        return $this->belongsTo(Brand::class);
    }

    public function subscribers()
    {
        return $this
            ->belongsToMany(Subscriber::class)
            ->withPivot('active')
            ->withTimestamps();
    }

    public function customFieldValues()
    {
        return $this->morphMany(CustomFieldValue::class, 'customFieldValueable');
    }
}

My migration to create the table to support this looks like this,
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('custom_field_values', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('custom_field_id');
            $table->string('value');
            // Manually create the polymorphic columns
            $table->unsignedBigInteger('custom_field_valueable_id');
            $table->string('custom_field_valueable_type');
            // Manually specify a shorter index name
            $table->index(['custom_field_valueable_type', 'custom_field_valueable_id'], 'custom_field_valueable_index');
            $table->timestamps();

            $table->foreign('custom_field_id')->references('id')->on('custom_fields')->onDelete('cascade');
        });

    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('custom_field_values');
    }
};

However in the Nova interface when I try and view a subscriber I get the following error,

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'custom_field_values.customFieldValueable_type' in 'where clause' (Connection: mysql, SQL: select * from custom_field_values where custom_field_values.customFieldValueable_type = App\Models\Subscriber and custom_field_values.customFieldValueable_id = 1016 and custom_field_values.customFieldValueable_id is not null order by custom_field_values.id desc limit 6 offset 0)

If someone could explain to me where I have gone wrong that would great. I am very new to polymorphic relationships.


I'm using Laravel Nova 4 (Laravel 10.43.0, PHP 8.2.8).
When using soft deletion, I get the error Column not found: 1054 Unknown column '*.deleted_at', where * is the table of the entity for which I use it.
Full SQL request in the exception:
select * from `users` where `id` = 1 and `users`.`deleted_at` is null limit 1

If I execute this query in the SQL console in PhpStorm, it will say that there is no such column, but the query itself will execute and do it correctly. An example of an implementation with a user.

Migration:
// ...
Schema::create('users', function (Blueprint $table) {
    // ...
    $table->softDeletes();
    // ...
});

Model:
// ...
class User extends Authenticatable
{
    // ...
    use SoftDeletes;
    // ...
}


why I can't bind or display data from the database going to input text field. I already add the rules just like what other said but still not luck. Please help, I stack on this part.
By the way I am using modal from question table CRUD.
LIVEWIRE COMPONENT
class ViewPromo extends Component
{

    public $questions;
    public Promo $promo;
    public Question $question;

    protected $rules = [
        'question.question_title' => 'required',
        'question.question_type' => 'required',
    ];

    public function editQuestion(Question $question) {
        $this->question = $question;
    }

    public function mount(Promo $promo) {
        $this->promo = $promo;
        $this->questions = $this->promo->questions()->get();
    }

    public function render()
    {
        return view('livewire.admin.promos.view-promo')->extends('layouts.app')->section('contents');
    }
}

LIVEWIRE BLADE FILE

    <x-label for="question_title">Title</x-label>
    <x-input-text wire:model.defer="question.question_title" id="question_title"></x-input-text>

    <x-label for="question_type">Type</x-label>
    <x-select wire:model.defer="question.question_type" id="question_type">
        <option value="single_select" @if($question->question_type == 'single_select') selected @endif>Single select</option>
        <option value="multiple_select" @if($question->question_type == 'multiple_select') selected @endif>Multiple select</option>
    </x-select>

BUTTON FROM THE LIST
<x-button wire:click="editQuestion({{ $question->id }})" data-modal-target="edit-default-modal" data-modal-toggle="edit-default-modal" >Edit</x-button>

I want to display record from the database going to the input fields.


I've got a long-running Laravel app with a traditional form in a blade view. Inside of this form I want to start to include a couple Livewire components that can refresh and submit data independent of the form. Is this possible?
For testing purposes I've created this simple component and nested it within the existing <form> on the page..
<div>
    Time: {{ time() }}
    <button wire:click="$refresh">Refresh</button>
</div>

But, clicking the button doesn't refresh the component, and instead submits the form.


I have a Laravel store project that I am confused to develop my products database. My store products are clothes, shoes, pants, laptops, phones, headphones, etc.
Hello friends, good time
This database is for the products of my store:
database photo
But as long as I have products like shoes and clothes it works correctly and optimally because they have many options, for example these are the options for product_id=3 which is a dress in the product_options table:

option::1
option::2
option::3

color_id:8
color_id:8
color_id:9

size_id: 3
size_id:5
size_id:5

price: 25
price: 20
price: 20

stock: 5
stock: 9
stock: 8

But for products such as phones, laptops, etc., which have only one option and do not have color_id and size_id at all. I don't know what to do. please help. For example, these are the options for product_id=5, which is a laptop in the product_options table:

option::1

color_id:null

size_id: null

price: 50

stock: 5


I was trying to print array inside a foreach loop in following way:
@foreach($response['results'] as $row)

         @foreach($row['status'] as $r)
            Status-  {{$r['groupName']}}   //  it shows above error on this line
         @endforeach

       {{$row['from'] - $row['sentAt']}}
       {{$row['to'] - $row['doneAt']}}

@endforeach

I have checked in every response and I have got status value on each response. Here is my array response:
"results" => array:14 [▼
      0 => array:13 [▼
        "messageSegments" => array:3 [▶]
        "sentAt" => "2024-02-23T04:41:01.881Z"
        "doneAt" => "2024-02-23T04:41:03.267Z"
        "mmsCount" => 3
        "mccMnc" => "310260"
        "price" => array:2 [▶]
        "status" => array:5 [▼
          "groupId" => 3
          "groupName" => "DELIVERED"
          "id" => 5
          "name" => "DELIVERED_TO_HANDSET"
          "description" => "Message delivered to handset"
        ]
        "error" => array:5 [▼
          "groupId" => 0
          "groupName" => "OK"
          "id" => 0
          "name" => "NO_ERROR"
          "description" => "No Error"
        ]
        "applicationId" => "default"
      ]
      1 => array:13 [▶]
      2 => array:14 [▶]
      3 => array:14 [▶]

But it shows following error :

Trying to access array offset on value of type int

What could be possible error behind that and how to solve it?


I have tried this in my migration but it does not work as expected.
$table->string('key')->primary()->index();
I also tried to use chatgpt but no solutions were correct. So I hit brick wall debugging, I know its something obvious I am missing.


I am building a website in Laravel and need to use a different domain for each language.
Currently I'm using mcamara/laravel-localization for the localization.
For example:

EN => my-english-website.com
NL => my-dutch-website.com

It seems like using different domains is not something that is supported by default.
Has someone run into this issue and knows how to solve this?


I recently installed Laravel Framework 10.43.0 and then installed Laravel Breeze into that, which created a bunch of new files, including resources/views/layouts/navigation.blade.php. In that file there's this:
<!-- Navigation Links -->
<div class="hidden space-x-8 sm:-my-px sm:ms-10 sm:flex">
    <x-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')">
        {{ __('Dashboard') }}
    </x-nav-link>
</div>

I can add new nav links by adding new x-nav-link elements but my question is...  what are the valid : attributes for x-nav-link? There's :href and :active...  anything else?
I ask because I'd like to make a nav link appear conditionally based on whether or not you're an admin for the site and I'm curious if there's a built in way to do that with the x-nav-link element.


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


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

    <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>

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:

    <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>

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.