I am trying to make an HTTP client request in Laravel. I have tried using Guzzle directly, and it works, but when doing it through "API around the Guzzle HTTP client" in Laravel, I always get a 400. I can't find where the error is since it seems to be correct. I give the example of the two cases.
$method = 'post', and route and $headers are the same too.
Guzzle (200 success)
$client = new \GuzzleHttp\Client();
$response = $client->request($method, $this->BASEURL . $endpoint, [
    'body' => '{"name":"testName"}',
    'headers' => $headers,
]);

Laravel HTTP Client (400 bad request)
$response = Http::withHeaders($headers)
    ->withBody('{"name":"testName"}', 'application/json')
    ->{$method}($this->BASEURL . $endpoint);

Example from AirbnbAPI using Guzzle
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.airbnb.com/v2/listings', [
    'body' => '{"name":"erer"}',
    'headers' => [
        'X-Airbnb-API-Key' => 'XXXXXXXX',
        'X-Airbnb-OAuth-Token' => 'XXXXXX',
        'X-Airbnb-Req-Api-Version' => '2022.12.31',
        'accept' => 'application/json',
        'content-type' => 'application/json',
    ],
]);

echo $response->getBody();


I want to import the Excel sheet using the artisan command. The excel-sheet file size is 400MB has 500 000 rows and 300 columns. This Excel sheet is stored in the public folder.
Artisan command code:
public function handle()
{
    $this->output->title('Excel Import Process Start');

    // Check type is valid
    $file = $this->option('file');

    $filePath = public_path('excel-import/' . $file);
    if (!File::exists($filePath)) {
        return $this->output->error("File is not found!");
    }

    Log::info("step 1");
    try {
        (new ImportApplications)->withOutput($this->output)->import($filePath);
    } catch (Exception $e) {
        $this->output->error("Import Exception");
        $this->output->info($e->getMessage());
        return false;
    }

    $this->output->success('Import successful');
    return true;
}

Import application code
class ImportApplications implements ToModel, WithHeadingRow, WithBatchInserts, WithChunkReading, WithUpserts, WithProgressBar , ShouldQueue
{
    use Importable;
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */

    public function model(array $row)
    {
        Log::info($row);
        return new Application([
            'FILED_NAME' => $row['column_name'],
            ...
        ]);
    }

    public function batchSize(): int
    {
        return 1000;
    }

    public function chunkSize(): int
    {
        return 1000;
    }
}

I have set memory_limit: 1500M
The given error is

XMLReader::read(): Memory allocation failed : growing input buffer

If I set memory_limit: 2500M
Then the command was automatically killed
I have also added the import process in the queue but same issue


I have a problem with relationships in Laravel 10. I have two tables in db: 'pages' and 'elements' between which I've tried to establish One-to-Many relationship, however, when I try to access elements related to given page, it returns all elements from table.
Here are simplified migrations for reference:
pages:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{

    public function up(): void {
        Schema::create('pages', function(Blueprint $table) {
            $table->string('id');
            $table->primary('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    public function down(): void {
        Schema::dropIfExists('pages');
    }
};

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

return new class extends Migration {

    public function up(): void {
       Schema::create('elements', function(Blueprint $table) {
            $table->string('id');
            $table->primary('id');
            $table->string('content');
            $table->string('page_id');
            $table->foreign('page_id')
                    ->references('id')
                    ->on('pages')
                    ->onDelete('cascade');
            $table->timestamps();
        });
    }

    public function down(): void {
        Schema::dropIfExists('elements');
    }
};

If I run the migrations and seed the tables, everything works, and is filled as expected.
I've tried to setup One-to-Many (Page-to-Elements) relationship between them, however, when I try to access elements on page (Page::find('some_id')->elements), it doesn't return only related rows, but instead all, even unrelated ones, and I don't understand why.
Here are Models:
App\Models\Page.php
namespace App\Models;

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

class Page extends Model
{
    use HasFactory;

    public function elements(): HasMany  {
        return $this->hasMany(Element::class);
    }
}

App\Models\Element.php
namespace App\Models;

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

class Element extends Model
{
    use HasFactory;

    public function page(): BelongsTo {
        return $this->belongsTo(Page::class);
    }
}

I've also tried giving hasMany method column names of foreign and local keys, but with no success.
Everywhere I look, people, and docs seem to do it the same way. Am I missing something?


i want to change the mysql innoDB engine to MyISAM using laravel migration i created the migration
that is names alter_products_engine that is suppose to change the table products but that is not happining
i made the table migration like below and i am expected the change happens but it dose not
<?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('products', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }

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

and also the alter table migration
<?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::table('products',function(Blueprint $table){
            $table->engine = 'MyISAM';
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('products',function(Blueprint $table){
            $table->engine = 'MyISAM';
        });
    }
};


Looking for a smarter way to do this. I have 4 migrations files (out of MANY dozen) that are related. I also have a seeder for these. Doing php artisan migrate:fresh --seed takes a good 30-45 seconds each time (there are also a few dozen seeders) and I want to just drop my 4 tables and rebuild quickly while testing.
I want to define this programmatically instead of with a CLI, so I made an artisan command:
/* routes/console.php */
Artisan::command('refresh-my-tables', function() {
    $numbers = include __DIR__ . './../database/migrations/2023_05_03_175125_create_my_table_numbers_table.php';
    $files = include __DIR__ . './../database/migrations/2023_05_08_160034_create_my_table_files_table.php';
    $orders = include __DIR__ . './../database/migrations/2023_05_03_175124_create_my_table_orders_table.php';
    $parent = include __DIR__ . './../database/migrations/2023_05_03_171245_create_my_table_table.php';

    // These are ordered intentionally to deal with foreign key constraints
    $numbers->down();
    $files->down();
    $orders->down();
    $parent->down();
    $parent->up();
    $orders->up();
    $files->up();
    $numbers->up();

    (new Database\Seeders\MyTableSeeder)->run();
});

Just need a simple php artisan refresh-my-tables
This feels... wrong. Specifically the include [long absolute filename].  I had thought Laravel, in the past, had a way to hook into migrations by name (letting PSR-4 handle finding the classes), but now, php artisan make:migration builds a file that returns an anonymous Migration extended class.
All Google and SO searches just refer to artisan migrate without acknowledging more complex edge-cases that, I can imagine, are quite common for sufficiently large projects. Is this the best (most Laravel-flavored) way to do this?


In my vue component, I have a form.
There's this field in it: <input type="file" name="image" id="image" class="form-control" required ref="image">
When I log this.$refs.image.files[0] it returns this
File {name: 'random-image.jpg', lastModified: 1684076710626, webkitRelativePath: '', size: 983632, …}

But when the Axios post request is sent, the payload is image:{}, so the image is not really sent.
I'm trying to submit the file/image to the API, am I missing something?
If the provided code snippet returns the data of the image, why is it not being sent to the API?
I've tried answers from other questions, but those didn't solve the problem. I know I'm forgetting something, but can't figure out what.
Edit 1:
So when I do this
async submitForm(){
            let formData = new FormData();
            formData.append('image', this.$refs.image.files[0]);
            formData.append('name', this.name);
            formData.append('price', this.price);
            let response = await submitProductForm(formData)

It actually works.
But what's the difference between using a FormData, and not using one? Now in the payload, the image is a binary, not a file.


I'm trying to load some images in my feature test with Laravlel 10:
class MyTest extends TestCase

    private string $path;

    protected function setUp(): void
    {
        $this->path = storage_path('image.jpeg');
    }
}

But I get this error message Call to undefined method Illuminate\Container\Container::storagePath()
Feature tests are supposed to load the framework, so this should work. I don't understand, did I miss something?


In the dabase i store the validation_parcellaire_at with :
$data = ['validation_parcellaire' => ($validation==1?\Carbon\Carbon::now()->toDateTimeString():null)];

In the database structure :

The result is :

The other field have the same info for the update :

When i retrieve the data with my software i get this :

And to retrieve in Laravel, i call the route which call :
use Illuminate\Http\JsonResponse;

     return $this->sendResponse(new UserResource($user), 'Utilisateur trouvé.');

Do you have any idea of what can happend to have the same data in the database and not the same result in the json with the API ?
Regards


I was able to successfully save the generated pdf file to the path storage/app/public/pdf. Now I want to open a link to each pdf file from a data table in a view. I keep getting a 404 error whenever I try to open the link from the table in my view. Any help would be greatly appreciated.
Here is the code for the data table in my view(reportLink is just the name of the pdf file):

Report History

          Date
          Report Type
          Customer ID
          Product ID
          Report PDF

    @foreach($report_archives as $report_archive)

    {{$report_archive->date}}
      {{$report_archive->reportType}}
      {{$report_archive->customerID}}
      {{$report_archive->productID}}
      reportLink}}">{{$report_archive->reportLink}}

@endforeach

I have tried using url and asset, but I get an error stating "Unclosed '(' does not match '}' "
reportLink}}')}}">{{$report_archive->reportLink}}
 reportLink}}')}}">{{$report_archive->reportLink}}


