vendredi 9 septembre 2022

how to send multipart data in axios with Laravel api

I am using axios.post method to send the data to the server. i make the larvel api. When i check that api in postman, it was working fine. but when i connect that api in frontend it send all data to the backend except my image file. below i mention the code that send the image file to the server. Please check carefully my code and help me out where i am doing wrong. I stuck in this problem since two days.

frontEnd code
  const params = useParams();
  const { some } = params;

  const [name, setName] = useState("");
  const [school, setSchool] = useState("");
  const [author, setAuthor] = useState("");
  const [grade, setGrade] = useState("");
  const [Extra, setExtra] = useState("");
  const [image, setImage] = useState("");

 
  if (some === "book") {
    const handleSubmit = async (e) => {
   e.preventDefault();
  const formData = new FormData();
  formData.append("image", image);
  if (image == null) return image;
  console.log(image, name)

  const token = localStorage.getItem("Token")
  console.log(token)


  try {
    const res = await axios.post(
      `http://127.0.0.1:8000/add-product`,



      {
        formData,

        product_name: name,
        product_auther: author,
        school_name: school,
        class: grade,
        product_image: image,
        category_id: "17"



      },
      {
        headers:

          { "Authorization": `Bearer ${token}` },
          'Content-Type': 'multipart/form-data'   ,
      }



    ).then((res) => {
      console.log("usman    ", res)
    });
    console.log()

   } catch (error) {
    if (error.request) {
      console.log(error.response);

    } else if (error.request) {
      console.log("network error");
    } else {
      console.log("CBM", { error });
    }
  }
}

return (
  <div className="container " style=>
    <br>
    </br>
    <form onSubmit={handleSubmit} >
      <div className="mb-3">
        <label htmlFor="exampleInputEmail1" className="form-label"> Name</label>
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" />
      </div>
      <div className="mb-3">
        <label htmlFor="exampleInputPassword1" className="form-label">Author</label>
        <input type="text" value={author} onChange={(e) => setAuthor(e.target.value)} className="form-control" id="exampleInputPassword1" />
      </div>
      <div className="mb-3">
        <label htmlFor="exampleInputPassword1" className="form-label">image</label>
        <input type="file" onChange={(e) => setImage(e.target.files[0])} className="form-control" id="exampleInputPassword1" />
      </div>
      <div className="mb-3">
        <label htmlFor="exampleInputPassword1" className="form-label">School Name</label>
        <input type="text" value={school} onChange={(e) => setSchool(e.target.value)} className="form-control" id="exampleInputPassword1" />
      </div>
      <div className="mb-3">
        <label htmlFor="exampleInputPassword1" className="form-label">Grade(Class)</label>
        <input type="text" value={grade} onChange={(e) => setGrade(e.target.value)} className="form-control" id="exampleInputPassword1" />
      </div>
      <div className="mb-3">
        <label htmlFor="exampleInputPassword1" className="form-label">Any Extra Information</label>
        <input type="text" value={Extra} onChange={(e) => setExtra(e.target.value)} className="form-control" id="exampleInputPassword1" />
      </div>

      <button type="submit " className="btn btn-primary d-flex mx-auto" style=>Submit</button>
    </form>
  </div>
)

}

Laravel API
public function store(Request $request){


  $product = new product;
   $product->category_id = $request->category_id;
   $product->product_name = $request->product_name;
   $product->product_image = $request->file('image')->store('p_imges');
     $product->product_quantity = $request->product_quantity;
     $product->product_price = $request->product_price;
   $product->product_auther = $request->product_auther;
   $product->class = $request->class;
   $product->school_name = $request->school_name;
   $product->gender = $request->gender;
   $product->F_xyz = $request->F_xyz;
   $product->size = $request->size;
   $product->xtra_info = $request->xtra_info;
    $product->doner_id = Auth::id();
    $product->save();
    $product = ["Product Successfully Added"];
    return $product;

}

