I am using laravel 10 and building rest api. I am creating Categories resorce,controller, model
Route::apiResource('/admin-category', CategoryController::class);
this is the route in api.php.
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Http\Requests\StoreCategoryRequest;
use App\Http\Requests\UpdateCategoryRequest;
use App\Http\Resources\CategoryResource;

class CategoryController extends Controller
{
    /**
    * Display a listing of the resource.
    */
    public function index()
    {
        return Category::query()->orderBy('id', 'desc')
            ->paginate(10);
    }

    /**
     * Store a newly created resource in storage.
     */
     public function store(StoreCategoryRequest $request)
     {
        $data = $request->validated();
        $data['image'] = $request['image'];
        $data['description'] = $request['description'];
        Category::create($data);
        return response(['success' => true, 'msg' => 'New Category created!'], 201);
     }

    /**
     * Display the specified resource.
     */
    public function show(Category $category)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateCategoryRequest $request, Category $category)
    {
        $data = $request->validated();
        if(isset($request['image'])){
            $data['image'] = $request['image'];
        }
        $category->update($data);
        return response(['success' => true, 'msg' => 'Category updated!'], 200);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Category $category)
    {
        $category->delete();
        return response(['msg' => 'Deleted successfully', 'success' => true], 201);
    }
}

This is my controller and here index() and store method is working as well but destroy and update is not working and not showing any error.
<?php

namespace App\Models;

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

class Category extends Model
{
   use HasFactory;

/**
 * The attributes that are mass assignable.
 *
 * @var array<int, string>
 */
  protected $fillable = [
    'name',
    'image',
    'description'
  ];
}

This is Category model.
And migration is
<?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('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('image')->nullable();
            $table->string('description')->nullable();
            $table->timestamps();
        });
    }

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

I am trying from frontend. And category creating and fetch is working perfectly.
what is the problem with destroy and update?
I have checked many times payload is sending correctly with category id


I am attempting to install my Laravel 10 project in a subfolder so that I can access it at example.com/laravel-project/ instead of example.com/laravel-project/public/. Here is the .htaccess configuration I tried in the /laravel-project/ directory:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^(.*)$ public/ [L]
</IfModule>

This configuration results in a Laravel-styled 404 error when accessing the subfolder URL. I've reviewed other questions and it seems that something has changed in Laravel 10 that prevents this setup from working as it did in previous versions. I'd like to avoid using php artisan serve. Additionally, I have the following set in my .env file, which should also be correct:
#...
APP_DIR=laravel-project
APP_URL=http://example.com/laravel-project
#...

How can I configure the .htaccess file or Laravel 10 setup to correctly render the homepage at the subfolder URL without having to go to public/ in the URL?
Edit: The site will be on shared hosting


I am creating a migration in Laravel and I need to reference the same table 2 times. I explain:
The "inventory" table has the "responsible" and "created by" fields that refer to the user table. The person responsible and the creator may be the same person in certain cases.
This is the migration code:
Schema::create('inventory', function (Blueprint $table) {
            $table->id();
            $table->integer('type');
            $table->string('state', 50);
            $table->timestamps();
            $table->foreignId('user_id')->constrained(
                table: 'user',
                indexName: 'created_inventory_id'
            )->cascadeOnUpdate()->restrictOnDelete();
            $table->foreignId('user_id')->constrained(
                table: 'user',
                indexName: 'responsible_inventory_id'
            )->cascadeOnUpdate()->restrictOnDelete();
            $table->foreignId('area_id')->constrained(
                table: 'area',
                indexName: 'area_inventory_id'
            )->cascadeOnUpdate()->restrictOnDelete();
        });