I am getting this error in my browser when I am trying to make post or put or delete request I tried to edit the response header in the controller and to have middleware but still getting the error
in one of the controllers it works for me for (get,post,delete) requests but still having the problem with the put request however here is the code of the working controller(just the post delete get)
   <?php

namespace App\Http\Controllers;

use App\Models\locations;
use Illuminate\Http\Request;

class locationController extends Controller
{
    public function store(Request $request){
        $data = $request->validate([
            'name'=>'required|min:3'
        ]);
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>locations::create($data)
        ];
         return response()->json($response,200)->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');

       }

public function delete($id){
        $location = locations::destroy($id);

        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$location
        ];
        return response($response,200)->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    }
     public function update(locations $location,Request $request){
        $data = $request->validate([
            'name'=>'required',

        ]);
        $location->update($data);
        $location->save();
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$location
        ];
        return response($response,200)->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    }

    public function getById($id){
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>locations::find($id)`your text`
        ];
        return response($response,200);
    }
    public function index(){
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>locations::all()
        ];
        return response($response,200);
    }

}

and here is the routes for the same controller

Route::get('/location/getall',[locationController::class,'index']);
Route::get('/location/getbyid/{id}',[locationController::class,'getById']);
Route::post('/location/add',[locationController::class,'store']);
Route::put('/location/update/{location}',[locationController::class,'update']);
Route::delete('/location/delete/{id}',[locationController::class,'delete']);
Route::options('/location/update/{location}', function () {
    return response()->json(null, 200)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'PUT,GET,DELETE,POST')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
});

here is the controller code that's not working for any(put, delete,post)
namespace App\Http\Controllers;

use App\Models\Lands;
use App\Models\locations;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\QueryBuilder\QueryBuilder;

use function PHPSTORM_META\map;

class landController extends Controller
{
   public function store(Request $request){

    $data = $request->validate([
        'ownerName'=>'required',
        'size'=>'required',
        'price'=>'required',
        'phoneNumber'=>'required',
        'locations_id'=>'required',
        'aquariumNumber'=>'required',
        'partNumber'=>'required',
        'streetNumber'=>'required',
        'streetWide'=>'required'
    ]);

    $land = Lands::create($data);
    $response = [
        'returnCode'=>200,
        "errorMsg"=>"",
        "result"=>$land
    ];
    return response($response, 200)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');

   }
//    public function search(Request $request){
//     //return locations::where('','LIKE',"%$request->name%")->get();
// }
    public function index(Request $request){
        $lands = lands::with(['locations'])->get();

        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$lands
        ];
        return response($response,200);
    }
    public function getById($id){
        $lands = lands::with(['locations'])->find($id);

        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$lands
        ];
        return response($response,200);
    }

    public function handleCorsPreflight()
{
    return response(null,200)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}

    public function delete($id){
        $lands = lands::destroy($id);

        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$lands
        ];
        return response($response,200);
    }
    public function update(Lands $land,Request $request){
        $data = $request->validate([
            'ownerName'=>'required',
            'size'=>'required',
            'price'=>'required',
            'phoneNumber'=>'required',
            'locations_id'=>'required',
            'aquariumNumber'=>'required',
            'partNumber'=>'required',
            'streetNumber'=>'required',
            'streetWide'=>'required'
        ]);
        $land->update($data);
        $land->save();
        $response = [
            'returnCode'=>200,
            "errorMsg"=>"",
            "result"=>$land
        ];
        return response($response,200);
    }

and here is the routing for the same controller
`
`Route::options('/land/add', [landController::class,'handleCorsPreflight']);
Route::get('/land/getall', [landController::class,'index']);
Route::get('/land/getbyid/{id}', [landController::class,'getById']);
Route::post('/land/add', [landController::class,'store']);
Route::put('/land/update/{land}', [landController::class,'update']);
Route::delete('/land/delete/{id}', [landController::class,'delete']);``

finnaly here is the error code
Access to XMLHttpRequest at 'https://swift-serv.com/api/land/add/' from origin 'https://house-land-asem.000webhostapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
***some note
I am using hostinger for laravel and 000webhost for the angular
thank you for your help and sorry if I wrote too much


TL;DR;
How can I get multiple repositories with different DB connections when using Repository Pattern.
About
Hello, I'm building an API Server using Laravel 10.
I choose Repository Pattern for testing, but struggled with multiple DB connections issue.
What I want

Declare multiple repositories in the controller.
Ex) $user_repo01, $user_repo02, ...
On controller's constructor, each repository is assigned with injected interface.
Each repository should have different DB connection.
Ex) $user_repo01 is connected to 'db01' while $user_repo02 is connected to 'db02'

What I did
Added setConnection($connection) into my BaseRepository.
This calls Eloquent Model's setConnection($connection) to change the connection.
Also added getConnectionNames() to retrive connection's name.
On controller's constuctor, get injected interface and assign to repository.
Before assigning, changed connection.
Problem
Calling '/user/test' should returns connection names by repository.

What I expected is
{
    'user_repo01': 'db01',
    'user_repo02': 'db02',
    'user_repo03': 'db03',
}

But the result is...
{
    'user_repo01': 'db03',
    'user_repo02': 'db03',
    'user_repo03': 'db03',
}

It seems injected interface is shared with all the repositories.
Not sure why, I just started applying Repository Pattern and I don't know much about it.
What I missed? How can I achieve what I want?
Codes
config/database.php
'connections' => [
    'db01' => [ ... ],
    'db02' => [ ... ],
    'db03' => [ ... ],
]

app/Repositories/Interfaces/BaseRepositoryInterface.php
interface BaseRepositoryInterface
{
    public function setConnection(string $connection);
    public function getConnectionName();
}

app/Repositories/BaseRepository.php
class BaseRepository implements BaseRepositoryInterface
{
    public function __construct(Model $model) {
        $this->model = $model;
    }

    public function setConnection(string $connection) {
        $this->model->setConnection($connection);

        return $this;
    }

    public function getConnectionName() {
        return $this->model->getConnectionName();
    }
}

app/Repositories/Interfaces/UserRepositoryInterface.php
interface UserRepositoryInterface extends BaseRepositoryInterface
{

}

app/Repositories/UserRepository.php
class UserRepository extends BaseRepository implements UserRepositoryInterface
{
    public function __construct(User $model) {
        parent::__construct($model);
    }
}

app/Providers/RepositoryServiceProvider.php
class RepositoryServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(UserRepositoryInterface::class, UserRepository::class);
    }
}

app/Http/Controllers/UserController.php
class UserController extends Controller
{
    private $user_repo01;
    private $user_repo02;
    private $user_repo03;

    public function __construct(UserRepositoryInterface $user_repo) {
        $this->user_repo01 = $user_repo->setConnection('db01');
        $this->user_repo02 = $user_repo->setConnection('db02');
        $this->user_repo03 = $user_repo->setConnection('db03');
    }