Error This error occur



via Chebli Mohamed

jeudi 8 septembre 2022

Laravel Project setup - failed to open stream: No such file or directory

file_put_contents(C:\xampp\htdocs\crmdemo\storage\framework/sessions/25qFABodcItYp2P122Qr0CFPq0fjXUGOHJLKuFqY): failed to open stream: No such file or directory

I tried all methods and degrade the php and composer version. But not working for this setup. Please guide to properly setup for me.



via Chebli Mohamed

WhereIn Insinde Where array - Laravel Query Builder

I'm trying use a whereIn inside a where array I am passing to Laravel query Builder:


$where = [['Participants.Client_Id','IN', $clientId]];

DB::table('Participants')->where($where)->get()

Something like is what I want to achieve, and I know there are works around such as using whereIn, but I'm sharing here a small piece of code to give you an idea, so I need to change the array to make it works as a whereIn, not changing the ->where to ->whereIn or ->whereRaw



via Chebli Mohamed

mercredi 7 septembre 2022

Can't download files from public folder from Laravel 5.6

I don't know what I am doing wrong here, but I can't for the life of me manage to get the download feature to work in Laravel 5.6

I have files saved to the public folder as you can see below:

enter image description here

On the webpage, these images show up correctly in HTML <img> tags and when I view the details of the image, it shows me that it points to https://mydomain.test/storage/LIizYnRWEqYOgTPlzTxbmuSbTMNYIFrnjLP1YWVH.png.

However, when I try and download this file from the server, I constantly get an exception error about the file not existing (for example: "data":"The file \"public\/LIizYnRWEqYOgTPlzTxbmuSbTMNYIFrnjLP1YWVH.png\" does not exist"). I have tried every combination of path string I can think of, but everything results in the same error.

I have tried using storage_path, I have tried using the original path, I've tried hard coding the path

    [2022-09-08 09:58:55] local.ERROR: Failed to download media file: The file "/home/vagrant/Code/dras/storage/LIizYnRWEqYOgTPlzTxbmuSbTMNYIFrnjLP1YWVH.png" does not exist  
    [2022-09-08 09:59:38] local.ERROR: Failed to download media file: The file "public/LIizYnRWEqYOgTPlzTxbmuSbTMNYIFrnjLP1YWVH.png" does not exist  
    [2022-09-08 10:00:14] local.ERROR: Failed to download media file: The file "https://mydomain.test/storage/LIizYnRWEqYOgTPlzTxbmuSbTMNYIFrnjLP1YWVH.png" does not exist   
    [2022-09-08 10:17:18] local.ERROR: Failed to download media file: The file "app/public/LIizYnRWEqYOgTPlzTxbmuSbTMNYIFrnjLP1YWVH.png" does not exist
    [2022-09-08 10:45:50] local.ERROR: Failed to download media file: The file "storage/public/LIizYnRWEqYOgTPlzTxbmuSbTMNYIFrnjLP1YWVH.png" does not exist 

The only combination that doesn't throw an exception about "file does not exist" is when I use the path

return response()->download( 'storage/LIizYnRWEqYOgTPlzTxbmuSbTMNYIFrnjLP1YWVH.png' );

However, that command throws a totally different error:

Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header() in file /home/vagrant/Code/dras/app/Http/Middleware/Cors.php on line 27



via Chebli Mohamed

MySQL 5.7 using JSON variable as counter to rank rows in Laravel 5.4

I am using MySQL 5.7 and trying to emulate rank(which is not available in 5.7) using JSON variables.

The problem is that in Laravel DB or PDO query below doesn't work correctly but works fine in TablePlus.

The idea of a query to count rows by groups and filter rows which have counter less than 250. Every group rows have it own counters in json variable.

The idea of this query:

select result.*
from (
    select 
        @extracted_counter:=JSON_EXTRACT(@row_number, CONCAT('game', t.game_id)) as extracted_counter,
        JSON_SET(@row_number, CONCAT('key', t.game_id), @extracted_counter + 1) as counters,
        t.*
    from (@row_number := '{"game1": 0, "game27": 0}') as x,
        table_name as t
    where t.app_id = 16325
) as result
where result.extracted_counter < 250;

@json_variable build from another table. I made it as a string to simplify.

Again, the original query is working ok in TablePlus program but when it comes to Laravel 5.4 DB, @row_number can't perform addition more than 3, for instance: "{"game27718": 0,"game27398": 3,"game26592": 0,"game24042": 0,"game23957": 3}"

I thought that Laravel uses specific PDO settings but couldn't find anything. Also, I've tried to use CAST but it didn't help really since addition is working for first three records.

Not really sure how is different settings for TablePlus and PDO Laravel. I've tried to google settings of TablePlus but I can't imagine how can I google it correctly to not bump into interface docs.

I would appreciate any help.

The original query I am trying to use looks like this:

SELECT temp.*
FROM (
    SELECT
    @extracted_counter:=CAST(JSON_EXTRACT(@row_number, CONCAT('$.game', sao.game_id)) AS UNSIGNED) AS extracted_rank,
    if(
        @extracted_counter < @games_length,
        @row_number:=JSON_SET(
            @row_number,
            CONCAT('$.game', sao.game_id),
            @extracted_counter + 1
        ),
        @const_length
    ) AS rnk,
    sao.email, sao.name,
    sao.game_id, sao.order_total_price,
    sao.device_type, sao.coupon_id,
    sao.coupon_code, sao.browser,
    sao.city, sao.country,
    sao.order_id, sao.created_at
    FROM (SELECT @row_number := (
        SELECT concat('{', group_concat(concat('"game', s.game_id, '"'), ': 0'), '}') AS str_json
        FROM (
            SELECT g.id AS game_id
            FROM users AS u
            LEFT JOIN games AS g ON u.id = g.user_id
            WHERE u.app_id = 16325
                AND g.deleted_at IS NULL
        ) AS s
    )) AS x,
    (SELECT @games_length := 250) AS games_length,
    (SELECT @const_length := @games_length + 100) AS const_length,
    shopify_app_orders as sao
    WHERE sao.app_id = 16325
        AND sao.coupon_id > 0
    ORDER BY sao.id DESC
) AS temp
LEFT JOIN coupons AS c ON c.id = temp.coupon_id
WHERE temp.extracted_rank < @games_length


via Chebli Mohamed

Stripe differentiate between payment Intent and payment link

I'm trying to read the webhook response from both a payment intent (in which a user in the website press pay to pay for an item) and a payment link (where he receives a link which then he can pay through) I'm trying to find how can I differentiate between them but I can't find a difference. Is there a flag or something to distinguish which one was paid



via Chebli Mohamed

mardi 6 septembre 2022

Laravel wait for a specific queued listener to finish then return

I have an Event with a bunch of queued listeners. Can't run sync because I am calling external APIs etc

Events\Invoice\InvoiceEvent::class => [
    Listeners\Invoice\Listener1::class, 
    Listeners\Invoice\Listener2::class,
    Listeners\Invoice\Listener3::class, // calling external APIs
    Listeners\Invoice\Listener4::class,
    Listeners\Invoice\Listener5::class,
],

Calling this event from a controller method.

public function store(Request $request)
{
    $invoice = Invoice::findOrFail($request->id);
    InvoiceEvent::dispatch($invoice); // Async event, it cannot be sync

    return $invoice; // need to return only when Listener3 finish execution
}

return $invoice is dependent on Listener3, otherwise, it will return incomplete data.

How can I return only when Listener3 is finished executing?

I came up with sleep(10); but it's not an ideal solution.

Listener3 saves data from third-party API to the invoices table which needs to be returned, that's why cannot return incomplete invoice data, right now the required data gets added to the invoice but after its return



via Chebli Mohamed