When I run the migration it gives me the following error:
SQLSTATE[42701]: Duplicate column: 7 ERROR:  column "user_id" was specified more than once (Connection: pgsql, SQL: create table "inventory"

How could I resolve that?


I can not get object data to pass to Blade template with Mccarlosen/Laravel-mpdf Package. The desire is to pass a singe row database record but call to page is met with error - "undefined variable $agency"
Target blade data syntax is correct as follows -
{{ $agency->id }}

Instructions per the repo as follows -
    use PDF;

class ReportController extends Controller
{
    public function viewPdf()
    {
        $data = [
            'foo' => 'bar'
        ];

        $pdf = PDF::loadView('pdf.document', $data);

        return $pdf->stream('document.pdf');
    }

}

In my controller, I am calling the Object without failure, grabbing the data without failure, and streaming pdf correctly without data (all tested). But when $agency is chained according to example above (per the common Laravel syntax) it fails. I believe this might be secondary to nested structure of data in Laravel object. But not sure. My controller function is below.
public function print(string $id) {

        // Read a single row of data in the Model
        $agency = Agency::find($id);

        // Redirect to the view with the data
        $pdf = PDF::loadView('modules.agencyMain.print',$agency);

        return $pdf->stream('agency.pdf');

    }

Looking for guidance/answers.


I want to save image file in the storage folder but when I insert a file in my form and I click on the button, it displays me the error "Path cannot be empty".
Path cannot be empty
{"exception":"[object] (RuntimeException(code: 0): Path cannot be empty at C:\\laragon\\www\\nextdrive_web\\vendor\\nyholm\\psr7\\src\\Factory\\Psr17Factory.php:41)
[stacktrace]
#0 C:\\laragon\\www\\nextdrive_web\\vendor\\symfony\\psr-http-message-bridge\\Factory\\PsrHttpFactory.php(118): Nyholm\\Psr7\\Factory\\Psr17Factory->createStreamFromFile('')
#1 C:\\laragon\\www\\nextdrive_web\\vendor\\symfony\\psr-http-message-bridge\\Factory\\PsrHttpFactory.php(100): Symfony\\Bridge\\PsrHttpMessage\\Factory\\PsrHttpFactory->createUploadedFile(Object(Symfony\\Component\\HttpFoundation\\File\\UploadedFile))
#2 C:\\laragon\\www\\nextdrive_web\\vendor\\symfony\\psr-http-message-bridge\\Factory\\PsrHttpFactory.php(72): Symfony\\Bridge\\PsrHttpMessage\\Factory\\PsrHttpFactory->getFiles(Array)
#3 C:\\laragon\\www\\nextdrive_web\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\RoutingServiceProvider.php(139): Symfony\\Bridge\\PsrHttpMessage\\Factory\\PsrHttpFactory->createRequest(Object(Illuminate\\Http\\Request))
#4 C:\\laragon\\www\\nextdrive_web\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php(873): Illuminate\\Routing\\RoutingServiceProvider->Illuminate\\Routing\\{closure}(Object(Illuminate\\Foundation\\Application), Array)
#5 C:\\laragon\\www\\nextdrive_web\\vendor\\laravel\\framework\\src\\Illuminate\\Container\\Container.php(758): Illuminate\\Container\\Container->build(Object(Closure))


I'm using Laravel 10 and Laravel Passport and in this project, I tried registering new users like this:
public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|unique:users|max:255',
            'password' => 'required|min:6'
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password)
        ]);

        $token = $user->createToken('MyApp')->accessToken;

        return response([
            'token' => $token
        ]);
    }

Then I defined another route which is under api middleware:
Route::post('register',[AuthenticationController::class,'register']);

Route::middleware('auth:api')->group(function() {
    Route::resource('products', ProductController::class);
});

And in the ProductController I tried adding this method for storing new products:
public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|max:255',
            'description' => 'required|max:255',
            'price' => 'required'
        ]);

        if ($request->user()) {
            Product::create([
                'title' => $request->title,
                'description' => $request->description,
                'price' => $request->price,
                'user_id' => $request->user()->id
            ]);

            return response([
                'message' => 'product created successfully'
            ],201);
        }else{
            return response(['message' => 'User not authenticated.'], 401);
        }
    }

But when I test the url in PostMAN which is this:
http://localhost:8000/api/products

I get this message:
{
    "message": "Unauthenticated."
}

However I have copied and pasted the token retrieved from /register rendpoint as Token input of Authorization section:

I also set the Headers to Accept and application/json and sent these form-data as Body:
title:myproduct
description:The production desc
price:2000

I don't know why I get this Unauthenticated Message, I also configured the auth.php like this:
'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

And added this Service Provider to app.php:
Laravel\Passport\PassportServiceProvider::class,

And used the correct class at User Model:
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    ...
}

So what's going wrong here? How can I solve this issue?

UPDATE #1:
Result of dd($user->createToken('MyApp'));:


I created the laravel project and the problem is that the admin users are filling the form along jpg file and the file is being uploaded and being stored in storage directory but where the image aim to be displayed to public users it is not being displayed.
{{url('/storage/app/news/' . $val2->id . '.png') }}"