    /**
     * /user/test
     */
    public function test() {
        return [
            'user_repo01' => $this->user_repo01->getConnectionName(),
            'user_repo02' => $this->user_repo02->getConnectionName(),
            'user_repo03' => $this->user_repo03->getConnectionName(),
        ];
    }


I have a user model and a Schedule model. I am trying to use relationships in Laravel instead of doing a join. Is it possible to return all users that have shifts where shift time = 'x' ? I would like to return all users that have shifts between a specific date range.
$users = User::select('name','location','id AS user_id')->has('shift')>where('schedule.startTime', $start)->get();

This obviously doesn't work because the start column exists in the Schedule Model.
In my User Model I have:
public function shift() {
    return $this->hasMany('App\Models\Schedule');
}

In my Schedule Model I have:
public function user()
{
    return $this->belongsTo('App\Models\User', 'user_id', 'id');
}

In my Schedule Controller I am using the below which works but I need to narrow down by my results by a where clause:
$users = User::select('name','location','id AS user_id')->has('shift')->get();

Any help is appreciated.


I have multiple packages that make up a CMS built on top of Laravel 10. In this example: a UI package and a core package.
In my core I define this route, which returns a view from my UI package:
Route::get('php-test', function () {
   return view('my-cms::dashboard.home');
});

I want to test this route, so in the composer.json of my core package I add the UI package:
"require-dev": {
    "my-cms/ui": "dev-master"
},

Then I write a test in my core package which contains this test method:
/** @test */
public function test_route_returns_view() : void
{
    $this->withoutExceptionHandling();

    $response = $this->get('php-test');
    $response->assertOk();
    $response->assertViewIs('my-cms::dashboard.home');
}

This returns the following error:

InvalidArgumentException: No hint path defined for [my-cms].

In the ServiceProvider of the UI package I register the views:
public function boot() : void
{
    $this->loadViewsFrom(__DIR__ . '/../resources/views', 'my-cms');
}

How can I test if a route returns a view, when that view is from another package?


I have two laravel 10 projects in the same domain cms and website i access the images and files from cms side that url show domain.com/cms/public/storage/pages/press/root_1683963515doc.pdf  here i remove the public from url and the cms domain like domain.com/cms/public/login without move the file from the public folder how we change the url with out public and whic project htacces file is use to change the url here i write in cms htacces file like
RewriteEngine On
RewriteBase /cms/

RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ public/$1 [L]

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,QSA]

but it not working i put domain.com/cms/login show 404 page, any way to solve this issue?


I'm working on a livewire component that acts as a file browser.
Initially a list of files and folders is passed to the components blade, if the item is a directory an anchor is returned which changes the current path to the items name which essentially 'moves' into the folder by requesting the files for the new path.
If the item is a file, a checkbox is returned like so
<input wire:model="fileList" class="form-check-input" value="latest.log" type="checkbox">

moving between folders and toggeling checkboxes works on the first render without issues, however when moved into another directory the wire:click event is not fired anymore. After changing the components controller numerous of times I noticed the when the view is re-rendered the checkbox is now returned but the attributes are in a different order like so:
<input class="form-check-input" type="checkbox" value="latest.log" wire:model="fileList">

After moving between folders a few times the checkboxes are returned as initially defined and the wire:click event is working as well. What is causing this behaviour? Why would the order change if its strictly defined in a blade templates for-loop like this;
@foreach ($files as $file)
    @if($file['attributes']['is_file'] == 'true')
        <input wire:model="fileList" class="form-check-input" value="{{ltrim($currentPath . '/' .  $file['attributes']['name'], '/')}}" type="checkbox">
    @else
         {{ $file['attributes']['name'] }}
    @endif
@endforeach

My components controller uses this function to move to a new folder;
public function updatePath($path)
    {
        $this->currentPath = ltrim($path, '/');

        $this->getFiles();
        $this->render();
    }

the getFiles() functions is defined like so;
    public function getFiles()
    {
        //redacted
        $this->files = $apiRequest['data'];
    }

It works as intended except for the checkboxes suddnly not fireing an event anymore.


