mteb/FreshStackRetrieval huggingface dataset:
I'm trying to allow a user to Unsubscribe from a email link via the server side.
Simply want them to click the link, add a column to my table and show them a page that tells them they have been unsubscribed.
The link looks like this:
https://mysite.test/unsubscribe-confirm/eyJpdiI6Ims3Y3RJdHhvWTgyNGVLais1UXlzdlE9PSIsInZhbHVlIjoiUUF0NFZUUkNqTklmTTExTVRmZEdyaEUvN1kzcXpLNmNhRit3enpPNDE0ak5xalRaa1JQQS91elBCazIzTWFxayIsIm1hYyI6IjMzZDM4MDUwNTYzZjY1ZjQ4OTEyNDI3ZjJhY2M4NzgxNzgwMDFiMGQ2NjQ0ZjFiMGFjNGJlNjg3YzY0Zjc5NTkiLCJ0YWciOiIifQ==/1

In my job JobToSendEmails I'm creating the $unsubscribeLink like this:
// Generate token
$unsubscribeToken = encrypt($sponsor->email);
// Generate unsubscribe link
$unsubscribeLink = route('unsubscribe.confirm', ['token' => $unsubscribeToken, 'campaign_id' => $emailCampaign->id]);

And then passing to my email like this:
Mail::to($sponsor->email)->send(new EmailToUsers(
...
$unsubscribeLink
));

Then in the EmailToUsers view I have this line:
If you no longer wish to receive these emails, you can [unsubscribe]({{ $unsubscribeLink }}) at any time.

The link goes to this route:
Route::post('/unsubscribe-confirm/{token}/{campaign_id}', [EmailPreferenceController::class, 'confirmUnsubscribe'])->name('unsubscribe.confirm');

Then in the EmailPreferenceController the confirmUnsubscribe method looks like this:
    public function confirmUnsubscribe()
    {
        $token = Request::get('token');
        $user  = User::findByToken($token);
        if ($user) {
            $emailCampaignId         = Request::get('email_campaign_id');
            $emailCampaignPreference = EmailCampaignPreference::updateOrCreate(
                [
                    'user_id'           => $user->id,
                    'email_campaign_id' => $emailCampaignId,
                ],
                [
                    'opt_out' => true,
                    'email'   => $user->email,
                ]
            );

            return redirect()->route('unsubscribe');
        }
        Log::error('User not found by token: ' . $token);

        return response()->view('errors.404', [], 404);
    }

findByToken looks like this:
public static function findByToken($token): User
  {
    $email = decrypt($token);
    return static::where('email', $email)->first();
  }

When I click the unsubscribe link in the email, I get the error:

Symfony \Component \HttpKernel \Exception \MethodNotAllowedHttpException
"The GET method is not supported for route
unsubscribe-confirm/eyJpdiI6Ims3Y3RJdHhvWTgyNGVLais1UXlzdlE9PSIsInZhbHVlIjoiUUF0NFZUUkNqTklmTTExTVRmZEdyaEUvN1kzcXpLNmNhRit3enpPNDE0ak5xalRaa1JQQS91elBCazIzTWFxayIsIm1hYyI6IjMzZDM4MDUwNTYzZjY1ZjQ4OTEyNDI3ZjJhY2M4NzgxNzgwMDFiMGQ2NjQ0ZjFiMGFjNGJlNjg3YzY0Zjc5NTkiLCJ0YWciOiIifQ==/1.
Supported methods: POST."

What can I do to fix this? I'm using a Post method on the route. I would like to keep this format in the email, [unsubscribe]({{ $unsubscribeLink }})
Any help would be appreciated.
I want to remove old images in my public folder when he want to change him profile photo.
ProfileController:
if($request->hasFile('image')){
    $request->validate([
        'image' => 'image|mimes:jpeg,png,jpg,svg|max:2048'
    ]);
            
    $imageName = $request->user()->id.'-'.time().'.'.$request->image->extension();
    $request->image->move(public_path('users'), $imageName);
    $path = "users/".$imageName;
    $request->user()->image = $path;
    $request->user()->save();
}

i tried somethings but i cant do it.
Thanks for your replys.
I made this route:
Route::resource('questionnaire_correction/{id}', QuestionnaireCorrectionController::class)->only(['create', 'store']);

Using this route, I get Route [questionnaire_correction.create] not defined..
Checking the routes with php artisan r:l --path=quesionnaire I get:
POST            questionnaire_correction/{questionnaireid} .................... {questionnaireid}.store › QuestionnaireCorrectionController@store
GET|HEAD        questionnaire_correction/{questionnaireid}/create ............. {questionnaireid}.create › QuestionnaireCorrectionController@create

Somehow, it is creating the route name {questionnaireid}.store. I am using Laravel 10.
Creating the routes like this works:
Route::get('/questionnaire_correction/{questionnaireid}', [QuestionnaireCorrectionController::class, 'create'])->name('questionnaire_correction.create');
Route::post('/questionnaire_correction/{questionnaireid}', [QuestionnaireCorrectionController::class, 'store'])->name('questionnaire_correction.store');
after updating to laravel 10, i cant perform raw query like this:
$statement = 'SELECT';
    foreach ($tables = collect(availableTables()) as $name => $table_name) {
        if ($tables->last() == $table_name) {
            $statement .= "( SELECT COUNT(*) FROM $table_name) as {$table_name}";
        }
        else {
            $statement .= "( SELECT COUNT(*) FROM $table_name) as {$table_name}, ";
        }
    }
    $query  = DB::select(DB::raw($statement));