Although the file exists at that locations.
I tried with changing the file reading mode permission for server.
I have not moved to deployment phase although, the issue is in Laravel development server.
The file is not being displayed at web while file is there don't know access issue or what else.


I'm working with Laravel latest version and I want to show an image like this:
<img src="{{ asset('storage/'.$media->med_path) }}" alt="Thumbnail" style="width: 100px; height: auto;">

And when I see the source code it adds this value to src attribute of image tag:
http://localhost:8000/storage/public/medias/jpg/57N8MJmsp2y8P0aexysV_200x200.jpg
But the image itself not showing up somehow:

Here is also the value of variable ($media->med_path) in the DB:
public/medias/jpg/57N8MJmsp2y8P0aexysV_200x200.jpg

However I have already ran the command php artisan storage:link and the links are already exists via this filesystems.php config file:
'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
            'throw' => false,
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
            'throw' => false,
        ],

        ...

        'links' => [
            public_path('storage') => storage_path('app/public'),
        ],

And the image already exists in this directory of my project:
-project
     -storage
           -app
                -public
                     -medias
                          -jpg
                               -57N8MJmsp2y8P0aexysV_200x200.jpg

So what's going wrong here? How can I solve this issue and show the image properly?


I'm trying to cache my routes using php artisan route:cache and it returns a logic exception because it thinks the route name is already used, which isn't the case. Here's the exception i get:

LogicException : Unable to prepare route [registreren] for serialization. Another route has already been assigned name [auth.register].

Here's my primary web.php routing file:
Route::name('auth.')->middleware(['basket'])->group(__DIR__ . '/web/auth.php');
Route::name('client.')->middleware(['basket'])->group(__DIR__ . '/web/client.php');
Route::prefix('admin')->name('admin.')->middleware(['admin'])->group(__DIR__ . '/web/admin.php');

Here's the excerpt of the auth.php routing file which throws the exception:
Route::controller(AuthRegisterController::class)->name('register')->middleware('guest')->group(function () {
    Route::get('/registreren', 'view');
    Route::post('/registreren', 'action');
});

I've searched through the routing files if i didn't accidently used the auth.register name twice but i didn't. However when i name the routes in the register group, it works:
Route::controller(AuthRegisterController::class)->name('register.')->middleware('guest')->group(function () {
    Route::get('/registreren', 'view')->name('get');
    Route::post('/registreren', 'action')->name('post');
});

Now i'm wondering, is this expected behaviour? The routing works perfectly without naming the get and post routes:
<a href="{{ route('auth.register') }}">
<form method="post" action="{{ route('auth.register') }}">

If this is expected behaviour, then the exception description is very misleading. I am hoping there's another solution to this problem because we've used the same approach for dozens of routes not to mention the hunderds of route calls in our views. Maybe it's a bug or i am doing something else wrong because it would require a huge refactor to name all the routes and route calls. Any thoughts would be very welcome, thanks.


I have two models:

User
Place
and a Pivot as:
Role(user_id, place_id, type)
and an example of type is "["manager", "reception"]" and i want to change this value to collection when retriving as:
Place::find(1)->users[0]->pivot->type

i add this method but it doesn't work and return string:
    public function getTypeAttribute($value){
        return collect(json_decode($value));
    }


I have a issue while trying to mock multi Storage in laravel test enviromnment.
Here is my my code:
public function sftp ( Sibling $sibling ) {
        $file_paths = Storage::build($sibling->config)
                             ->files($this->track->track_token);
        Storage::disk('public')
               ->makeDirectory($this->track->track_token);
        foreach ( $file_paths as $file_path ) {
            $file_content = Storage::build($sibling->config)
                                   ->get($file_path);
            TrackMp3::query()
                    ->where('track_id' , $this->track->id)
                    ->where('file_name' , basename($file_path))
                    ->update([
                                 'downloaded_at' => now() ,
                             ]);
            Storage::disk('public')
                   ->put($file_path , $file_content);
        }
    }

Here is my test case:

public function test_sftp_works_when_track_exists_in_sibling () {
        $track_token = md5('sample');
        $track_320 = UploadedFile::fake()
                                 ->create('track_320.mp3')
                                 ->getContent();
        $track_160 = UploadedFile::fake()
                                 ->create('track_160.mp3')
                                 ->getContent();
        $track_96 = UploadedFile::fake()
                                ->create('track_96.mp3')
                                ->getContent();
        $track_demo = UploadedFile::fake()
                                  ->create('track_demo.mp3')
                                  ->getContent();
        $sibling = SiblingFactory::new()
                                 ->create();
        $public_disk = Storage::fake('public');
        $sibling_disk = Storage::fake('sibling');
        Storage::shouldReceive('build')
               ->with($sibling->config)
               ->andReturn($sibling_disk);
        $sibling_disk->put($track_token . '/track_320.mp3' , $track_320);
        $sibling_disk->put($track_token . '/track_160.mp3' , $track_160);
        $sibling_disk->put($track_token . '/track_96.mp3' , $track_96);
        $sibling_disk->put($track_token . '/track_demo.mp3' , $track_demo);
        $track = TrackFactory::new()
                             ->md5Fetched()
                             ->has(TrackMp3Factory::new([ 'md5' => md5_file($sibling_disk->path($track_token . '/track_320.mp3')) ])
                                                  ->fileName320())
                             ->has(TrackMp3Factory::new([ 'md5' => md5_file($sibling_disk->path($track_token . '/track_160.mp3')) ])
                                                  ->fileName160())
                             ->has(TrackMp3Factory::new([ 'md5' => md5_file($sibling_disk->path($track_token . '/track_96.mp3')) ])
                                                  ->fileName96())
                             ->has(TrackMp3Factory::new([ 'md5' => md5_file($sibling_disk->path($track_token . '/track_demo.mp3')) ])
                                                  ->fileNameDemo())
                             ->create([ 'track_token' => $track_token ]);

        Storage::fake('public'); // ----> Error happend here
        Artisan::call('download');
    }

Here is the error:
Mockery\Exception\BadMethodCallException: Received Mockery_2_Illuminate_Filesystem_FilesystemManager::createLocalDriver(), but no expectations were specified
C:\Development\projects\track-download-manager\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:353
C:\Development\projects\track-download-manager\vendor\laravel\framework\src\Illuminate\Support\Facades\Storage.php:107
C:\Development\projects\track-download-manager\tests\Feature\DownloadCommandTest.php:55


I'm currently develop a web application with Laravel.
My database engine is a Microsoft SQL Server.
For some data I preferred to generate an uuid.
When I use Windows to run my Laravel app, the uuid format is correct :

A5EE121A-1F10-46FC-B779-49D2A0FA3B68

But when I ran my Laravel app under linux, and use the same database, the uuid format is like this :

b"\x1A\x12î¥\x10\x1FüF·yIÒ ú;h"

I don't know where is the problem...
Have you an idea ?
Thanks.
The goal is to retrieve the same format when the Laravel app ran under Windows and under Linux.


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.


im new on livewire and im got stuck from it.
"i want to get 'id' from route and fetch it using livewire component (function) to get data from by id in the database, and get error about parameter 0 or somethink, here the error :
Unable to resolve dependency [Parameter #0 [ <required> $id ]] in class App\Livewire\StartExams

i know if it using laravel i can get te data, but when im using livewire  got error
here my button :
exams->id) }}"
    wire:click="mount({{ $getExamsOnLecture->exams->id }})">

        {{ $getExamsOnLecture->exams->name }}

my route:
use App\Livewire\StartExams;
Route::get('/exams/{any}/start', StartExams::class)->name('start-quiz');

here the livewire controller:
namespace App\Livewire;
use App\Models\Questions;
use App\Models\QuestionsOption;
use Livewire\Component;

class StartExams extends Component
{
    public $id;
    public $questions = [];
    public $questionIndex = 0;
    public $question;
    public $answer;
    public $questionOption;

    public bool $finished = false;

    public function mount($id)
    {
        $this->id = $id;
        $this->questions = Questions::where('exam_id', $this->id)->get();

        foreach ($this->questions as $key => $questionOption) {
            $this->questionOption[$key]['options'] = QuestionsOption::where('question_id',  $questionOption->id)->get();
            // return $this->questions[$key]['options'];
        }

    }

    public function resetRadioOptions()
    {
        $this->answer = null;
    }

    public function submitQuiz()
    {
        //otw making save to database ///

        $this->questionIndex++;
        if ($this->questionIndex >= count($this->questions)) {
            $this->finished = true;
        } else {
            $this->question = $this->questions[$this->questionIndex];
            $this->resetRadioOptions();
        }
    }
    public function render()
    {
        return view('livewire.start-exams', [
            'id' => $this->id,
        ])->layout('layouts.auth');
    }
}