how can I solve it (Laravel 10) so that I can query all the rows and the corresponding "instrument_types" from the 3 tables via a model?
Database and Models:
https://i.sstatic.net/cuY26.png
I call it like this in my controller, but it's obviously not good:
$hangszerek = Hangszer::all();
I would like to receive such json data as a response:
  {
    "h_id": 1,
    "hangszer_nev": "Gitár",
    "brutto_ar": 100000,
    "kep_url": "https://image.com/image1.png",
    "cikkszam": "4792146AG",
    "leiras": "Nagyon fain gitár",
    "tipusok":[
      {
      "t_id":1,
      "tipus_nev":"Type 1"
      },
      {
      "t_id":2,
      "tipus_nev":"Type 2"
      }
    ]
  },
  {
    "h_id": 2,
    "hangszer_nev": "Dob",
    "brutto_ar": 120000,
    "kep_url": "https://image.com/image2.png",
    "cikkszam": "47924636BF",
    "leiras": "Nagyon fain dob",
    "tipusok":[
      {
      "t_id":2,
      "tipus_nev":"Type 2"
      },
      {
      "t_id":3,
      "tipus_nev":"Type 3"
      }
    ]
  }
]```


In my Laravel 10 Breeze app I'm setting up a private Pusher connection. I am using logtoconsole to debug the connection, and any request I put in works, and I can send and receive data. However, when it comes to processing the data inside a callback function, it's no use. What am I doing wrong?
To further explain, using pusher.logToConsole works. However putting any kind of code like, console.log, alert, setting state, etc. Does not work.
The channel is correct as changing it won't do much. My guess is there is something wrong with the event, as changing it to SomeRandomName doesn't yield an error nor different results.
Pusher.logToConsole = true;
window.Echo.private('admin_users').listen('DeliveryListUpdated', (e) => {
        console.log(1111)
        console.log(e)
    });

One of the logs does seem to be a error that could be a cause:
["No callbacks on private-admin_users for pusher:subscription_succeeded"]
I don't know why I am getting this.
This is my event class:
class DeliveryListUpdate implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    /**
     * Create a new event instance.
     */
    public function __construct(
        $message
        //public User $user
    )
    {
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array|Channel|Channel[]
     */
    public function broadcastOn()
    {
        return new PrivateChannel('admin_users');
    }
}

This is my bootstrap.js:
window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
    // wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
    // wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
    // wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
    forceTLS: true,
    // forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
    // enabledTransports: ['ws', 'wss'],
});

.. and this is where i send a request (in my Laravel controller):

    public function activateWeek($id, Request $request) {
        $week = Week::find($id);
        $week->active = true;
        $week->save();

        broadcast(new DeliveryListUpdate(
            ['event_type' => 'remove_user',
                'user_id' => $request->user_id,
            ]))->toOthers();
    }

I tried listeners and event service providers, but I'm not sure if it's the solution for my problem. Did not seem to work for me anyhow.
Thanks in advance!


protected function isPublished(): Attribute
{
    return Attribute::make(
        get: fn($value) => $value ? 'yes' : 'no',
    );
}

As we know that mentioning the return type  as "Attribute" is not necessary until we don't use strict type so before mentioning the return type the accessor wasn't working but when I mentioned the return type it started working why even ?
It should work without mentioning the return type as :Attribute


I have a small query to run in my controller, it works fine in MySQL Workbench
  SELECT
  subprocess_id,
  MAX(CASE WHEN step_no = '1' THEN s_name END) AS first_step,
  MAX(CASE WHEN step_no = '2' THEN s_name END) AS second_step,
  MAX(CASE WHEN step_no = '3' THEN s_name END) AS thrid_step,
  MAX(CASE WHEN step_no = '4' THEN s_name END) AS fourth_step,
  MAX(CASE WHEN step_no = '5' THEN s_name END) AS fifth_step,
  MAX(CASE WHEN step_no = '6' THEN s_name END) AS sixth_step
FROM
  worksteps
  where subprocess_id=8010
GROUP BY
  subprocess_id;

Trying to translate it to Laravel with no success
DB::table("worksteps")
->select("subprocess_id", "max (case when step_no = '1' then s_name end) as `first_step`", "max (case when step_no = '2' then s_name end) as `second_step`", "max (case when step_no = '3' then s_name end) as `thrid_step`", "max (case when step_no = '4' then s_name end) as `fourth_step`", "max (case when step_no = '5' then s_name end) as `fifth_step`", "max (case when step_no = '6' then s_name end) as `sixth_step`")
->where("subprocess_id", "=", 8010)
->groupBy("subprocess_id")
->get();

Getting the error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'max...

I don't have a max column, I used MAX() in the query to avoid error in case there are 2 same steps IDs against one main id.
How could I execute this in my controller show function?


I am using free version of Backpack 5 for Laravel as my admin panel. Also, I am using Laravel 10.13 and PHP 8.2.6. I have been trying to create a feature to add pictures for my blog posts however whenever I save the file it shows in my database following path: C:\wamp64\tmp\phpEF80.tmp However, I need my files to be saved in public/images/news. Please could you help me to solve this problem? I have googled and I could not find even a similar solution. Mainly people have problems with wrong directory, or they cannon open files, but it seems no one had probles with saving files into temporary directory of webserver. Restarting server and cleaning cache or running php artisan optimize does not help. Using public as disk in Controller and Model also create the same issue.
MIGRATION FILE
Schema::create('news', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('article');
            $table->string('main_picture_path');
            $table->timestamps();
        });

MODEL
use CrudTrait;
    use HasFactory;

    protected $fillable = [
        'title',
        'article',
        'main_picture_path'
    ];

    public function setImageAttribute($value)
    {
        $attribute_name = "main_picture_path";
        $disk = "images";
        $destination_path = "news";

        $this->uploadFileToDisk($value, $attribute_name, $disk, $destination_path);
    }

CRUD CONTROLLER
protected function setupCreateOperation()
    {
        CRUD::setValidation(NewsRequest::class);

        CRUD::field('title');
        CRUD::field('article');
        $this->crud->addField([
            'name' => 'main_picture_path',
            'label' => 'main_picture_path',
            'type' => 'upload',
            'upload' => true,
            'disk' => 'images',
        ]);
    }

FILESYSTEMS
'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,
        ],

        'images' => [
            'driver' => 'local',
            'root' => public_path('images'),
        ],

    ]

I need my files to be saved in public/images/news. I have googled and I could not find even a similar solution. It seems no one had problems with saving files into temporary directory of webserver. Restarting server and cleaning cache or running php artisan optimize does not help. Using public as disk in Controller and Model also create the same issue. Also, I tried to write simple debugging code in my modal in the method of setImageAttribute but it did not work at all, nothing was shown as output:
$attribute_name = "main_picture_path";

if (!request()->hasFile($attribute_name)) {
    throw new \Exception('No file was uploaded');
}

if (!request()->file($attribute_name)->isValid()) {
    throw new \Exception('Uploaded file is not valid');
}

throw new \Exception('IT SHOULD WORK');


On the blog page I made a category to show the highlighted category that is selected I used JavaScript to add a class called active but after clicking the category the JavaScript did put the class but after page load the added css is gone so the highlight is also gone.
I want the JavaScript added CSS to not be gone after page load.
JavaScript
const tabs = document.querySelectorAll("[data-tab-target]");
const tabContents = document.querySelectorAll("[data-tab-content]");

tabs.forEach((tab) => {
    tab.addEventListener("click", () => {
        const target = document.querySelector(tab.dataset.tabTarget);
        tabContents.forEach((tabContent) => {
            tabContent.classList.remove("active");
        });
        tabs.forEach((tab) => {
            tab.classList.remove("active");
        });
        tab.classList.add("active");
        target.classList.add("active");
    });
});

category (blade)

            All
            Coding
            Covid-19
            EHR
            Financial Analysis
            Medical Billing
            Patient Engagement
            RCM
            Telehealth
            GGGG
            GGGG


I am currently having some issues setting up some dependency injection for a new service I have made.
I am trying to get PartyRingService to inject into a constructor without me passing it in.
I have tried the following in my PartyRingServiceProvider:
class PartyRingServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->singleton('App\Services\PartyRingService', function ($app) {
            return new PartyRingService();
        });
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        //
    }
}

I have added to config/app.php my new service provider to the providers array:
/*
 * Application Service Providers...
 */
......
App\Providers\PartyRingServiceProvider::class,

And this is the constructor where I am trying to inject my service:
This is the class where I am trying to use my new service in the constructor:
class Party
{
    private PartyRingService $partyRingService;

    public function __construct(PartyRingService $partyRingService)
    {
        $this->partyRingService = $partyRingService;
    }
    ...
}

However, I am getting the following error when I am trying to use PartyService:

ArgumentCountError PHP 8.2.7
10.13.5 Too few arguments to function App\Party::__construct(), 0 passed in
/var/www/html/app/Http/Controllers/PartyController.php on line 28
and exactly 1 expected

This is what line 28 of PartyController looks like:
$party = new Party();
I feel like I am just missing a step here, so if someone could help me identify it, that would be great, thank you.


I am following sanctum documentation from here.  I did all same as described but still it is not working.
I am getting an error when I am generating new token "Call to a member function createToken() on null".
use Illuminate\Http\Request;

Route::post('/tokens/create', function (Request $request) {
    $token = $request->user()->createToken($request->token_name);

    return ['token' => $token->plainTextToken];
});

Here is my code on github https://github.com/farukhaleem/sanctum
I am trying to use sanctum as it is described in the documentation. I am getting createToken() method for generating a token but I am unable to get anyting in $request->user(). I am using thunder client in vscode for getting result. http://127.0.0.1:8000/api/tokens/create is the endpoint, method type is POST. FORM data has token_name with value 'data'


I encountered an error when the user registers, everything is ok and works perfectly, but when the user registers again with the same previous data, it shows this error:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '123456789' for key 'users.users_phone_unique'

and i have no ideo what is wrong in these codes
i'm using laravel 10
this is my register controller
namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'min:10'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'phone' => ['required', 'string', 'max:11'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'phone' => $data['phone'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

this is my user.php
namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

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

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

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'phone',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];
}

this is my create user table migration
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('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('password');
            $table->string('phone')->unique();
            $table->rememberToken();
            $table->timestamps();
        });
    }

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


I'm not sure why I couldn't find it, but I need to get the value of the required parameter in the controller. For example if the route is /route/{param}, and if someone entered /route/123, I want to get 123:
public function some_method(Request $request)
{
    // get {param} value, 123
}

All I've seen is that it's either used for route-model-binding or that it doesn't use the Request (https://laravel.com/docs/10.x/routing#route-model-binding):
use App\Http\Controllers\UserController;
use App\Models\User;

// Route definition...
Route::get('/users/{user}', [UserController::class, 'show']);

// Controller method definition...
public function show(User $user)
{
    return view('user.profile', ['user' => $user]);
}

*But perhaps I don't even need Request $request because I can get it via the request() helper?


I have tried to install multiple different packages and I have failed every time. Let's say I want to add the Wysimark editor to my project. I run npm i --save @wysimark/standalone as described in the documentation. Next, in resources/js/app.js, I add this line:
import { createWysimark } from "@wysimark/standalone";

But what do I do next? When I try to use the createWysimark() function in my Laravel view, I get Uncaught ReferenceError: createWysimark is not defined. Should I include the app.js file into the page somehow? But how? I can't use its path, since it is in the resources folder, right?


I'm using Laravel 10 and I have made a table named pages which stores the all static pages field data of website.
Here is the table:

Now in order to retrieve this data, at the Controller I added this:
use App\Repositories\PageRepository;
use App\Models\Page;

class MainPagesController extends Controller
{
    protected $pageRepository;

    public function __construct(PageRepository $pageRepository)
    {
        $this->pageRepository = $pageRepository;
    }

    public function home()
    {
        $homeInfo = $this->pageRepository->getPageByType('home');
        return view('admin.pages.main.home', compact('homeInfo'));
    }
}

So I made a respository named PageRepository.php which goes like this:
namespace App\Repositories;

use App\Models\Page;

class PageRepository
{
    public function getPageByType(string $pageType)
    {
        return Page::where('pag_type', $pageType)->first();
    }

    public function getPageByName(string $pageName)
    {
        return Page::where('pag_name', $pageName)->first();
    }
}

So it looks nice and perfect but at the Blade, when I do this:
@dd($homeInfo->where('pag_name', 'hero_image')->first()->pag_value)

I get this error:
Attempt to read property "pag_value" on null
However, the pag_name with hero_image has already a value named layer.png and this error occurs for other pag_names as well!
So what's going wrong here? How can I solve this issue?


As far as I know,
when a class extending another class, It's should override all abstract methods of parent class and It can also override non-abstract methods
And also when a class implementing an interface, It's should override all of the parent interface methods
but I've seen a Laravel project that didn't do this

This is the parent interface:
<?php

interface MustVerifyEmail
{
    /**
     * Determine if the user has verified their email address.
     *
     * @return bool
     */
    public function hasVerifiedEmail();

    /**
     * Mark the given user's email as verified.
     *
     * @return bool
     */
    public function markEmailAsVerified();

    /**
     * Send the email verification notification.
     *
     * @return void
     */
    public function sendEmailVerificationNotification();

    /**
     * Get the email address that should be used for verification.
     *
     * @return string
     */
    public function getEmailForVerification();
}

this is the parent class:
<?php

class User extends Model implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail;
}

and this is the child class:
<?php

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    public function activeCode()
    {
        return //...
    }

    public function hasTwoFactor($key)
    {
        return //...
    }

    public function isTwoFactorAuthEnabled()
    {
        return //...
    }
}

How did this happen?


I add a with-success message in the controller but after inserting data in the database, the successful message not showing. Hoping an expert help.
This is my HTML code:
<form action="{{url('/')}}/register" method="post">
  @csrf

      First Name

        <input type="text" id="fn" name="First_Name" placeholder="Enter Your First Name" />

    Last Name

      <input type="text" id="ln" name="Last_Name" placeholder="Enter Your Last Name" />

    E-mail

      <input type="text" id="email" name="email" placeholder="Enter Your Email" required />

</form>

This is my controller:
Registrationform::create($request->all());

return redirect()->route('register')->withSuccess('You have registered successfully!');

This is my route:
Route::get('/register', [Registrationcontroller::class,'register'])->name('register');
Route::post('/register', [Registrationcontroller::class,'store']);


I am trying to make my own custom laravel 10 login/registration because i didn't want to use the breez package because i wanted to learn how do you make a login/registrasion by yourself.
But I cant seem to get past the authentication of the dashboard page.
I am using an if statment if(Auth::check()) on my dashboard function to authenticate the user in the database.
but for me this isn't working because i keep getting the error message from the redirect back to the login page (This only happens when I register a new user into the database) but whenever I try loging in I get the success message from my login function (See code futher down) while still being in the login page.
AuthController (Dashboard):
public function dashboard(): View
    {
        if(Auth::check()) {
            return view('auth.dashboard');
        }

        return view('auth.login')->with('error', 'You are not allowed to access');
    }

AuthController (Login):
public function loginPost(Request $request): RedirectResponse
    {
        $request->validate([
           'email' => 'required',
           'password' => 'required'
        ]);

        $credentials = $request->only('email', 'password');

        if(Auth::attempt($credentials)) {

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

            return redirect()->intended(route('dashboard'))->with('success', 'You have successfully logged in');
        }

        return redirect(route('login'))->with('error', 'Oppes! You have entered invalid credentials');
    }

web.php
Route::get('/register', [AuthController::class, 'register'])->name('register');
Route::post('/register', [AuthController::class, 'registerPost'])->name('register.post');
Route::get('/login', [AuthController::class, 'login'])->name('login');
Route::post('/login', [AuthController::class, 'loginPost'])->name('login.post');
Route::get('/dashboard', [AuthController::class, 'dashboard'])->name('dashboard');
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth')->name('logout');

I havn't found any solution yet so if someone can help me it will be very appreciated.


I'm able to add more data to the authenticated user by using the Laravel Global Scopes what I didn't know is that this forces the data in every relationship with the model User.
My user class is something like this:
class User extends Authenticatable
{
    protected static function booted()
    {
        static::addGlobalScope('subscription', function (Builder $builder)
        {
            $builder->with('subscription.lastpayment');
            $builder->with('tickets');
        });
    }
}

Which translates to being able to access auth()->user()->subscription, auth()->user()->subscription->lastpayment and auth()->user()->tickets.
But now if I use a model that has a relationship with the user model, such as:
$tickets = \App\Models\Tickets::with('user')
    ->with('lastmessage')
    ->with('lastmessage.user')
    ->where('subscription_id', auth()->user()->subscription_id)
    ->get();

Both with('user') and with('lastmessage.user') are running the global scope and querying subscriptions, lastpayment & tickets tables.
How can I avoid this? This is performing multiple queries unnecessarily.


I am working in:

Livewire 3, Laravel version is 10.10, PHP 8.2.4

I am trying to bind simple data with simple code but its not working, I am not sure why? Can you please help me? Livewire actions functions on click working, but data binding not updating data while typing in input field.
user.blade.php
<div>
    <input type="text" wire:model="name" id="description">
    Hi! My name is {{ $name }}
    <script>
        console.log("Livewire JavaScript loaded and working!");
    </script>
</div>

User.Php
namespace App\Livewire;

use Livewire\Component;

class User extends Component
{

    public $name = 'ali';

    public function render()
    {

        return view('livewire.user');
    }
}

On page load Output shows "ali" in the input field, but when I type more characters in input fields its not updating variable value.


I have been using laravel framework version 10 for in-house web application development, which will run on intranet not internet.
I downloaded and installed xampp having php version 8.1.17, i downloaded and install composer with selecting php.exe of php version 8.1.17 installed at "C:/xampp/php"
after that i have downloaded laravel 10 project using composer at path "C:/xampp/htdocs/project".
I have valid ssl certificate for my intranet domain for example abc.example.com, now at "C:/xampp/apache/extra/httpd-vhosts.conf", i have placed following code to configure ssl certificate
<VirtualHost abc.example.com:444>
    DocumentRoot "C:/xampp/htdocs/project"
    ServerName abc.example.com:444
    SSLEngine on
    SSLCertificateFile "conf/ssl.crt/22112022.cer"
    SSLCertificateKeyFile "conf/ssl.crt/22112022-rsa.key"
    SSLProtocol all -SSLv3
    <Directory "C:/xampp/htdocs/project">
        Options All
    AllowOverride All
    Require all granted
    </Directory>
</VirtualHost>

Now i am running my laravel project with command "php artisan serve --host=abc.example.com --port=444"
when i am accessing my application using url "https://abc.example.com:444/", it is showing directory listing of my project at "C:/xampp/htdocs/project", Please check image below :

My laravel project is not executing, instead directory listing is displaying, ssl is resolving as expected. can anyone guide me with this ? i am new to laravel but not xampp.


I am using Laravel Framework 10.15.0.
I am trying to load my API-Keys the following way:
        $apiKeyOpenAI = env('OPENAI_API_KEY');
        $client = OpenAI::client($apiKeyOpenAI);

In my .env file the api key is clearly defined:
OPENAI_API_KEY=xx-xxxxxxxxxxxxxxxxxxxxxxx
However, when executing my application on the server I get that the $apiKeyOpenAI is null.
Still my .env file has the OPENAI_API_KEY in it. I checked this!
I tried to clear my cache php artisan config:clear , I still get the error:

   TypeError

  OpenAI::client(): Argument #1 ($apiKey) must be of type string, null given, called in /var/www/demo-website/app/Console/Commands/AdminCommand.php on line 151

  at vendor/openai-php/client/src/OpenAI.php:13
      9▕ {
     10▕     /**
     11▕      * Creates a new Open AI Client with the given API token.
     12▕      */
  ➜  13▕     public static function client(string $apiKey, string $organization = null): Client
     14▕     {
     15▕         return self::factory()
     16▕             ->withApiKey($apiKey)
     17▕             ->withOrganization($organization)

  1   app/Console/Commands/AdminCommand.php:151
      OpenAI::client()

  2   app/Console/Commands/AdminCommand.php:39
      App\Console\Commands\AdminCommand::generateContentUsingOpenAI()

Any suggesitons what I am doing wrong?
I appreciate your replies!
UPDATE
After deploying to the server I need to run this script so that it seems to work:
Route::get('/clear', function() {
    Artisan::call('cache:clear');
    Artisan::call('config:clear');

    return "Cache, Config is cleared";
})->middleware(['auth', 'admin']);

When deploying this script is also automatically run:
#!/bin/sh
set -e

echo "Deploying application ..."

# Enter maintenance mode
(php artisan down) || true
    # Update codebase
    git fetch origin deploy
    git reset --hard origin/deploy

    # Install dependencies based on lock file
    composer install --no-interaction --prefer-dist --optimize-autoloader

    # Migrate database
    php artisan migrate --force

    # Note: If you're using queue workers, this is the place to restart them.
    # ...

    # Clear cache
    # php artisan optimize

    php artisan config:cache
    php artisan route:clear
    php artisan route:cache
    php artisan view:clear
    php artisan view:cache
    php artisan auth:clear-resets
    php artisan cache:clear
    php artisan config:clear

    # Generate sitemap
    # php artisan sitemap:generate

    # Reload PHP to update opcache
    echo "" | sudo -S service php8.1-fpm reload
# Exit maintenance mode
php artisan up

echo "Application deployed!"


I have 2 separate columns for the date: the date itself in YYYY-mm-dd format, and a time column in time(7) datatype, for example 11:15:10.0000000
How can I check for rows that are in the future?
I can get the first part, for the day itself:
MyModel::where('date', '>=', Carbon::today())->get()

But when I try adding the time it doesn't work:
MyModel::where('date', '>=', Carbon::today())->where('time', '>', Carbon::now()->format('H:i'))->get()

because they are separate and now even though the date is in the future, the time is separate so there may be a situation where the time doesn't match. So I somehow need to have both the date and the time related to it in the future, not separately


I have an eloquent model in Laravel that I would like to mark an user_id attribute as deprecated using the @deprectated tag in PHPDoc.
I can add the @property tag to my model to document user_id but if I try to add the deprecated tag my IDE (vscode) still does not inform me that the attribute is deprecated.
Looking at the documentation I can't see any way of combining both @property and @deprecated.
Does anyone know a way for me to document this correctly?
The model
/**
 * App\Task\Models\Task
 *
 * @property null|int $user_id
 */
final class Task extends Model
{
    protected $guarded = ['id'];

    protected $casts = [
        'user_id' => 'int',
    ];

    protected $fillable = [
        'user_id',
    ];

}

Attempted Code
@property @deprecated null|int $user_id
Versions

Laravel: 10
PHP: 8.2
VSCode: 1.80.2
VSCode extension PHP Intelephense: 1.9.5


I'm currently developing a Laravel package. The service provider of this package relies on magic methods config('my.config') and config_path('../my-config.php') defined in Illuminate/Foundation/helpers.php. PHPStorm notifies that it can't find these magic methods.

How to make sure that these dependencies resolve?
Is it possible to check which package installed a certain namespace in Composer?

Things I tried:

The standalone package: https://packagist.org/packages/illuminate/foundation This package is apparently abandoned. No alternatives provided
Install the entire laravel/framework. This conflicts with the application with which I try to install the package. I also want to avoid installing unnecessary dependencies in the package.
I tried a bunch of packages from Illuminate: config, container and contracts. When I check the vendor folder, I don't see any foundation directory in the Illuminate directory


I'm using the use Illuminate\Validation\Rules\Password; on the Password Validation rules and the use Illuminate\Support\Facades\Password; for the password reset the application is displaying error then I put the two of them together.
<?php

    namespace App\Http\Controllers;

    use Carbon\Carbon;
    use App\Models\User;
    use Illuminate\Support\Str;
    use Illuminate\Http\Request;
    use App\Mail\PasswordResetMail;

    use Illuminate\Validation\Rule;
    use Illuminate\Support\Facades\DB;
    use App\Http\Controllers\Controller;
    use function GuzzleHttp\Promise\all;
    use Illuminate\Support\Facades\Hash;
    use Illuminate\Support\Facades\Mail;
    use Illuminate\Auth\Events\PasswordReset;
    use Illuminate\Validation\Rules\Password;
    use Illuminate\Support\Facades\Password;

    class UserController extends Controller
    {
        // Show Register/Create Form
        public function create()
        {
            return view('users.register');
        }

    // Create New User
    public function store(Request $request)
    {
        $formFields = $request->validate([
            'name' => ['required', 'min:3', 'max:255', Rule::unique('users', 'name')],
            'email' => ['required', 'email', Rule::unique('users', 'email')],
            'password' =>
            [
                'required', 'confirmed',
                Password::min(8)
                    ->max(255)
                    ->mixedCase()
                    ->letters()
                    ->numbers()
                    ->symbols()
                    ->uncompromised(),
            ],
        ]);

Here for the Password Reset
// Submit Forgot Password
    public function forgotSubmit(Request $request)
    {
        $request->validate(['email' => 'required|email']);

        $status = Password::sendResetLink(
            $request->only('email')
        );

        return $status === Password::RESET_LINK_SENT
            ? back()->with(['status' => __($status)])->with('reset', 'We have e-mailed your password reset link!')
            : back()->withErrors(['email' => __($status)]);
    }


Is it possible to validate and compare between 2 time inputs using the available rules, or I will have to have custom rule in this case?
I have 2 time inputs - start and end. They are in the format HH:mm and I need the end date to be greater than the start date.
Is there a combination I can have with the available rules to do that, or I should just create a custom rule?


I am new to Laravel and here is my setup:

I have a companies table which is linked to a plans table (plan_id)
I have a function that seed the plans table with very specific data
I have created a factory for the Company model but not for the Plan model as I don't want random data for this model (I have 3 plans with prices)

My issue is that when I run the Company factory, it creates new Plan entries instead of using the existing ones.
Here is my DatabaseSeeder:
/**
 * Seed the application's database.
 */
public function run(): void
{
    // Create the plans.
    $this->createPlans();

    Company::factory()
        ->count(3)
        ->create();
}

/**
 * Create the plans.
 *
 * @return void
 */
private function createPlans(): void
{
    Plan::create([
        'name' => __('Free'),
        'amount' => 0.00,
    ]);

    Plan::create([
        'name' => __('Pro'),
        'amount' => 99.95,
    ]);

    Plan::create([
        'name' => __('Business'),
        'amount' => 199.95,
    ]);
}

And my CompanyFactory:
public function definition(): array
{
    return [
        'plan_id' => fake()->randomElement(Plan::all()->pluck('id')->toArray()),
        'name' => fake()->company(),
        'plan_status' => fake()->randomElement(['active', 'pending', 'canceled']),
    ];
}

Each time I seed the database, it creates x new entries for the plans instead of using existing entries. I have tried many things, but I can't get it to work... Could somebody point me in the right direction?


I just recently started working with Laravel 10.
I'm using nwidart/laravel-modules v10 for creating modules in my new project.
Since the project is going to be an SaaS product, I am also using stancl/tenancy for multiple tenants.
I have a config file for every tenant and want to dynamically activate or deactivate the modules from the tenants config.
The Config-Key is ActivatedModules and looks like this:
'ActivatedModules' => [
    ['id' => 'homepage', 'name' => 'Homepage', 'icon' => 'homepage', 'visibility' => 'extern', 'no' => 1], // Homepage
],

My idea was to uses the method Module::all() of use Nwidart\Modules\Facades\Module; as mentioned in the docs.
My Problem is that there is an error saying that this funcion is not existing and on the website comes the following error:
Fatal error: Uncaught RuntimeException: A facade root has not been set. in
D:\Programmieren\referee365\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:350
Stack trace: #0
D:\Programmieren\referee365\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\RegisterErrorViewPaths.php(16):
Illuminate\Support\Facades\Facade::__callStatic('replaceNamespac...',
Array) #1
D:\Programmieren\referee365\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php(674):
Illuminate\Foundation\Exceptions\RegisterErrorViewPaths->__invoke() #2
D:\Programmieren\referee365\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php(655):
Illuminate\Foundation\Exceptions\Handler->registerErrorViewPaths() #3
D:\Programmieren\referee365\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php(586):
Illuminate\Foundation\Exceptions\Handler->renderHttpException(Object(Symfony\Component\HttpKernel\Exception\HttpException))
#4 D:\Programmieren\referee365\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php(492):
Illuminate\Foundation\Exceptions\Handler->prepareResponse(Object(Illuminate\Http\Request),
Object(Symfony\Component\HttpKernel\Exception\HttpException)) #5
D:\Programmieren\referee365\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php(409):
Illuminate\Foundation\Exceptions\Handler->renderExceptionResponse(Object(Illuminate\Http\Request),
Object(RuntimeException)) #6
D:\Programmieren\referee365\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(509):
Illuminate\Foundation\Exceptions\Handler->render(Object(Illuminate\Http\Request),
Object(RuntimeException)) #7
D:\Programmieren\referee365\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(148):
Illuminate\Foundation\Http\Kernel->renderException(Object(Illuminate\Http\Request),
Object(RuntimeException)) #8
D:\Programmieren\referee365\public\index.php(51):
Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#9 D:\Programmieren\referee365\vendor\laravel\framework\src\Illuminate\Foundation\resources\server.php(16):
require_once('D:\\Programmiere...') #10 {main} thrown in
D:\Programmieren\referee365\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php
on line 350

I hope some of you can help me with this, in the best case, easy problem.


when I can install Laravel password, I got this error, what exactly should I do to solve this problem, if you can help me step by step to solve the problem
 composer require laravel/passport
https://repo.packagist.org could not be fully loaded (curl error 6 while downloading https://repo.packagist.org/packages.json: Could not resolve host: repo.packagist.org), package information was loaded from the local cache and may be out of date
./composer.json has been updated
Running composer update laravel/passport
Loading composer repositories with package information
https://repo.packagist.org could not be fully loaded (curl error 6 while downloading https://repo.packagist.org/packages.json: Could not resolve host: repo.packagist.org), package information was loaded from the local cache and may be out of date
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel/passport[v11.5.0, ..., v11.8.4] require league/oauth2-server ^8.2 -> satisfiable by league/oauth2-server[8.2.0, ..., 8.5.3].
    - laravel/passport[v11.8.5, ..., v11.8.8] require lcobucci/jwt ^4.3|^5.0 -> satisfiable by lcobucci/jwt[4.3.0, 5.0.0].
    - league/oauth2-server[8.5.2, ..., 8.5.3] require lcobucci/jwt ^4.3 || ^5.0 -> satisfiable by lcobucci/jwt[4.3.0, 5.0.0].
    - laravel/passport[v0.1.0, ..., v0.2.4, v1.0.0, ..., v1.0.18, v2.0.0, ..., v2.0.11, v3.0.0, ..., v3.0.2, v4.0.0, ..., v4.0.3, v5.0.0, ..., v5.0.3, v6.0.0, ..., v6.0.7, v7.0.0, ..., v7.5.1] require guzzlehttp/guzzle ~6.0 -> found guzzlehttp/guzzle[6.0.0, ..., 6.5.8] but it conflicts with your root composer.json require (^7.2).
    - laravel/passport[v8.0.0, ..., v8.5.0, v9.0.0, ..., v9.3.2] require php ^7.2 -> your php version (8.2.0) does not satisfy that requirement.
    - laravel/passport v9.4.0 requires illuminate/auth ^6.18.31|^7.22.4 -> found illuminate/auth[v6.18.31, ..., v6.20.44, v7.22.4, ..., v7.30.6] but these were not loaded, likely because it conflicts with another require.
    - laravel/passport[v10.0.0, ..., v10.0.1] require php ^7.3 -> your php version (8.2.0) does not satisfy that requirement.
    - laravel/passport[v10.1.0, ..., v10.2.2] require illuminate/auth ^8.2 -> found illuminate/auth[v8.2.0, ..., v8.83.27] but these were not loaded, likely because it conflicts with another require.
    - laravel/passport[v10.3.0, ..., v10.3.2] require illuminate/auth ^8.2|^9.0 -> found illuminate/auth[v8.2.0, ..., v8.83.27, v9.0.0, ..., v9.52.15] but these were not loaded, likely because it conflicts with another require.
    - laravel/passport[v10.3.3, ..., v10.4.2] require illuminate/auth ^8.37|^9.0 -> found illuminate/auth[v8.37.0, ..., v8.83.27, v9.0.0, ..., v9.52.15] but these were not loaded, likely because it conflicts with another require.
    - laravel/passport[v11.0.0, ..., v11.4.0] require illuminate/auth ^9.0 -> found illuminate/auth[v9.0.0, ..., v9.52.15] but these were not loaded, likely because it conflicts with another require.
    - league/oauth2-server[8.2.0, ..., 8.5.1] require psr/http-message ^1.0.1 -> found psr/http-message[1.0.1, 1.1] but the package is fixed to 2.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.
    - lcobucci/jwt[4.3.0, 5.0.0] require ext-sodium * -> it is missing from your system. Install or enable PHP's sodium extension.
    - Root composer.json requires laravel/passport * -> satisfiable by laravel/passport[v0.1.0, ..., v0.2.4, v1.0.0, ..., v1.0.18, v2.0.0, ..., v2.0.11, v3.0.0, v3.0.1, v3.0.2, v4.0.0, v4.0.1, v4.0.2, v4.0.3, v5.0.0, v5.0.1, v5.0.2, v5.0.3, v6.0.0, ..., v6.0.7, v7.0.0, ..., v7.5.1, v8.0.0, ..., v8.5.0, v9.0.0, ..., v9.4.0, v10.0.0, ..., v10.4.2, v11.0.0, ..., v11.8.8].

To enable extensions, verify that they are enabled in your .ini files:
    - F:\xampp\php\php.ini
You can also run `php --ini` in a terminal to see which files are used by PHP in CLI mode.
Alternatively, you can run Composer with `--ignore-platform-req=ext-sodium` to temporarily ignore these required extensions.

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require laravel/passport:*" to figure out if any version is installable, or "composer require laravel/passport:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

I use Windows 10 and xampp or the following specifications:
Apache/2.4.54 (Win64) OpenSSL/1.1.1p PHP/8.2.0
Database client version: libmysql - mysqlnd 8.2.0
PHP extension: mysqli Documentation curl Documentation mbstring Documentation
PHP version: 8.2.0
enter image description here
Please help me to solve this problem if you can


This is the code from my Laravel application:
public function sendNotifications()
    {
        $matchingSubscriptions = DB::table('tournament_match_plan')
            ->join('push_subscriptions', 'push_subscriptions.age_group', '=', 'tournament_match_plan.league')
            ->where('tournament_match_plan.start', '=', '11:20:00')
            ->where('tournament_match_plan.team_1', '=', 'push_subscriptions.club')
            ->orwhere('tournament_match_plan.team_2', '=', 'push_subscriptions.club')
            ->get();

        dd($matchingSubscriptions);
}

Here is the debug message:
Illuminate\Support\Collection {#751 ▼ // app\Http\Controllers\Guests\GuestsPushController.php:97
  #items: []
  #escapeWhenCastingToString: false
}

Why don't I get any result from my Laravel Code?
I've tried the same query in phpMyAdmin:
SELECT *
FROM tournament_match_plan
JOIN push_subscriptions ON push_subscriptions.age_group = tournament_match_plan.league
WHERE tournament_match_plan.start = '11:20:00'
AND (tournament_match_plan.team_1 = push_subscriptions.club OR tournament_match_plan.team_2 = push_subscriptions.club);

With the above code, I get the correct result.


I've been developing in Laravel 10 in my local, and seeing the web using php artisan serve then I uploaded all those files to a webserver, updated .env file with the new DB and url data, and tried a couple of times and work ok!! But after some hours, it stoped working. I can access the root folder and see the Laravel main screen, but if I want to access some controller it says "Target class  does not exists".
I guess it worked on local, and then on the server the firsts times, until some cache refreshed and then it didn't work anymore.
I accessed the webserver through ssh and run:
composer update
composer install --optimize-autoloader --no-dev as
php artisan cache:clear
php artisan route:clear
php artisan optimize:clear

But nothing seems to work. Any idea what could be happening?
EDIT: If I add add the namespace in the route like this
Route::get('/landing', 'App\Http\Controllers\LandingController@index');

instead of this:
Route::get('/landing', 'LandingController@index');

it works fine! But I need to know WHY on local it works without adding the namespace and in the webserver it doesn't!
EDIT 2: I move this to it's own subdomain, so it isn't in a subfolder anymore, and it still happens.


I have created a custom class in laravel 10 located in:
App\Helpers\CompletedOrders

The class contain this code:
<?
namespace App\Helpers\CompletedOrders;

class DeliverOrdersByMail
{

    public static function DeliverOrdersToCustomerMail($OrderID)
    {
        return "mail ok ". $OrderID;
    }

}

When I try to call the class on a file:
use App\Helpers\CompletedOrders\DeliverOrdersByMail;

Route::get('test', function(){
    DeliverOrdersByMail::DeliverOrdersToCustomerMail("fgzefef");
});

I'm getting an error that the class is not found!

Class "App\Helpers\CompletedOrders\DeliverOrdersByMail" not found

Any solution please?


Laravel 10 showing error Exception Illuminate\Database\QueryException
I am using Laravel 10 and I am trying to add a new column in the table students, using these below steps in the terminal.

Step 1: php artisan make:migration update_student_table --table=students

Step 2: in the 2023_08_17_055949_update_student_table.php file add the code

https://prnt.sc/fdGTj1t_3iIJ

Step 3: php artisan migrate run this command

Step 4: in the terminal, it is showing the Error.

enter image description here
I am trying to add a new column in the table, but showing the below error
exception
enter image description here


I am using Laravel 10. Basically I try to pass the user name to the view. I used to do it in the following way:
$user_name = DB::table('users')->select('name')->where('id', $id)->get();

Then I use it in the view {{$user_name[0]->name}}.
It shows special characters as desired. However, as a quicker solution to get the user name I decided to use
$user_name = User::where('id', $id)->pluck('name');

It shows some special characters B\u00fcy\u00fck instead of Büyük, for example, when I use it {{$user_name}} in my view.
Is there any missing part in my code?


Is it possible to have eager loading without $append attributes? I have following code:
Product model:
public function category(): BelongsTo
    {
        return $this
            ->belongsTo(ProductCategory::class, 'product_category_id');
    }

public static function adminTableData(): Builder
    {
        return self::query()->select('*')
            ->with(['category' => function($query)
            {
                return $query->select('id', 'name');
            }]);
    }

Company model:
protected $appends = [
        'admin_table_logo',
        'edit',
        'remove',
    ];


I am using Laravel 10.
I am utilizing casting for a JSON column in the following manner:
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
  protected $casts = [
    'meta' => 'collection', // here
  ];
}

When attempting to update a value within a collection directly, for instance:
$model->meta->put('test', 100);
$model->save();

Nothing occurs.
When I assign the variable as it is, it functions correctly.
$model->meta = ['test' => 100];
$model->save();

However what if I only need to update/add a single element?
I have discovered the following workaround, but is this the intended behavior?
$meta = $model->meta;
$meta->put('test', 100);
$model->meta = $meta;
$model->save();

It appears that only direct assignment works in such a case, and it seems that the cast collection does not support any of its write functionality.


I'm writing a feature test and noticed that the session ID value changes after every request.
For instance, each dumped value will be different:
dump(session()->getId());

$response = $this->get('/?param=foo');

dump(session()->getId());

$response = $this->get('/?param=foo');

dump(session()->getId());

This issue doesn't seem to happen outside of the testing environment. I can reload a page in the browser and the session ID remains consistent.
This is my web middleware group, which is pretty standard out of the box:
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,

I'm running this Laravel app on Valet on Mac with zero custom PHP configuration changes. Just whatever Homebrew provides with php@8.1.
Here are the session values from php -i:
session.auto_start => Off => Off
session.cache_expire => 180 => 180
session.cache_limiter => nocache => nocache
session.cookie_domain => no value => no value
session.cookie_httponly => no value => no value
session.cookie_lifetime => 0 => 0
session.cookie_path => / => /
session.cookie_samesite => no value => no value
session.cookie_secure => 0 => 0
session.gc_divisor => 1000 => 1000
session.gc_maxlifetime => 1440 => 1440
session.gc_probability => 1 => 1
session.lazy_write => On => On
session.name => PHPSESSID => PHPSESSID
session.referer_check => no value => no value
session.save_handler => files => files
session.save_path => no value => no value
session.serialize_handler => php => php
session.sid_bits_per_character => 5 => 5
session.sid_length => 26 => 26
session.upload_progress.cleanup => On => On
session.upload_progress.enabled => On => On
session.upload_progress.freq => 1% => 1%
session.upload_progress.min_freq => 1 => 1
session.upload_progress.name => PHP_SESSION_UPLOAD_PROGRESS => PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.prefix => upload_progress_ => upload_progress_
session.use_cookies => 1 => 1
session.use_only_cookies => 1 => 1
session.use_strict_mode => 0 => 0
session.use_trans_sid => 0 => 0
session.trans_sid_hosts => no value => no value
session.trans_sid_tags => a=href,area=href,frame=src,form= => a=href,area=href,frame=src,form=

In my phpunit.xml file:
<server name="SESSION_DRIVER" value="array"/>

What could cause the session to be regenerated every time?


I am upgrading a Laravel 5.2 site to 10.20.
I followed the official documentation to encrypt/decryt the data the Laravel 10.x way as it was done differently on 5.2 (see it used the trait Encryptable).
When retrieving encrypted data from the same database (with the same APP_KEY) in Laravel 5.2 I get Hello World whereas on 10.20 I get s:11:"Hello World".
The other attributes that are not encrypted are shown correctly.
I searched the web for that but did not found anything pertaining to that issue. ChatGPT told me it was linked to serialization but even with that keyword I did not find the problem described somewhere.
In my model the attributes to be encrypted are cast like this :
        protected $casts = [
        'my_not_encrypted_attribute' => 'boolean',
        'my_encrypted_attribute_string' => 'encrypted'
    ];

Can you tell me how to get rid of that prefix and only get the actual payload as in L5.2 ?
Thanks for your help!
EDIT :
Manually defining the accessors in my model requires the use of unserialize() to get clean data :
    protected function myEncryptedAttributeString(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => unserialize(Crypt::decryptString($value)),
        );
    }

So it would mean that the data stored in the database were serialized before being stored.That's weird because the Encryptable trait shows no trace of  serialize in the setters :
public function setAttribute($key, $value) {
        if (in_array($key, MyModel::getEncryptableAttributes())) {
            $value = Crypt::encrypt($value);
        }

        return parent::setAttribute($key, $value);
    }

Nor can I find trace of unserialize in the getters (although for the same database the output was clean) :
public function getAttribute($key) {
        $value = parent::getAttribute($key);
        //[...]
        $decrypted = Crypt::decrypt($value);
        //[...]
        return $decrypted;
}


When I retrieve data directly from the model using the following approach:
Contact::where('company_id', auth()->user()->company_id)->get()

The query looks like this:
select * from "contacts" where "company_id" = 'xxx'

But when I retrieve data through direct relations like this:
auth()->user()->company->contacts

The query looks like this and takes longer:
select * from "contacts" where "contacts"."company_id" = 'xxx' and "contacts"."company_id" is not null

It adds the additional;
and "contacts"."company_id" is not null

part, which affects performance negatively. What should I do to prevent this? Querying directly from models without using relations anywhere also doesn't seem very logical and clean.
Note: company_id is indexed.


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