this returns me the following error:
PDO::prepare (): Argument #1 ($query) must be of type string, Illuminate\Database|Query\ Expression given

what should i do to fix this issue
When I start the run docker and meilisearch container doesn't run with this error :

2023-04-10 17:23:44 Error: Your database version (1.0.2) is incompatible with your current engine version (1.1.0).
2023-04-10 17:23:44 To migrate data between Meilisearch versions, please follow our guide on https://docs.meilisearch.com/learn/update_and_migration/updating.html

When I run my project yesterday everything was good but today I can't start the run meilisearch.
I was early into working on a Laravel 10/Inertia 1/Vue 3 SSR app, and I noticed a Hydration node mismatch error show up out of nowhere. After a fair bit of removing things, I was left with the following:
web.php:
Route::get('/', function () {
    return Inertia::render('Welcome');
});

Layout.vue:
<template>
    <div>
        <slot/>
    </div>
</template>

Welcome.vue:
<template>
    <section>
        <h1 class="text-3xl">Hello, World!</h1>
    </section>
</template>

Removing the layout from app.js fixes it, but I don't really see how. Additionally, it seems that adding the layout by just using it as a component, works fine.
I want to connect my terminal to sail for running commands and edit files in sail containers.
I found that I can execute php artisan commands like:
sail artisan migrate replacing php to sail.
But I want to get into: /var/www/project in container to execute php artisan migrate
What aliases exists for this?
I watched a tutorial on youtube on how to return datas from database with eloquent. it worked for the basics but i dont know how to join the foreign keys from beasiswas with the primary key in mitras. I tried to import the tables models into the resource file but it says that the "id" column names are the same for both tables. but when i specify which id is which with something like "beasiswas.id" and "mitras.id", it say that it doesnt recognize the "beasiswas". These are my codes.
App\Http\Resources\V1\BeasiswaResource
<?php

namespace App\Http\Resources\V1;
use App\Models\Beasiswa;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class BeasiswaResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $beas = Beasiswa::join('mitras','beasiswas.id','=','mitras.id')->get();
        
        
        return [
            'idBeasiswa'=>$beas->beasiswas.id,
            'idMitra'=>$beas->id_mitra,
            'deskripsi'=>$beas->deskripsi,
            'angkatanAwal'=>$beas->angkatan_awal,
            'angkatanAkhir'=>$beas->angkatan_akhir,
            'semMin'=>$beas->sem_min,
            'semMax'=>$beas->sem_max,
            'status'=>$beas->status
        ];
    }
}

App\Http\Controllers\Api\V1
<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Beasiswa;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreBeasiswaRequest;
use App\Http\Requests\UpdateBeasiswaRequest;
use App\Http\Resources\V1\BeasiswaResource;
use App\Http\Resources\V1\BeasiswaCollection;

class BeasiswaController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return new BeasiswaCollection(Beasiswa::paginate());
    }
...
I am trying to download a file from local storage but keep getting the error: Unable to retrieve the file_size for file at location.
        if (file_exists($filePath)) {
            return Storage::download($filePath, $fileName);
        }

The file path is tested prior to make sure the file exists.
The error is being thrown from vendor/league/flysystem-local/LocalFilesystemAdapter.php line 418.
    public function fileSize(string $path): FileAttributes
    {
        $location = $this->prefixer->prefixPath($path);
        error_clear_last();

        if (is_file($location) && ($fileSize = @filesize($location)) !== false) {
            return new FileAttributes($path, $fileSize);
        }

        throw UnableToRetrieveMetadata::fileSize($path, error_get_last()['message'] ?? '');
    }

I set a break point on the line
$location = $this->prefixer->prefixPath($path);

and found that $location is being set to some kind of weird concatenation of the folder path and the full file path.
C:\Users\tomva\Projects\laravel\storage\app\C:/Users/tomva/Projects/laravel/storage/app/pph/482678575-0150974001684180496/1283_CO1SAL_202301_O.pdf

I thought maybe it had something to do with developing on windows so I uploaded to our web server which is Linux but got the same error.
I tested just getting the file size and it throws the same error.
$size = Storage::size($filePath);

But using is_file($filePath) and filesize($filePath) work fine;
Just to make sure the file could be downloaded I tried using some code from another application that I have used for downloading files and it worked fine.
Anyone know what would cause this?
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):
<h1 style="text-align:center; font-size:50px;">Report History</h1>
<div id="content">
<table  id="datatable" class="table table-bordered table-hover table-sm"  border="2" style="width:100%;">
<thead>
        <tr>
          <th style="height:40px;">Date</th>
          <th>Report Type</th>
          <th>Customer ID</th>
          <th>Product ID</th>
          <th>Report PDF</th>
        </tr>
      </thead>
      <tbody>
    @foreach($report_archives as $report_archive)
    <tr>
    <td>{{$report_archive->date}}</td>
      <td>{{$report_archive->reportType}}</td>
      <td>{{$report_archive->customerID}}</td>
      <td>{{$report_archive->productID}}</td>
      <td><a href="/storage/app/public/pdf/{{$report_archive->reportLink}}">{{$report_archive->reportLink}}</a></td>
</tr>
@endforeach    
</tbody>
        </table>
</div>

I have tried using url and asset, but I get an error stating "Unclosed '(' does not match '}' "
<td><a href="{{asset('/storage/app/public/pdf/{{$report_archive->reportLink}}')}}">{{$report_archive->reportLink}}</a></td>
 <td><a href="{{url('/storage/app/public/pdf/{{$report_archive->reportLink}}')}}">{{$report_archive->reportLink}}</a></td>
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.