i thought at first it same as laravel so im ignore it and doing other file than this, then im im going to fix it so i can get the data based bny id, it got error..
im already trying searching on google and even AI but its failed, so im posting here..
can someone help me? just giving me step by step that i must fixed.
i want the id get it form id from tag  route so i cane get data based by id
$this->questions = Questions::where('exam_id', $this->id)->get();

but if it like this (work, cause im put number instead id)
$this->questions = Questions::where('exam_id', '1')->get();

i can get the record, but based by $id its got error..


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 am new to Laravel and Vue 3.
I have a create and update form for pages.
The created page works 100% with or without uploading images.
I copied and pasted and changed the page object to the prop.page, updated the form route and a few other small changes but nothing else.
When submitting the form without an image everything works fine, but if you submit a form, no input fields are submitted.
I get no errors, from laravel, vue or console.log.
Here is my page controller:
<?php

namespace App\Http\Controllers;

use App\Models\Page;
use Inertia\Inertia;
use Inertia\Response;
use Intervention\Image\ImageManager;
use Illuminate\Http\RedirectResponse;
use App\Http\Requests\StorePageRequest;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests\UpdatePageRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Intervention\Image\Drivers\Gd\Driver;

class PageController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(Page::class, 'page');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(): Response
    {
        $pages = Page::select('id', 'name', 'in_menu', 'position')->paginate(20);
        return Inertia::render('Admin/Pages/Index', compact('pages'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return Inertia::render('Admin/Pages/Create', ['status' => session('status')]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StorePageRequest $request): RedirectResponse
    {
        $page = new Page();

        $newImageName = '';

        if($request->hasFile('header')){
            $image = $request->file('header');

            $originalName = pathinfo(str_replace(' ', '', $image->getClientOriginalName()), PATHINFO_FILENAME);
            $newImageName = time().'-'.$originalName.'.'.$image->guessClientExtension();

            $manager = new ImageManager(
                new Driver()
            );

            $image = $manager->read($image);

            $image->coverDown(1200, 675)->save(public_path('storage/uploads/page/images/full/'.$newImageName));
            $image->coverDown(600, 338)->save(public_path('storage/uploads/page/images/medium/'.$newImageName));
            $image->coverDown(100, 100)->save(public_path('storage/uploads/page/images/thumb/'.$newImageName));
        }

        $page->name = $request->name;
        $page->title = $request->title;
        $page->description = $request->description;
        $page->content = $request->content;
        $page->header = $newImageName;
        $page->in_menu = $request->in_menu;
        $page->position = $request->position;

        $page->save();

        return Redirect::route('admin.pages.index')->with('success', 'page created successfully');
    }

    /**
     * Display the specified resource.
     */
    public function show(Page $page)
    {

    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Page $page)
    {
        return Inertia::render('Admin/Pages/Edit', compact('page'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdatePageRequest $request, Page $page): RedirectResponse
    {
        dd([$request, $page]);
        $newImageName = $page->header;

        if($request->hasFile('header')){
            $image = $request->file('header');

            $originalName = pathinfo(str_replace(' ', '', $image->getClientOriginalName()), PATHINFO_FILENAME);
            $newImageName = time().'-'.$originalName.'.'.$image->guessClientExtension();

            $manager = new ImageManager(
                new Driver()
            );

            $image = $manager->read($image);

            $image->coverDown(1200, 675)->save(public_path('storage/uploads/page/images/full/'.$newImageName));
            $image->coverDown(600, 338)->save(public_path('storage/uploads/page/images/medium/'.$newImageName));
            $image->coverDown(100, 100)->save(public_path('storage/uploads/page/images/thumb/'.$newImageName));

            Storage::delete('/uploads/page/images/full/'.$page->header);
            Storage::delete('/uploads/page/images/medium/'.$page->header);
            Storage::delete('/uploads/page/images/thumb/'.$page->header);
        }

        $page->name = $request->name;
        $page->title = $request->title;
        $page->description = $request->description;
        $page->content = $request->content;
        $page->header = $newImageName;
        $page->in_menu = $request->in_menu;
        $page->position = $request->position;

        $page->save();

        return Redirect::route('admin.pages.index')->with('success', 'page update successfully');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Page $page)
    {
        //
    }
}

Here is my routes:
<?php

use App\Http\Controllers\PageController;
use Illuminate\Support\Facades\Route;

Route::middleware('auth')->group(function () {
    Route::controller(PageController::class)->group(function () {
        Route::get('/admin/pages', 'index')->name('admin.pages.index');

        Route::get('/admin/pages/create', 'create')->name('admin.pages.create');
        Route::post('/admin/pages/store', 'store')->name('admin.pages.store');

        Route::get('/admin/pages/{page}/edit', 'edit')->name('admin.pages.edit');
        Route::put('/admin/pages/{page}/update', 'update')->name('admin.pages.update');
    });
});

My UpdatePageRequest:
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdatePageRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:50', 'min:4'],
            'title' => ['required', 'string', 'max:150', 'min:4'],
            'description' => ['required', 'string', 'max:200', 'min:20'],
            'content' => ['required', 'string', 'min:4'],
            'header' => ['sometimes', 'image'],
            'in_menu' => ['required', 'numeric', Rule::in([0,1])],
            'position' => ['required', 'numeric'],
        ];
    }
}

Page Policy:
<?php

namespace App\Policies;

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

class PagePolicy
{
    /**
     * Determine whether the user can view any models.
     */
    public function viewAny(User $user): bool
    {
        return (bool)$user->is_admin;
    }

    /**
     * Determine whether the user can view the model.
     */
    public function view(User $user, Page $page): bool
    {
        return (bool)$user->is_admin;
    }

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

    /**
     * Determine whether the user can update the model.
     */
    public function update(User $user, Page $page): bool
    {
        return true;
        // return (bool)$user->is_admin;
    }

    /**
     * Determine whether the user can delete the model.
     */
    public function delete(User $user, Page $page): bool
    {
        return (bool)$user->is_admin;
    }

    /**
     * Determine whether the user can restore the model.
     */
    public function restore(User $user, Page $page): bool
    {
        return (bool)$user->is_admin;
    }

    /**
     * Determine whether the user can permanently delete the model.
     */
    public function forceDelete(User $user, Page $page): bool
    {
        return (bool)$user->is_admin;
    }
}

And Finally my Vue:
<template>

    <AuthenticatedLayout>
        <template #header>

Create New Page

        </template>

                <AdminLeftColumn />

                        <Link href="/admin/pages" class="py-2 px-2 rounded-sm bg-blue-400 text-white text-sm hover:ring-4 hover:ring-blue-500">Back</Link>

                    <form @submit.prevent="form.put(route('admin.pages.update', page))" enctype="multipart/form-data" class="mt-6 space-y-6">

                                    <InputLabel for="name" value="Page Name" />

                                    <TextInput
                                        id="name"
                                        type="text"
                                        class="mt-1 block w-full"
                                        v-model="form.name"
                                        required
                                        autocomplete="name"
                                    />

                                    <InputError class="mt-2" :message="form.errors.name" />

                                    <InputLabel for="title" value="Page Title" />

                                    <TextInput
                                        id="title"
                                        type="text"
                                        class="mt-1 block w-full"
                                        v-model="form.title"
                                        required
                                        autocomplete="title"
                                    />

                                    <InputError class="mt-2" :message="form.errors.title" />

                            <InputLabel for="header" value="Header Image" />

                            <TextInput
                                id="header"
                                type="file"
                                class="mt-1 block w-full text-sm text-gray-900 border border-gray-300 rounded-lg cursor-pointer focus:outline-none p-2"
                                @input="form.header = $event.target.files[0]"
                            />

                            <InputError class="mt-2" :message="form.errors.header" />

                            <InputLabel for="description" value="Page Description" />

                            <TextArea
                                rows="3"
                                id="description"
                                type="text"
                                class="mt-1 block w-full"
                                v-model="form.description"
                                required
                                autocomplete="description"
                            />

                            <InputError class="mt-2" :message="form.errors.description" />

                            <InputLabel for="content" value="Page Content" />

                            <Editor
                            id="content"
                            v-model="form.content"
                            :mode="form.content"
                            required
                            autocomplete="content"
                            />

                            <InputError class="mt-2" :message="form.errors.content" />

                                Your email address is unverified.
                                <Link
                                    :href="route('verification.send')"
                                    method="post"
                                    as="button"
                                    class="underline text-sm text-gray-600 hover:text-gray-900 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                                >
                                    Click here to re-send the verification email.
                                </Link>

                                A new verification link has been sent to your email address.

                            <PrimaryButton :disabled="form.processing">Save</PrimaryButton>

                            <Transition
                                enter-active-class="transition ease-in-out"
                                enter-from-class="opacity-0"
                                leave-active-class="transition ease-in-out"
                                leave-to-class="opacity-0"
                            >

Saved.

                            </Transition>

                    </form>

    </AuthenticatedLayout>
</template>

I have been trying everything on the internet I can find that is remotely plausable to this issue, 5 hours in total.
I have used Chat GPT with very little help. It just tells me to make sure the routes and validations are correct.
The validation works because it is the same as the create, no differences.
The permissions from the policy look good and to make sure I even set them all to true to make sure it wasnt that.
I did a console.log() of the form after it has been sent and it shows that the form.name, form.title etc was within the form.
But when it lands in the PageController@update it has nothing.
Here is the dump when file is not uploaded:
array:2 [▼ // app\Http\Controllers\PageController.php:101
  0 =>
Illuminate\Http
\
Request {#37 ▼
    +attributes:
Symfony\Component\HttpFoundation
\
ParameterBag {#42 ▼
      #parameters: []
    }
    +request:
Symfony\Component\HttpFoundation
\
InputBag {#41 ▼
      #parameters: array:6 [▼
        "name" => "About Us Page"
        "title" => "This is a title for about us page"
        "description" => "This is a little description about the about us page"
        "content" => "
sdasdasdasdasdasdasdasdasd
"
        "in_menu" => 1
        "position" => 0
      ]
    }
    +query:
Symfony\Component\HttpFoundation
\
InputBag {#45 ▶}
    +server:
Symfony\Component\HttpFoundation
\
ServerBag {#40 ▶}
    +files:
Symfony\Component\HttpFoundation
\
FileBag {#44 ▶}
    +cookies:
Symfony\Component\HttpFoundation
\
InputBag {#43 ▶}
    +headers:
Symfony\Component\HttpFoundation
\
HeaderBag {#39 ▶}
    #content: "
{"name":"About Us Page","title":"This is a title for about us page","description":"This is a little description about the about us page","content":"
sdasdasda
 ▶
"
    #languages: null
    #charsets: null
    #encodings: null
    #acceptableContentTypes: null
    #pathInfo: "/admin/pages/5/update"
    #requestUri: "/admin/pages/5/update"
    #baseUrl: ""
    #basePath: null
    #method: "PUT"
    #format: null
    #session:
Illuminate\Session
\
Store {#322 ▶}
    #locale: null
    #defaultLocale: "en"
    -preferredFormat: null
    -isHostValid: true
    -isForwardedValid: true
    -isSafeContentPreferred: ? bool
    -trustedValuesCache: []
    -isIisRewrite: false
    #json:
Symfony\Component\HttpFoundation
\
InputBag {#41 ▶}
    #convertedFiles: null
    #userResolver: Closure($guard = null) {#285 ▶}
    #routeResolver: Closure() {#294 ▶}
    basePath: ""
    format: "html"
  }
  1 =>
App\Models
\
Page {#1324 ▼
    #connection: "mysql"
    #table: "pages"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    +preventsLazyLoading: false
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #escapeWhenCastingToString: false
    #attributes: array:10 [▶]
    #original: array:10 [▶]
    #changes: []
    #casts: []
    #classCastCache: []
    #attributeCastCache: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    +usesUniqueIds: false
    #hidden: []
    #visible: []
    #fillable: array:7 [▼
      0 => "name"
      1 => "title"
      2 => "description"
      3 => "content"
      4 => "header"
      5 => "in_menu"
      6 => "position"
    ]
    #guarded: array:1 [▼
      0 => "*"
    ]
  }
]

This is with the image uploaded:
array:2 [▼ // app\Http\Controllers\PageController.php:101
  0 =>
Illuminate\Http
\
Request {#37 ▼
    +attributes:
Symfony\Component\HttpFoundation
\
ParameterBag {#42 ▼
      #parameters: []
    }
    +request:
Symfony\Component\HttpFoundation
\
InputBag {#38 ▼
      #parameters: []
    }
    +query:
Symfony\Component\HttpFoundation
\
InputBag {#45 ▶}
    +server:
Symfony\Component\HttpFoundation
\
ServerBag {#40 ▶}
    +files:
Symfony\Component\HttpFoundation
\
FileBag {#44 ▶}
    +cookies:
Symfony\Component\HttpFoundation
\
InputBag {#43 ▶}
    +headers:
Symfony\Component\HttpFoundation
\
HeaderBag {#39 ▶}
    #content: null
    #languages: null
    #charsets: null
    #encodings: null
    #acceptableContentTypes: null
    #pathInfo: "/admin/pages/5/update"
    #requestUri: "/admin/pages/5/update"
    #baseUrl: ""
    #basePath: null
    #method: "PUT"
    #format: null
    #session:
Illuminate\Session
\
Store {#322 ▶}
    #locale: null
    #defaultLocale: "en"
    -preferredFormat: null
    -isHostValid: true
    -isForwardedValid: true
    -isSafeContentPreferred: ? bool
    -trustedValuesCache: []
    -isIisRewrite: false
    #json: null
    #convertedFiles: null
    #userResolver: Closure($guard = null) {#285 ▶}
    #routeResolver: Closure() {#294 ▶}
    basePath: ""
    format: "html"
  }
  1 =>
App\Models
\
Page {#1324 ▼
    #connection: "mysql"
    #table: "pages"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    +preventsLazyLoading: false
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #escapeWhenCastingToString: false
    #attributes: array:10 [▼
      "id" => 5
      "name" => "About Us Page"
      "title" => "This is a title for about us page"
      "description" => "This is a little description about the about us page"
      "content" => "
sdasdasdasdasdasdasdasdasd
"
      "header" => ""
      "in_menu" => 1
      "position" => 0
      "created_at" => "2024-02-15 16:15:13"
      "updated_at" => "2024-02-15 18:56:48"
    ]
    #original: array:10 [▶]
    #changes: []
    #casts: []
    #classCastCache: []
    #attributeCastCache: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    +usesUniqueIds: false
    #hidden: []
    #visible: []
    #fillable: array:7 [▼
      0 => "name"
      1 => "title"
      2 => "description"
      3 => "content"
      4 => "header"
      5 => "in_menu"
      6 => "position"
    ]
    #guarded: array:1 [▼
      0 => "*"
    ]
  }
]

Any help would be highly appreciated.


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.


In table, I have a "View Address" button where when I click, it will show the address details. It works fine but however, since I am still new in Alpine.js, when I click the view address it shows all address details for all rows in the table. Below is my code:

    @foreach ($customer as $customers)

            {{ $customers->id }}
            {{ $customers->name }}
            {{ $customers->email }}

                    <button class="address-button" x-on:click=" show=!show ">View Address</button>

                id) }}"
                    class="text-indigo-600 hover:text-indigo-900"><svg xmlns="http://www.w3.org/2000/svg"
                        width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000000"
                        stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M20 14.66V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h5.34"></path>
                        <polygon points="18 2 22 6 12 16 8 16 8 12 18 2"></polygon>
                    </svg>

                @if ($customers->addresses)
                    @php
                        $addresses = is_string($customers->addresses) ? json_decode($customers->addresses, true) : $customers->addresses;
                        $addresses = isset($addresses['addresses']) ? $addresses['addresses'] : $addresses;
                        $num = 1;
                    @endphp
                    @if (!empty($addresses) && is_array($addresses))
                        @foreach ($addresses as $address)

                                Address {{ $num }}

                                @if (array_key_exists('street1', $address))
                                    Street 1: {{ $address['street1'] }}

                                @endif
                                @if (array_key_exists('street2', $address))
                                    Street 2: {{ $address['street2'] }}

                                @endif
                                @if (array_key_exists('postcode', $address))
                                    Postcode: {{ $address['postcode'] }}

                                @endif
                                @if (array_key_exists('city', $address))
                                    City: {{ $address['city'] }}

                                @endif
                                @if (array_key_exists('state', $address))
                                    State: {{ $address['state'] }}

                                @endif
                                @if (array_key_exists('country', $address))
                                    Country: {{ $address['country'] }}

                                @endif

                            @if (!$loop->last)

                            @endif
                            @php
                                $num++;
                            @endphp
                        @endforeach
                    @endif
                @endif

    @endforeach

I believe that since I declare
, it will show all the address details for all rows. I tried to use based on $customer->id but somehow it does not work.


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.