vendredi 31 juillet 2020

How can I make notification recieved count for each user

Whenever admin sends message to a user I want the notification to appear on user dashboard as a counter on the menu, below is the code i have tried in my header menu

<li class="nav-item">
@foreach($Notif as $notification)
<a href="">Notification <span>    

</span></a>
@endforeach
</li>

Image of where notification is on header (user header)

Image of admin panel to send message to user



via Chebli Mohamed

Cannot show modal on button click using vue.js in laravel

I want to simply open modal on button click, i have used below code for that but i'm getting following error when i click button to open it, I'm new to vue.js so not have much idea about it.

app.js:42386 [Vue warn]: Property or method "showModal" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property

created component for modal:

<template>
<transition name="modal">
    <div class="modal-mask">
      <div class="modal-wrapper">
        <div class="modal-container">

          <div class="modal-header">
            <slot name="header">
              default header
            </slot>
          </div>

          <div class="modal-body">
            <slot name="body">
              default body
            </slot>
          </div>

          <div class="modal-footer">
            <slot name="footer">
              default footer
              <button class="modal-default-button" @click="$emit('close')">
                OK
              </button>
            </slot>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
  export default {

  }
</script>

Added button code on view to open modal:

 <button id="show-modal" @click="showModal = true">Show Modal</button>
  <modal v-if="showModal" @close="showModal = false">

    <h3 slot="header">custom header</h3>
  </modal>

In app.js:

Vue.component('modal', require('./components/web/Category.vue').default);


via Chebli Mohamed

Add subdomain parameter in api routes Laravel

I'm trying to add parameter subdomain in routes in Laravel 5.8

Here is my code:

Route::domain('{subdomain}.localhost:8080')->group(function () {

    Route::group(['prefix' => 'auth'], function () {
        Route::post('login', 'Api\Auth\LoginController@login');
        Route::post('register', 'Api\Auth\RegisterController@register');
    });
});

But I get this error:

enter image description here

Help me to understand what am I missing!



via Chebli Mohamed

How do I create a "Play Code Snippet" Button with JavaScript? [closed]

I am trying to create a function that allows the author of a document to execute code that they have entered. The page looks like this:

enter image description here

As you can see the author can enter code snippets, however, I would like them to be able to check what they have entered is correct. I have an idea similar to what is used on stack overflow. I want to reader to be able to click the "Play Code Snippet" Button and the result to be shown. At the moment the result is hardcoded and once the user pressed the show button the webpage looks like this:

enter image description here

This is the jQuery for that:

<script>
    (function () {
        $(document).ready(function(){
            $('#showCode').click(function(){
                $(".resultSection").addClass("show");
            });

            $('#hideResult').click(function(){
                $(".resultSection").removeClass("show");
            });
        });
    })();
</script>

How do I take the code/input from the code section (.codeSection) and execute it using javascript to then output the correct response?

I am also using Laravel, are there any helpers that it could provide?

Any help would be great! Thanks



via Chebli Mohamed

How to pass Js variable through html anchor tag

Here I am trying to pass the id to the controller like this

but the '+val[0]+' is consider as a string in url http://localhost:8000/admin/service/**+val%5B0%5D+**/edit

but the variable looks like +val%5B0%5D+ in URL but I want its value

this is my anchor tag

<a href=""></a>

Below is the full code

$.ajax({
       type:'POST',
       url:'/admin/service/show_list',
       data:{ modality_id: m, center_id: h },
       success:function(data) {
           $("#service-table > tbody").empty();
                var trHTML = '';
                $.each( data.service_list1, function( i, val ) {
                    trHTML +='<tbody><tr id="myTableRow" style="text-align:center;"><td>' + val[0] + '</td><td>' + val[1] + '</td><td><a href="" class="btn btn-default btn-xs" title="Edit Service"><i class="fa fa-pencil"></i></a></td></tr></tbody>';
                });
                $('#service-table').append(trHTML);
                }
       });

But I want to pass the value of that variable in URL so how I am able to do it ??

Advance Thanks



via Chebli Mohamed

Laravel clear all SQS queues using localstack

When I start a new day at work, I open all the containers again, and when I run php artisan queue:work or listen I expect nothing to run, since everything is fresh and I haven't done anything yet .. but for some reason it's trying to execute old queues. I am using SQS queues on localstack

I tried clearing everything, using: php artisan queue:flush

Also I used php artisan queue:restart

I checked php artisan queue:failed to make sure that nothing is in any file

I also deleted recorded_api_calls.json just to make ure its not from there .. and its not

Does anybody have any idea where all the random queue calls may come from ?



via Chebli Mohamed

jeudi 30 juillet 2020

how to validate atleast one value of form input array in laravel request?

I am passing array input to store function .

  <div class="col-md-4 form-group-sub mt-2 date_">
   <input type="text" name="date[]" class="form-control datepicker" placeholder="Date">
  </div>
                                               

this array should be have atleast one field filled . If all the values are null i don't to submit this form how shoult i validate in request

public function rules()
    {
        return [
           
            'date.*' => '?'

        ];
    }



via Chebli Mohamed

How to fix error while cloning branch git

 git clone https://github.com/RezkyRizaldi/CostumRubber.git
 Cloning into 'CostumRubber'...
 remote: Enumerating objects: 53, done.
 remote: Counting objects: 100% (53/53), done.
 remote: Compressing objects: 100% (37/37), done.
 remote: Total 10622 (delta 22), reused 33 (delta 14), pack-reused 10569
 Receiving objects: 100% (10622/10622), 69.05 MiB | 2.28 MiB/s, done.
 Resolving deltas: 100% (1687/1687), done.
 error: invalid path 
 'C:\Users\RULLRUBBER\Documents\CustomRubber\storage\logs/laravel-2020-06- 
 29.log'
 fatal: unable to checkout working tree
 warning: Clone succeeded, but checkout failed.
 You can inspect what was checked out with 'git status'
 and retry with 'git restore --source=HEAD :/'

Error begin when i cloning I tried to find storage folder but its not there



via Chebli Mohamed

Invalid datetime format in laravel while sending data from angular

Can anyone help me how to solve this issue? I have a request data from angular that I had passed to the laravel backend for inserting multiple rows at a time. But I got below error. I tried running the below query in Mysql, it is working fine there but not from laravel.

How can I fix this??

Request data from Angular (API):

[
  {
    "customer_id": 3,
    "check_in_date": "2020-07-30T00:00:00.000Z",
    "check_out_date": "2020-07-31T00:00:00.000Z",
    "room_id": 2
  },
  {
    "customer_id": 3,
    "check_in_date": "2020-07-29T00:00:00.000Z",
    "check_out_date": "2020-07-31T00:00:00.000Z",
    "room_id": 3
  }

]

Migration Table

public function up()
{
    Schema::create('reservations', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('room_id');
        $table->foreign('room_id')->references('id')->on('rooms');
        $table->unsignedBigInteger('customer_id');
        $table->foreign('customer_id')->references('id')->on('customers');
        $table->unsignedBigInteger('booking_id')->nullable();
        $table->foreign('booking_id')->references('id')->on('bookings');
        $table->dateTime('check_in_date');
        $table->dateTime('check_out_date');
        $table->timestamps();
    });
}

Controller of reservation:

public function store(Request $request)
{
    $reservation = Reservation::insert($request->all());
    
    return $this->jsonResponse(true, 'Reservation has been created successfully.', $reservation);
}


private function jsonResponse($success = false, $message = '', $data = null)
{
    return response()->json([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ]);
}

Error:

 "message": "SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2020-07- 
 29T00:00:00.000Z' for column 'check_in_date' at row 1 

 (SQL: insert into `reservations` (`check_in_date`, `check_out_date`, `customer_id`, `room_id`)

 values (2020-07-29T00:00:00.000Z, 2020-07-31T00:00:00.000Z, 3, 2),
        (2020-07-29T00:00:00.000Z, 2020- 07-31T00:00:00.000Z, 3, 3), 
        (2020-07- 29T00:00:00.000Z, 2020-07-31T00:00:00.000Z, 3, 3))",
 "exception": "Illuminate\\Database\\QueryException",


via Chebli Mohamed

Leave System Balance on a HR application Laravel

I'll just head on to the question directly, I'm currently trying to build an HR(Human Resources) Application on Laravel and at the Leave System where a user can take a specific type of Leave(Vacation and such), I would like to create a Balance system where the user selects a date from and date to and that number in between them gets deducted from the main balance that a user has and that would be the number 20 which I added to my user table on a field called leave_balance(the number is set by default as 20 when a user is created).

Now except deducting the number I would also like to add a function somehow that adds a specific number to the leave_balance every day ex 0.05 I am suspecting I can do this with carbon but I have not the slightest idea how since im relatively new to Laravel

So this is the Leave Table(it is not connected by a foreign key with the user's table):

  1. id
  2. user_id
  3. from
  4. to
  5. type
  6. description
  7. status
  8. message

The user_id is only there to store the id of the authenticated user who creates a leave it is not related by a foreign key

This is what I was thinking of adding in the LeaveController:

// checks for table if employee leave is at 0
$employee = DB::table('leaves')->where('id', $id)->where('leave', 0)->get()->all();
$employeeObj = DB::table('leaves')->where('id', $id)->get()->all();

// init for needed condition
$leaveBool = false;
if(sizeof($employee) < 1) {
  $leaveBool = true;
}

// leave is not at 0
if(!$leaveBool) {
  DB::table('leaves')->update([
    'id' => $id,
    'leave'       => $employeeObj['leaves'] - 1,
  ]);
}

I would like to fix this code so that I can add this in the Leave Controller(also if it's possible to explain to me where exactly I should put such a code in the controller) by fix I mean to not just removed -1 but the number between "from" and "to"

I'm not sure if these are helpful but I will post them too just to make it easier to see,

This is the Leave Model:

class Leave extends Model
{
    use Notifiable;

    protected $guarded=[];
    
    public function user(){
        return $this->belongsTo(User::class,'user_id','id');   
     }
}

This is the view of the Leave

<div class="card-body">
                    <form method="POST" action="">
                        @csrf

                        <div class="form-group">
                            <label>From Date</label>
                            <div class="col-md-6">
                                <input class="datepicker" type="text" class="form-control @error('from') is-invalid @enderror" name="from" required="">

                                @error('from')
                                    <span class="invalid-feedback" role="alert">
                                        <strong></strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group">
                            <label>To Date</label>
                            <div class="col-md-6">
                                <input class="datepicker1" type="text" class="form-control @error('to') is-invalid @enderror" name="to" required="">

I used datepicker for the date, this would be a visualization of what I'm trying to achieve enter image description here

Also by any means, if you have a better code or idea on how I can do this do share it your way it may probably be heaps better



via Chebli Mohamed

How to clear laravel request?

I accept a response from a form and I want to create a request using Request::create() and pass parameters to it. But when the request gets created, the previous form request parameters is also attached. I want to clear those request and only pass parameters through Request::create() Below is my code:

$request = Request::create('api/my-api', 'POST', $response);
$request->headers->set('Content-Type', 'application/json');
$request->headers->set('api-key' , $api_key);
$request->headers->set('api-secret', $api_secret);
Route::dispatch($request)

Please help.



via Chebli Mohamed

mercredi 29 juillet 2020

How can i get one another address for every data will submit,i do just output same address

Hello i use cold storage i dont want use RPC because so many memory needed,but i need use manual.How can i get different address when data will be submit,When user fill data controller will redirect to pay and pay will get different address every submit data in cart list.Example when user fill again and user will get different address.When address reach 24 hour dont have balance data will be revert zero in 'in_use' column.Can you help me because many time i dont wills show same address every data submit https://pastebin.com/6tB1HtGM

//wallet table
Schema::create('wallets', function (Blueprint $table) {
            $table->id();
            $table->boolean('in_use')->default(false);
            $table->string('address');
            $table->timestamps();
        });
 
//product controller
<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\Product;
use Darryldecode\Cart\CartCondition;
use App\Customer;
use App\Http\Requests\BuyRequest;
use App\Http\Requests\ProductRequest;
use App\Wallet;
class ProductController extends Controller
{
    //
    public function index(){
        // $products = Product::all();
        // return dd($products);
    }
 
    public function showpage(){
        $dataproducts = Product::all();
        return view('index.homeshop',compact('dataproducts'));
    }
 
    public function addtocart(ProductRequest $request){
        $cart = \Cart::add(array(
            'id' => $request->input('id'),
            'name' => $request->input('name'),
            'price' => $request->input('price'),
            'quantity' => $request->input('quantity'),
        ));
        return back();
    }
 
    public function updatetocart(Request $request){
        // $cartupdate = \Cart::
        return back();
    }
 
    public function deletetocart(){
 
    }
 
    public function checkout(Request $request){
        $items = \Cart::getContent();
        return view('index.wishlist',compact('cartcontent'));
    }
 
 
    public function buyprocess(BuyRequest $request){
        $customer = new Customer();
        $customer->wallet_id = Wallet::where('is_use',0)->first();
        $customer->firstname = $request->input('firstname');
        $customer->lastname = $request->input('lastname');
        $customer->email = $request->input('email');
        $customer->address = $request->input('address');
        $customer->address2 = $request->input('address2');
        $customer->postcode = $request->input('postcode');
        $customer->city = $request->input('city');
        $customer->state = $request->input('state');
        $customer->country = $request->input('country');
        $customer->save();
        return redirect('pay');
    }
 
}
 
//wallet controller
<?php
namespace App\Http\Controllers;
 
use App\MemberCustomer;
use App\Customer;
use App\Product;
use Illuminate\Http\Request;
use Darryldecode\Cart\CartCondition;
use SimpleSoftwareIO\QrCode\Generator;
use Illuminate\Support\Str;
use App\Wallet;
 
class WalletController extends Controller
{
    //
    public function getwallet(Request $request){
 
        if(\Cart::getSubTotal() == true){
        $wallet = Wallet::where('is_use',0)->first();
        //if wallet has been use put 1
        return view('index.payment',compact('wallet'));
        }
        else{
            echo 'not allowed,Please add some product';
        }
    }
 
}


via Chebli Mohamed

Laravel SQS queue on localstack returns errors when running it

I have an empty Job file:

<?php

namespace SS\Jobs;

use Exception;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;


class SJQJob implements ShouldQueue
{

    protected $payload;

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

    public function handle()
    {
        Log::info('!!!! Handle');
    }

    
    public function failed(Exception $exception)
    {
        Log::info('!!!! Failed');
    }

}

I am dispatching this, then using php artisan queue:work ssqjobrequest I can see it being processed (2020-07-29 16:43:07][06978486-4c62-3948-5b4a-f8c648038c34] Processing: SS\Jobs\SJQJob)

The problem is that I am seeing this message in the log:

2020-07-29 16:43:07] local.ERROR: Error executing "DeleteMessage" on "http://localstack.test:4576/000000000000/ssqjobrequest"; AWS HTTP error: Client error: `POST http://localstack.test:4576/000000000000/ssqjobrequest` resulted in a `400 Bad Request` response:
<?xml version="1.0" encoding="UTF-8"?>
  <ErrorResponse>
    <Errors>
      <Error>
        <Code>ReceiptHandleIsInvalid (truncated...)
 ReceiptHandleIsInvalid (client): The input receipt handle is invalid. - <?xml version="1.0" encoding="UTF-8"?>
  <ErrorResponse>
    <Errors>
      <Error>
        <Code>ReceiptHandleIsInvalid</Code>
        <Message>The input receipt handle is invalid.</Message>
        
      </Error>
    </Errors>
  <RequestID>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</RequestID>
</ErrorResponse> {"exception":"[object] (Aws\\Sqs\\Exception\\SqsException(code: 0): Error executing \"DeleteMessage\" on \"http://localstack.test:4576/000000000000/ssqjobrequest\"; AWS HTTP error: Client error: `POST http://localstack.test:4576/000000000000/ssqjobrequest` resulted in a `400 Bad Request` response:
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  <ErrorResponse>
    <Errors>
      <Error>
        <Code>ReceiptHandleIsInvalid (truncated...)
 ReceiptHandleIsInvalid (client): The input receipt handle is invalid. - <?xml version=\"1.0\" encoding=\"UTF-8\"?>
  <ErrorResponse>
    <Errors>
      <Error>
        <Code>ReceiptHandleIsInvalid</Code>
        <Message>The input receipt handle is invalid.</Message>
        
      </Error>
    </Errors>
  <RequestID>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</RequestID>
</ErrorResponse> at /var/www/sst/vendor/aws/aws-sdk-php/src/WrappedHttpHandler.php:195)
[stacktrace]
#0 /var/www/sst/vendor/aws/aws-sdk-php/src/WrappedHttpHandler.php(97): Aws\\WrappedHttpHandler->parseError()
#1 /var/www/sst/vendor/guzzlehttp/promises/src/Promise.php(198): Aws\\WrappedHttpHandler->Aws\\{closure}()
#2 /var/www/sst/vendor/guzzlehttp/promises/src/Promise.php(169): GuzzleHttp\\Promise\\Promise::callHandler()
#3 /var/www/sst/vendor/guzzlehttp/promises/src/RejectedPromise.php(40): GuzzleHttp\\Promise\\Promise::GuzzleHttp\\Promise\\{closure}()
#4 /var/www/sst/vendor/guzzlehttp/promises/src/TaskQueue.php(47): GuzzleHttp\\Promise\\RejectedPromise::GuzzleHttp\\Promise\\{closure}()
#5 /var/www/sst/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php(118): GuzzleHttp\\Promise\\TaskQueue->run()
#6 /var/www/sst/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php(145): GuzzleHttp\\Handler\\CurlMultiHandler->tick()
#7 /var/www/sst/vendor/guzzlehttp/promises/src/Promise.php(241): GuzzleHttp\\Handler\\CurlMultiHandler->execute()
#8 /var/www/sst/vendor/guzzlehttp/promises/src/Promise.php(218): GuzzleHttp\\Promise\\Promise->invokeWaitFn()
#9 /var/www/sst/vendor/guzzlehttp/promises/src/Promise.php(262): GuzzleHttp\\Promise\\Promise->waitIfPending()
#10 /var/www/sst/vendor/guzzlehttp/promises/src/Promise.php(220): GuzzleHttp\\Promise\\Promise->invokeWaitList()
#11 /var/www/sst/vendor/guzzlehttp/promises/src/Promise.php(262): GuzzleHttp\\Promise\\Promise->waitIfPending()
#12 /var/www/sst/vendor/guzzlehttp/promises/src/Promise.php(220): GuzzleHttp\\Promise\\Promise->invokeWaitList()
#13 /var/www/sst/vendor/guzzlehttp/promises/src/Promise.php(61): GuzzleHttp\\Promise\\Promise->waitIfPending()
#14 /var/www/sst/vendor/aws/aws-sdk-php/src/AwsClientTrait.php(58): GuzzleHttp\\Promise\\Promise->wait()
#15 /var/www/sst/vendor/aws/aws-sdk-php/src/AwsClientTrait.php(86): Aws\\AwsClient->execute()
#16 /var/www/sst/vendor/laravel/framework/src/Illuminate/Queue/Jobs/SqsJob.php(71): Aws\\AwsClient->__call()
#17 /var/www/sst/vendor/dusterio/laravel-plain-sqs/src/Integrations/LaravelServiceProvider.php(28): Illuminate\\Queue\\Jobs\\SqsJob->delete()
#18 /var/www/sst/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(369): Dusterio\\PlainSqs\\Integrations\\LaravelServiceProvider->Dusterio\\PlainSqs\\Integrations\\{closure}()
#19 /var/www/sst/vendor/laravel/framework/src/Illuminate/Events/Dispatcher.php(218): Illuminate\\Events\\Dispatcher->Illuminate\\Events\\{closure}()
#20 /var/www/sst/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(509): Illuminate\\Events\\Dispatcher->dispatch()
#21 /var/www/sst/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(370): Illuminate\\Queue\\Worker->raiseAfterJobEvent()
#22 /var/www/sst/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(314): Illuminate\\Queue\\Worker->process()
#23 /var/www/sst/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(134): Illuminate\\Queue\\Worker->runJob()
#24 /var/www/sst/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(112): Illuminate\\Queue\\Worker->daemon()
#25 /var/www/sst/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(96): Illuminate\\Queue\\Console\\WorkCommand->runWorker()
#26 [internal function]: Illuminate\\Queue\\Console\\WorkCommand->handle()
#27 /var/www/sst/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(32): call_user_func_array()
#28 /var/www/sst/vendor/laravel/framework/src/Illuminate/Container/Util.php(36): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()
#29 /var/www/sst/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(90): Illuminate\\Container\\Util::unwrapIfClosure()
#30 /var/www/sst/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(34): Illuminate\\Container\\BoundMethod::callBoundMethod()
#31 /var/www/sst/vendor/laravel/framework/src/Illuminate/Container/Container.php(590): Illuminate\\Container\\BoundMethod::call()
#32 /var/www/sst/vendor/laravel/framework/src/Illuminate/Console/Command.php(134): Illuminate\\Container\\Container->call()
#33 /var/www/sst/vendor/symfony/console/Command/Command.php(255): Illuminate\\Console\\Command->execute()
#34 /var/www/sst/vendor/laravel/framework/src/Illuminate/Console/Command.php(121): Symfony\\Component\\Console\\Command\\Command->run()
#35 /var/www/sst/vendor/symfony/console/Application.php(1001): Illuminate\\Console\\Command->run()
#36 /var/www/sst/vendor/symfony/console/Application.php(271): Symfony\\Component\\Console\\Application->doRunCommand()
#37 /var/www/sst/vendor/symfony/console/Application.php(147): Symfony\\Component\\Console\\Application->doRun()
#38 /var/www/sst/vendor/laravel/framework/src/Illuminate/Console/Application.php(93): Symfony\\Component\\Console\\Application->run()
#39 /var/www/sst/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(131): Illuminate\\Console\\Application->run()
#40 /var/www/sst/artisan(35): Illuminate\\Foundation\\Console\\Kernel->handle()

I am not trying to delete anything (so I guess that laravel tries to delete the message from Amazon SQS) .. but why does it fail? I have checked and the message gets there .. so why would it fail when trying to delete it ?

Thanks!



via Chebli Mohamed

How to show pagination from controller Laravel

The question is not directly on how to show the pagination that much I'm aware but rather how to modify it so that I can show it here

public function create()
    {
        $leaves = Leave::latest()->where('user_id',auth()->user()->id)->get();
        $pagination = Leave::latest()->paginate(5);
        return view('leave.create',compact('leaves'),compact('pagination'));
    }

The create function here returns to a page where you can create and view all that you have created at the same time on a table but the table keeps getting bigger so I wanted to add pagination here but it seems this is not the correct way I tried adding the ->paginate(5) right after latest() of $leaves but it showed an error

Is there another way I can add the pagination, the one right now works but it shows the leaves of all users but I need it to only show of that specific user that's why I added the auth up but I think the one under for pagination is overriding it



via Chebli Mohamed

how can i set new cashe just in 10s using laravel Cashe

I used put function for make new manual Cashe. for example :

$cashtime =Cache::put('filekey', 'mycashtime', 20);

and sent it to view but it not expired . when i send it to view it will back me true. but after 20s have to send me false and expire it.

and then how can i check it is expired or not .



via Chebli Mohamed

Laravel queue listen returns var_dump of $this

When I run any command like listen, or work, or anything else, I get a 30mb dump of data (I think it's the $this variable

One command that I run, where I get that dump is: php artisan queue:listen --timeout=30 --tries=1

Basically this returns something like: (this is truncated, since like I said its 30mb)

  ["this"]=>
  object(Illuminate\Queue\QueueServiceProvider)#212 (1) {
    ["app":protected]=>
    object(Illuminate\Foundation\Application)#5 (32) {
      ["basePath":protected]=>
      string(12) "/var/www/sst"
      ["hasBeenBootstrapped":protected]=>
      bool(true)
      ["booted":protected]=>
      bool(true)
      ["bootingCallbacks":protected]=>
      array(3) {
        [0]=>
        object(Closure)#148 (1) {
          ["this"]=>
          object(Clockwork\DataSource\LaravelDataSource)#143 (7) {
            ["app":protected]=>
            *RECURSION*
            ["response":protected]=>
            NULL
            ["log":protected]=>
            object(Clockwork\Request\Log)#147 (2) {
              ["data"]=>
              array(0) {
              }
              ["collectStackTraces":protected]=>
              bool(true)
            }
            ["timeline":protected]=>
            object(Clockwork\Request\Timeline)#144 (1) {


via Chebli Mohamed

How to display database table data on a view for a specific authenticated user

I'm currently working on a feature where when a user is created his job position can be selected and I connected that through a foreign key where the user gets to select the ID of the specific job and it works well when storing the data, the actual ID of the specific field is showing on the users table but now my problem is when I want to show that specific data of the authenticated user Here's the table I have

Job's Table

  1. id
  2. job_name
  3. line_manager
  4. department
  5. branch
  6. job_type

The id is a foreign key for the users table at

  1. job_id

Heres my JobController:

public function index()
    {
        $role = Auth::guard('web')->user()->role_id;
        if($role == 1)
        {
            $jobs = Job::latest()->where('id',auth()->user()->id)->get();
            return view('job.index',compact('jobs'));
        }

The Model:

class Job extends Model
{
    protected $table = 'jobs';

    public function jobWhich()
    {
        return $this->job_name;
    }

And this is the view I want the data of that ID that I selected when I created the user to show here(its static data that was inserted in the database so it won't change)

<tbody>
@foreach($jobs as $job)
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
@endforeach
</tbody>

I'm not sure if I need to show the users controller on how I store this into the user but it's working well because I can see the id of the specific field at the user when I create



via Chebli Mohamed

Sending image in the mail in laravel

I am trying to send auto reply to the newly registered user and I want to send them an image rather than the text but when I try to send the image the mail does sent but image receive is broken. Studied many answers from stackoverflow as well tried many other solutions from the internet but nothing seems to be working. here is my mail class.

<?php

 namespace App\Mail;

 use Illuminate\Bus\Queueable;
 use Illuminate\Mail\Mailable;
 use Illuminate\Queue\SerializesModels;

 class autoMail extends Mailable
 {
  use Queueable, SerializesModels;

/**
 * Create a new message instance.
 *
 * @return void
 */
public function __construct()
{
    //
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->subject("Subject")
            ->view('emails.autoemail');
}
}

And here is my function which is calling this mail class.

Mail::to($request->email)->send(new autoMail());

And last but not the least my view which I am sending as a mail.

<!DOCTYPE html>
<html>
<head>
    <title>Auto Email</title>
</head>
<body>
    <img src="">
</body>
</html>

Any help would be appreciated as I am stuck here for so much time. Thank you in advance



via Chebli Mohamed

duplicate the value with space in php [closed]

I have the variable

$request['customer']=Array ( Existing_Customer, New_Customer)

I want to replace parse the each data and duplicate with space as

$request['customer']=Array ( Existing_Customer,Existing Customer,New_Customer,New Customer);

array_replace ()

I cant replace as expected



via Chebli Mohamed

newly created guard is not working in multiauth laravel routes?

I have created new guard and trying to implement on routes but it is not working but when i try to implement it in controller it works fine. On routes it gives too many redirection error

routes

// Route::group(['middleware' => ['trading_partner']], function () {
Route::group(['prefix' => 'tradingpartners'], function () {
    //contractor auth controller
    Route::get('/login', 'ContractorAuth\ContractorAuthController@getLogin')->name('contractors.login');
    Route::post('/login', 'ContractorAuth\ContractorAuthController@postLogin')->name('contractors.login');
    Route::post('/logout', 'ContractorAuth\ContractorAuthController@postLogout')->name('contractors.logout');
    //user contractor contorller
    Route::get('/dashboard', 'User\ContractorController@contractorDashboard')->name('contractors.dashboard');
    Route::get('/dashboard/pallets_balance_report_table', 'User\ContractorController@palletsBalanceReportTable');
});
// });

controller

class TradingPartnerAuthController extends Controller
{
    use AuthenticatesUsers;

    protected $guardName = 'trading_partner';
    protected $maxAttempts = 3;
    protected $decayMinutes = 2;

    protected $loginRoute;

    public function __construct()
    {
        $this->middleware('guest:trading_partner', ['except' => ['logout', 'postLogout']]);
        $this->loginRoute = route('trading_partners.login');
    }
   }



via Chebli Mohamed

mardi 28 juillet 2020

problem with dash character in the Laravel routing

I have this code in my route:

Route::get('/{lang}/post/{id}-{slug?}',function($lang, $id, $slug=null) {
    dd($lang, $id, $slug);
})->where('id', '[0-9]+');

site.com/en/post/30 -> Work

site.com/en/post/30-myslug -> Work

site.com/en/post/30- -> 404

Why I get a 404 error? slug is optional.

If I replace the dash with another character for example 'i'

Route::get('/{lang}/post/{id}i{slug?}',function($lang, $id, $slug=null) {
    dd($lang, $id, $slug);
})->where('id', '[0-9]+');

site.com/en/post/30i Work

Is there any limitation for the dash character?

Laravel 5.8

Sincerely



via Chebli Mohamed

use whereIntegerInRaw In laravel5.5

I need to use whereIntegerInRaw query because when I have too large database, use whereIn is very slow.

I try to extend query builder and add that method to it,but it still no working.

In OptimizeBuilder

public function whereIntegerInRaw($column, $values, $boolean = 'and', $not = false)

$type = $not ? 'NotInRaw' : 'InRaw';

if ($values instanceof Arrayable) {
    $values = $values->toArray();
}

foreach ($values as &$value) {
    $value = (int) $value;
}

$this->wheres[] = compact('type', 'column', 'values', 'boolean');

return $this;

In model

public static function query(): OptimizeBuilder
{
  return parent::query();
}
public function newEloquentBuilder($query)
{
   return new OptimizeBuilder($query);
}


via Chebli Mohamed

Laravel: Combining transformed data based on common field

I am transforming some data from a query within my controller and returning it the frontend. I am getting an array of custom transformed "Orders" with the info I need. I will be calling this endpoint every few seconds. I am trying to see if there is a way I can combine the total of all the orders that have the same customer_id

Controller

 $orders = Order.where("type", "=", "valid")->get();

   foreach ($orders as $order) {
        $ordersArray[] = [
            'order_id' => $order->id,
            'customer_name' => $order->customer_id),
            'customer_id' => $order->customer_id,
            'total' => $order->total,
        ];
    }

    return [
        'paidOrders'    =>  $ordersArray,
    ];

example of what is returned to the frontend

[
   {order_id: 314, customer_name: "Martin", customer_id: 71, total: 66},
   {order_id: 315, customer_name: "Barry", customer_id: 82, total: 217},
   {order_id: 316, customer_name: "Barry", customer_id: 82, total: 217},
   {order_id: 317, customer_name: "Barry", customer_id: 82, total: 147},
]

example of what I'd like returned -- just combine the total for the same customer

[
   {order_id: 314, customer_name: "Martin", customer_id: 71, total: 66},
   {order_id: ?, customer_name: "Barry", customer_id: 82, total: 581},
]


via Chebli Mohamed

change api data language on UI of website

I am using an API from the GOvernment which provides market rates of agricultural products from the local markets of India. The data from the API are in the English language. I want to show the data to the user of my website in the Hindi language.

  • I have tried google translate but I am not able to hide the translate bar from the website as I do not want it to show. *I want to automate the process so that I don't have to enter manually the data in Hindi. *The website is being built using laravel. *The government API has no language option it comes in English only. *I want to use the same in the app of the website to the solution should work in the web portal as well as the app.

please ask if I left anything that is needed to solve this.



via Chebli Mohamed

how to fix id property?

$request->validate([ 'current_password' => 'required',new MatchOldPassword, 'new_password' => 'required', 'new_confirm_password' => 'required|same:new_password', ]); $data = $request->all();

$user=User::find(auth()->user()->id)->update(['password'=> Hash::make($request->new_password)]);

dd('Password change successfully.'); }



via Chebli Mohamed

How to get join results as an array of objects in Laravel?

I have been working on a personal project where users can rate different shops. Among many, I have two tables schemas that I am working on.

Table: Shops

  1. id
  2. shop_name
  3. user_id (shops belongs to a user)

Table : Ratings

  1. id
  2. shop_id (foreign_key)
  3. rating
  4. user_id

Now I want to fetch all the shops and its corresponding ratings using SQL join.

 $shop = Shop::leftJoin('ratings', 'ratings.shop_id', '=', 'shops.id')
    ->select('shops.*', 'ratings.rating')->get();
    return response($shop);

When I do this I get response but the it is repeated for each ratings on the same shop.

[
    {
        "id": 1,
        "name": "manjil",
        "rating": 4
    },
    {
        "id": 1,
        "name": "manjil",
        "rating": 5
    },
    {
        "id": 1,
        "name": "manjil",
        "rating": 2
    }]

What I really want is :

        [{
            "id": 1,
            "name": "manjil",
            "rating": [4,5,2]
        }]

Please Laravel geeks, help :)



via Chebli Mohamed

laravel job to generate file not queued properly

On production even if queue is on redis, the method is executed automatically instead of waiting file generation as it was on local. What could be the reasons?



via Chebli Mohamed

Laravel ignoring case-sensitivity in relationships when running test-suites

I have a relationship defined as :

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

When I call this relationship in test suites. I get no error. It ignores the case-sensitivity and successfully loads the class Contract instead of contract which doesn't exist.

But the same relationship when called through normal client call, it throws and error Class 'App\Models\contract' not found .

Why laravel is not throwing any error when this relationship is called through test-suites.Can we disable this behaviour?



via Chebli Mohamed

Middleware not working when created route from routeserviceprovider in laravel

Create the Route file from the Route Service Provide and assign the middleware "admin.auth" and this middlware working in the web.php giving the basic information of the admin user but from the custom.php it is not checking the auth. How can admin.auth will work from route service provider

 protected function mapWebRoutes2()
    {
        Route::group([
            'namespace' => $this->namespace,
            'prefix' => 'custom',
            'middleware' => 'admin.auth'
        ], function ($router) {

            require base_path('routes/custom.php');
        });
    }


via Chebli Mohamed

show the section based on page

I have created filter section with filter.blade.php.I have 5 selectbox in that page.I want to display only four in page1 and 5 selectbox section in page2.

In web.php

Route::get('/page1',array('middleware'=>'checksession',function(){return View('layouts.page1');}));
Route::get('/page2',array('middleware'=>'checksession',function(){return View('layouts.page2');}));

I want to display below selectbox only in page2

<div class="col-md-12">
       <!-- Card header -->
        <div class="card-header" role="tab" id="headingFive5">
            <a class="collapsed" data-toggle="collapse" data-parent="#accordionEx" href="#collapseFive5"
            aria-expanded="false" aria-controls="collapseFive5">
                <h5 class="mb-0">
                    <div id="username_view">Username</div> 
                    <img src="img/chevron-down.png" class="fa-angle-down rotate-icon">
                </h5>
            </a>
        </div>


via Chebli Mohamed

where does laravel can function for user object define?

i am working on a laravel project .almost i see in each controller these line format :

!auth()->user()->can('something (differ from each controller to other one)')

but in my php editor it says method {can} not found for this object. so i try to found method can and not found it .even i edit __Call magic method to see if when can method is calling does magic function run but i know it never run for can function.so how it is possible to link function to object when it is not defined in class and its all mother class.and where does can function locate?i search and i see laravel has some policy for authorize users but yet i don not know how can function link to user object without define in classes and even magic method does not run .and how can i develope these type of function (for authorizing in laravel and change policy)



via Chebli Mohamed

lundi 27 juillet 2020

i want to upload image into my database but i keep getting this ```C:\xampp\tmp\php4FB4.tmp``` in my database?

i only get filename in public/doc folder, i want to get filename in my database.

my html

                            
<input type="file" id="image" name="image">```


my model

```protected $fillable = [
        'created_by', 'employee_id', 'name', 'father_name', 'mother_name', 'spouse_name', 'email', 'password', 'present_address', 'permanent_address', 'home_district', 'id_name', 'id_number', 'contact_no_one', 'contact_no_two', 'emergency_contact', 'web', 'gender', 'date_of_birth', 'marital_status', 'avatar', 'client_type_id', 'designation_id', 'access_label', 'joining_position', 'activation_status', 'academic_qualification', 'professional_qualification', 'experience', 'reference',  'joining_date', 'deletion_status', 'role', 'image',
    ];```

my route
```Route::post('/people/employees/store', 'EmplController@store');```


my controller
```$filename = $request->image->getClientOriginalName();

         $request->image->move(public_path('doc'), $file_name);```


via Chebli Mohamed

Is it possible to intiailize variables in a constructor for a Laravel facade?

If I am creating a custom facade and want to have certain variables initialized at every instance of using customFacade::doSomething(), is that possible? My main purpose for doing this is to be able to store variables that are other objects and call functions on them directly. Example being customFacade::client->send() where in this case client is the initialized variable of an object with a send() function. I am aware I can have a function client() instead and return the a new instance of the object so the send() goes through, but I'd still like to know if its possible the other way.

In a normal class I can do below, but it doesn't work on facades.

$protected client;

public function __construct()
{
    $this->client = new instanceOfObject();
}


via Chebli Mohamed

how to check dublicate entry in a coloum in csv file . Can you tell me whats wrong with the code

i tried this code but when i upload a csv file even if it has no duplicate entries it show me it contain dublicates.

$chkDuplicate = false;
                        $inner_row = 0;
                        //check duplicate value on csv
                        foreach ($imported_data as $inner_key => $inner_value) 
                        {
                            if ($key != $inner_key && $product_imei == trim($inner_value[1])) {
                                $chkDuplicate = true;
                                $inner_row = $inner_key + 1;
                            }
                           
                        }

                        if ($chkDuplicate) 

                        {
                            $is_valid = false;
                            $error_msg = "Same PRODUCT IMEI in row no. $row_no and row no. $inner_row ";
                            break;
                        } 


via Chebli Mohamed

How to delete folder (and its content) not under storage/app in Laravel?

I know we can use Storage::delete() or File::delete to delete folders and/or files in laravel, but this seems not working for folders directly under storage, I mean storage/tmp by example. It only works for storage/app. How to deal with this?

if (file_exists( storage_path() . '/tmp/file1'.'.pdf' )) {
     File::delete(storage_path() . '/tmp/file1'.'.pdf') );
}

Thanks



via Chebli Mohamed

Login users created by admin in laravel

In my application, i have admin that can create different role and user to access the admin panel, for that i am inserting a new user in the user table whose structure is :

Users:

id | name | email | password | role_id

role id 1 and 2 is fixed for admin and normal customer respectively but after creating sub user that user cannot login because in the admin controller i have checked 1 role id for Admin but sub users have different roles also (for eg. Manager can have role id-4 and so on)

This is the Admin login controller snippet :

 $request->merge(["role_id" => 1]);
    if (Auth::guard('admin')->attempt([
        'email' => $request->email,
        'password' => $request->password,'role_id' => $request->role_id
    ], $request->input('remember_me'))) {
        return redirect()->intended(route('admin.dashboard'));
    }


via Chebli Mohamed

Where API credentials should be stored in laravel?

We are developing package for laravel which interact with another app through API. Currently we are storing api credentials in cache. Whenever cache get cleared connection break. We are thinking for alternative . Is this good practice to store those credentials in database? if yes how it will get refresh for next credentials?



via Chebli Mohamed

Mailable button not working ( href missing )

Im creating a mail with a button to take you to a login screen.
The mail is sent the button is rendered, but the href is missing.
I have checked the indentation and it fine, so im unsure why its rendering that way.

Mail blade

@component('mail::message')
# Introduction

Not him old music think his found enjoy merry. Listening acuteness dependent at or an.
Apartments thoroughly unsatiable terminated sex how themselves. She are ten hours wrong walls stand early.
Domestic perceive on an ladyship extended received do.
Why jennings our whatever his learning gay perceive. Is against no he without subject.
Bed connection unreserved preference partiality not unaffected.
Years merit trees so think in hoped we as.

SOME DATA: 

@component('mail::button', ['url' => $url])
    Goto questionnaires
@endcomponent

Thanks,<br>
Some Hospital team.
@endcomponent

MAIL CLASS

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Http\Request;

class QuestionnaireMail extends Mailable
{
    use Queueable, SerializesModels;

    public $someData;
    public $url;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->someData = "Some Data";
        $this->url = 'localhost:8077/login_patient';
    }

    /**
     * Build the message.
     *
     * @param Request $request
     * @return $this
     */
    public function build(Request $request)
    {
        return $this->markdown('emails.answered' );
    }
}

RENDERED BUTTON

<tr>
    <td style="font-family:Avenir,Helvetica,sans-serif;box-sizing:border-box">
        <a style="font-family:Avenir,Helvetica,sans-serif;box-sizing:border-box;border-radius:3px;color:#fff;display:inline-block;text-decoration:none;background-color:#3097d1;border-top:10px solid #3097d1;border-right:18px solid #3097d1;border-bottom:10px solid #3097d1;border-left:18px solid #3097d1">Goto questionnaires</a>
    </td>
</tr>


via Chebli Mohamed

Select rows where sum of a column equals a fixed value in Laravel

I would like to get one (or all) possible combination of rows where sum of quantity column equals 20

here an example :

id quantity
1   11          
2   1           
3   4           
4   12          
5   19          
6   10          
7   3           
8   13          
9   16          
10  14  

I want to have less rows, in this example:

5   19 

2   1

If it's impossible this one is acceptable too:

5   19 
9   16 


via Chebli Mohamed

controller changes not reflected after updated composer

I have tried to update the composer.But even not able to update the verson.After that attempt I cant do change with controller. even I changed the variable name in controller but that new variable is not renamed in controller. I have cleared view cache also but no luck



via Chebli Mohamed

dimanche 26 juillet 2020

Error: Use of undefined constant result -assumed 'result'

I'm trying to develop a website with Laravel and ican't seem to create the table 'ens' getting the following error:

Use of undefined constant result -assumed 'result' <this will throw an 
  Error in a future version of PHP>

and then it indicated the line

         $table->string('photo',150)->ingres_field_nullable(result, index); 

from the following code of ens table migration

   <?php

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

 class CreateEnsTable extends Migration
{
 
  public function up()
  {
     Schema::create('ens', function (Blueprint $table) {
        $table->increments('id');
          $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('photo',150)->ingres_field_nullable(result, index);
        $table->rememberToken();
        $table->timestamps();
    });
     }

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

I can't migrate my DB table 'ens' because of it :/

Is there anything I can do to fix it? Thank you!



via Chebli Mohamed

Laravel trailing slash connects to GET instead of POST

I have a POST route setup called user/connect which points to the relevant controller function ( which expects post varialbles), but adding a trailing slash e.g. user/connect/ redirects it to GET thus returning "MethodNotAllowedHttpException"

I am unable to remove the forward slash ( as the consuming app is sending it and i have no control ) . Any pointers on how i could get the route with the trailing slash to also point to my POST route ?



via Chebli Mohamed

Request failed with status code 405 React Native Laravel

I am having Request failed with status code 405 error when submitting the post request from React Native and using Laravel 7 in the backend.

const data = {
...
}

const headers = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Method": "POST",
    "Content-Type": "application/json",
}

axios.post(API_URL, data, headers).then((response) => {
    consoleLog("token", response.data)
    if (response.data) {
        this.setState({
            bkashURL: API_URL + response.data,
            loading: false,
        })
    }
})

Laravel Route:

Route::post('/', 'PaymentController@processInput');

enter image description here

Please help.



via Chebli Mohamed

Save images in array in session (Using dropzone library)

Hello everyone I am stuck in this. Can anybody please tell me how to save the images in the session in array only. I am using the dropzone library and here I am able to save only one image. I want that if I drop 3 -4 images at a time that my below function is called and in array only 1 index is saved. I want to save all the image in array in session. Any help is appreciated . Please answer The code I am using to save the images in database is here.

 public function image_upload(Request $request)
    {
    $names = [];
    $files = $request->file('file');
    foreach ($files as $file)
    {
        echo $names = $file->getClientOriginalName();
    }
    $image = $request->file('file');
    $profileImage = $image->getClientOriginalName();
    // Define upload path
    $destinationPath = public_path('/uploads/'); // upload path
    $extension = $image->getClientOriginalExtension();
    $image->move($destinationPath,$profileImage);
    
    $rand_num = rand ( 10000 , 99999 );
    $str = $rand_num;
    // Saving images In Database
    $imagemodel= new ImageDump();
    $imagemodel->images=$profileImage;
    $imagemodel->rand_img_id = $rand_num;
    $request->session()->put('rand_img_id', $rand_num);
    $imagemodel->save();
    return response()->json(['success'=>$profileImage]);
}


via Chebli Mohamed

How I make this query in laravel

Select a.,b.,c.* FROM ( table_3 c LEFT JOIN ( table_2 b LEFT JOIN table_1 a ON (( a.id_key = b.id_key ))) ON (( b.id_second = c.id_second ))) GROUP BY b.id_key, b.number_aa, c.number_bb

Nb: I'am using Laravel 5.8



via Chebli Mohamed

samedi 25 juillet 2020

PHP Warning: require(vendor/autoload.php)

PHP Warning: require(D:\Work\Web development\Larachat\lara-chat-app-starter/ven dor/autoload.php): failed to open stream: No such file or directory in D:\Work\W eb development\Larachat\lara-chat-app-starter\artisan on line 18



via Chebli Mohamed

I need to update existing foreign key, but I can't drop it in order to update it

I've got a migration to correct existing foreign key, it looks like this

public function up()
{
    Schema::table('content_term', function (Blueprint $table) {
        $table->dropForeign('content_term_content_id_foreign');
        $table->foreign('content_id')->references('id')->on('content')->onUpdate('cascade')->onDelete('cascade');
    });
}

The original table and foregin key looked like this

public function up()
{
    Schema::create('content_term', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedBigInteger('content_id')->unsigned();
        $table->unsignedInteger('term_id');

        $table->foreign('content_id')->references('id')->on('content')->onUpdate('cascade');
        $table->foreign('term_id')->references('id')->on('terms')->onDelete('cascade')->onUpdate('cascade');
    });
}

I forgot to add onDelete('cascade') for content_id foreign key creation and need to correct that in a new migration.

When I run php artisan migrate with thew latest migration I've added I get this

enter image description here

SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'content_term_content_id_foreign'; check that column/key exists (SQL: alter table content_term drop foreign key content_term_content_id_foreign)

MYSQL complains that the foreign key does not exist in content_term table. When I check that table using phpmyadmin I can clearly see that key exists. See attached pic for proof of that.

enter image description here

What's the problem with my new migration, why is this line causing a problem:

$table->dropForeign('content_term_content_id_foreign');


via Chebli Mohamed

how to genrate qr code in laravel for get the user detail

am try to simplesoftware package but in which same issue on size and save file so tell me brifly how to genrate QR code in laravel rest api



via Chebli Mohamed

Laravel custom query for answer and question database

I have three table called exams, questions and answers. They are connected via foreign id. I have function which i join questions and answers table. I have 1 question and multiple answers. When i join i see many same questions with 1 answer (which is normal). Is there any way to make join 1 question and multiple answers in one query(array) via query builder

Exams table

        $table->id();

        $table->string('language_code');
        $table->string('title');
        $table->integer('subcategory_id')->nullable();
        $table->string('section');
        $table->string('class');
        $table->string('subject')->nullable();
        $table->string('time')->default('60');

        $table->timestamps();

Questions table

        $table->id();

        $table->integer('exam_id');
        $table->string('q_pic')->nullable();
        $table->string('q_name')->nullable();
        $table->string('q_text');

        $table->timestamps();

Answers table

        $table->id();

        $table->integer('user_id');
        $table->integer('question_id');
        $table->text('user_answer')->nullable();
        $table->integer('user_answer_id');
        $table->integer('c_answer_id'); 

        $table->timestamps();

And here is my view function

public function view($id)
{
    $questions = DB::table('questions')
        ->leftJoin('answers','answers.question_id','=','questions.id')
        ->where('questions.exam_id','=',$id)
        ->get();

    return view('main/view',compact('questions'));
}


via Chebli Mohamed

Intervention Image Package - Can't install - file could not be downloaded

I have this error when I try to install intervention/image in Laravel 5.8:

[Composer\Downloader\TransportException] The "https://ift.tt/3f15RiW" file could not be downloaded: php_network_g etaddresses: getaddrinfo failed: No such host is known. failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known.

Could you help me to understand the error and how I can fix it, please?

Thanks in advance.



via Chebli Mohamed

How to pass big length of encrypted string url in Laravel?

I want to pass the encrypted string with URL but it's giving my 404 page can't found.

URL sample:

http://localhost/elearn/join/video/call/for/lecture/6fc1a5f5a35741988051cca196ce8609/talkme/0066fc1a5f5a35741988051cca196ce8609IABaKWU/xYxlYJKs7nVS845xc9d0YcRLJJhdUEdpTzhDs85c2l0AAAAAEADgyGnmqB4dXwEAAQCmHh1f

How can I succeed in accessing the specific route?

how to increase the encrypted character length in URL using laravel?



via Chebli Mohamed

vendredi 24 juillet 2020

laravel 5.8 language localization not working in my project

i made this localization before in another project , but this project i changed in admin middleware to make permissions for users in dashboard. this project is for two languages arabic and english it is working fine in website out admin but in admin i don't know what is the problem in my code.

now localization not working

this is my route:

Route::namespace('admin')->group(function (){
   Route::group(['middleware'=> ['web','admin']], function (){
       Route::prefix('admin-123')->group(function (){

           Route::get('locale/{locale}', function ($locale){
               \Illuminate\Support\Facades\Session::put('locale', $locale);
               return redirect()->back();
           });

and this is my middleware:

<?php

namespace App\Http\Middleware;

use App\user_permission_group;
use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use \Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Auth;

class admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!auth()->check()){
            return redirect('login');
        }

        if(Auth::user()->admin > 2)
        {
            return redirect('/');
        }

        $url = Request::fullUrl();

        $lang = explode('admin-123/locale/', $url);
//        dd($lang[1]);
        if (isset($lang[1]) && $lang[1] !='')
        {
            App::setLocale($lang[1]);
//            Session::put('locale', $lang[1]);
        }

        $admin = explode('admin-123', $url);
        $permission = explode('/', $admin[1]);

        if (isset($permission[1]) && $permission[1] !='' && $permission[1] != 'locale')
        {
            if (Request::is('admin-123/' . $permission[1] .'/*')) {
                $permissions = DB::table('permission_group_details')->select('group_id')->where('permission', $permission[1])->get();
                if ($permissions->count() > 0)
                {
                    foreach ($permissions as $per)
                    {
                        $gr_id[] = $per->group_id;
                    }
                    $grid = collect($gr_id);
                    $users = user_permission_group::where('user_id', Auth::user()->id)->whereIn('group_id', $grid)->first();

                    if (!isset($users)){ return redirect()->back(); }

                    $permission_route = DB::table('permission_group_details')->select('permission')->where('group_id' , $users->group_id)->first();
                    if (!isset($permission_route) && $permission_route =='')
                    {
                        return redirect()->back();
                    }
                }
                else{
                    return redirect()->back();
                }
            }
        }

        return $next($request);
    }
}

and this is my blade :

@if(\Illuminate\Support\Facades\App::isLocale('en'))
        @php
            $lang = 'English';
            $pull_right = '';
            $pull_left = 'pull-right';
            $rtl ='';
            $title = 'title';
            $currency = 'EGP';
            $pull = 'pull-left';
        @endphp
    @else
        @php
            $lang = 'العربية';
            $pull_right = 'pull-right';
            $pull_left = 'pull-left';
            $rtl ='rtl';
            $title = 'title_ar';
            $currency = 'جنيه';
            $pull = 'pull-right';
        @endphp
    @endif

        
    <li class="dropdown dropdown-small">
       <a href="#" class="dropdown-toggle" data-hover="dropdown" data-toggle="dropdown"><span class="value"> </span><b class="caret"></b></a>
          <ul class="dropdown-menu" style="padding: 0.5rem 1.5rem !important; margin: 0.125rem 5px 0 !important;">
               <li><a href="">English</a></li>
               <li><a href="">العربية</a></li>
           </ul>
    </li>

please help.. thanks for all



via Chebli Mohamed

laravel rest api login time accesstokn cant genrate

Call to a member function createToken() on array in file enter code here if(!Auth::attempt($user)){ return reponse(['massage'=>'error']); }enter code here $success['token'] = $user->createToken('MyApp')-> accessToken; $success['email'] = $user->email; return response()->json(['user'=>$user]);



via Chebli Mohamed

Laravel6 - View for laravel-admin

I'm trying to build an admin page with laravel-admin. I created my own admin/controller and added router::resource on admin.routes. My next work is to prepare CRUD page. I read through the manual and got a basic concept for how CRUD can be edited by using grid, detail and form. My question is how I can add an original content in those CRUD page. Where can I edit view files for each CRUD? (For example, how can I add a certain message below the input form in xxx/create page?) Thanks in advance!



via Chebli Mohamed

Passing Stripe Payment Methods to Laravel View

I am trying to load previously used cards using the Stripe API using Laravel using this link from Stripe https://stripe.com/docs/api/payment_methods/list?lang=php

Here is the snippet of code from my controller:

 $stripe = new \Stripe\StripeClient(
            'sk_test_51GueZuLq4MEy
          );


    $customer_id = "cus_HhnBT9fpjxW3hn";
    
    $paymentMethods = $stripe->paymentMethods->all([
            'customer' => $customer_id,
            'type' => 'card',
          ]);
    
    $pm = ($paymentMethods->data);
    
    return view('payment.details', $pm);

However when I am trying to pass the card data into my view I am unable to do so. The variable I am passing in views is:


The error message I get is that my variable is not recognised. The data I am trying to access is $paymentmethods->-data->card->last4

Any help is always appreciated



via Chebli Mohamed

Disable required CSRF in POST method in selected route

I have 4 router, where I need disable required CSRF in post (payments).

Route::post('createPayment', 'DotpayController@createPayment')->name('frontend.dotpay.createPayment');
Route::post('paymentConfirmation', 'DotpayController@paymentConfirmation')->name('frontend.paymentConfirmation');
Route::match(['POST', 'GET'], 'paymentConfirmationSplash', 'DotpayController@paymentConfirmationSplash')->name('frontend.paymentConfirmationSplash');
Route::get('/paymentStatus', 'DotpayController@paymentStatus')->name('frontend.paymentStatus')

How can I make it?



via Chebli Mohamed

Laravel use queue:listen but it called another file

i have new project, i create file App\Helpers\function.php in method construct() i Log::info(123). Then i run command php artisan queue:listen, supprise file function.php was called. I don't know why function.php called. I don't include it in autoload on composer.json. Please tell me why? Thank you. This is my code. enter image description here

enter image description here

enter image description here



via Chebli Mohamed

this is my code but my pagination is not working ..please guide me with similar solutions

public function index(Request $request) { if($_GET) { if(!empty($_GET['name'])&& (empty($_GET['email'])&&empty($_GET['phone']))) { $data = Users::where('name', $_GET['name'])->paginate(5); $links = $data->appends(['sort' => 'name'])->links(); return view('users.index', compact('data', 'links'));

        }
        else  if(!empty($_GET['email'])&&(empty($_GET['name'])&&empty($_GET['phone'])))
        {
            $data = Users::where('email', $_GET['email'])->paginate(5);
            $links = $data->appends(['sort' => 'email'])->links();
            return view('users.index', compact('data', 'links'));

        }
        else  if(!empty($_GET['phone'])&&(empty($_GET['name'])&&empty($_GET['email'])))
        {
            $data = Users::where('phone', $_GET['phone'])->paginate(5);
            $links = $data->appends(['sort' => 'phone'])->links();
            return view('users.index', compact('data', 'links'));

        }
        else  if(empty($_GET['phone'])&&(!empty($_GET['name']))&&(!empty($_GET['email'])))
        {
           // $data= DB::table('users')->where('name', $_GET['name'])->where('email', $_GET['email'])->get();
          //  $data = Users::where('name', $_GET['name'] )->where('email', $_GET['email'] );
            $data = Users::where('name', '=' ,$_GET['name'])->where('email', '=', $_GET['email'])->paginate(5);
             $links = $data->appends(['sort' => 'name'])->links();
            return view('users.index', compact('data', 'links'));

        }
        else  if(empty($_GET['email'])&&(!empty($_GET['name']))&&(!empty($_GET['phone'])))
        {

            $data = Users::where('name', '=' ,$_GET['name'])->where('phone', '=', $_GET['phone'])->paginate(5);
            $links = $data->appends(['sort' => 'name'])->links();
            return view('users.index', compact('data', 'links'));

        }
        else  if(empty($_GET['name'])&&(!empty($_GET['email']))&&(!empty($_GET['phone'])))
        {

            $data = Users::where('email', '=' ,$_GET['email'])->where('phone', '=', $_GET['phone'])->paginate(5);
            $links = $data->appends(['sort' => 'name'])->links();
            return view('users.index', compact('data', 'links'));

        }
        else  if(!empty($_GET['name'])&&(!empty($_GET['email']))&&(!empty($_GET['phone'])))
        {

            $data = Users::where('name', '=' ,$_GET['name'])->where('email', '=', $_GET['email'])->where('phone', '=', $_GET['phone'])->paginate(5);
            $links = $data->appends(['sort' => 'name'])->links();
            return view('users.index', compact('data', 'links'));

        }

   }

    else{
        $data = Users::orderBy('name', 'ASC')->paginate(5);
        //print_r($data);die();
        $links = $data->appends(['sort' => 'name'])->links();
        return view('users.index', compact('data', 'links'));

    }
}


via Chebli Mohamed

Laravel 5.6 is not displaying errors with line number

I am working on debugging the issues in Laravel Application. I am getting the errors but unfortunately not getting the line number. So, it is very difficult to track the issue. Because a lot of the methods are called with in a method.

I am getting the errors like this

Trying to get property 'id' of non-objectTrying to get property 'id' of non-object

Trying to get property 'id' of non-objectTrying to get property 'id' of non-object

but not getting the line number.



via Chebli Mohamed

jeudi 23 juillet 2020

Laravel: Passing a value of 0 back to controller from frontend

I have a boolean field that is represented by 0 and 1 in my database.

if ($request->input('submitted')) {
       // do code
 }

This has been working because it's only been setting the field to 1 (true) but now there's a new flow that can revert the submission.
It has not been setting it back to 0 when I pass the value 0 in from the frontend and I assume it's because that condition is getting skipped since 0 would eval to null.

Is the best way to handle it:

if (isset($request->input('submitted'))) {
           // do code
}

or would strictly checking against null work better:

if ($request->input('submitted') !== null) {
     // do code
}


via Chebli Mohamed

Trying to get property 'id' of non-object on click of the edit button


I'm new to Laravel and Stackoverflow.
I have this page where I'm displaying all the candidates who have applied for a job.
job-applications.blade.php
```
                    <thead>

                        <th style="padding:5px 22px 10px 6px !important">Candidate</th>

                        <th style="padding:5px 22px 10px 6px !important">Status</th>

                        <th style="padding:5px 22px 10px 6px !important">Edit</th>


                    </thead>

                    <tbody>

                        @foreach ($applications as $application)

                        <tr>

                            <td>

                            <a class="text-center" href=""

                                target="_blank" class="text-theme"></a>

                            </td>
                     
                            <td>

                                

                            </td>

                            <td>

                                    <a href="route('employers.applicants.edit', $applicant->id)" class="mt-1 text-center btn-sm btn btn-outline-yellow"> <i class="fa fa-pencil"></i> Edit</a> 

                            </td>

                        </tr>
                    </tbody>
                 </table>
<br>
Whenever I'm clicking on the edit button it is showing the error that "Trying to get property 'id' of non-object".<br>
Here's my controller code for jobApplications,<br>

public function jobApplications($slug)

{



    if (!Auth::check()) {

        session()->flash('error', 'Sorry !! You are not an authenticated Employer !!');

        return back();

    }

    $user = Auth::user();

    $user_id = $user->id;

    $applicant = DB::table('job_activities')->where('user_id',$user_id)->get();

    $job = Job::where('slug', $slug)->first();

    $expreience_data = Experience::all();

    $query = JobActivity::query();

    $applications = $query->where('job_id', $job->id)->get();

    $experiences = [];

    $education = [];

    $application_data = [];

    foreach ($applications as $application) {

        // Filter

        if (isset(request()->exp)) {

            $exp_data = CandidateProfile::with('experience')->where('experience_id', request()->exp)->where('user_id', $application->user_id)->first();



            if ($exp_data) {

                $experiences[] = $exp_data;

                $education[] = UserQualification::where('user_id', $application->user_id)->first();



                $application_data[] = $application;



                $filter['exp'] = request()->exp;

            }

            

        }else{

            $experiences[] = CandidateProfile::with('experience')->where('user_id', $application->user_id)->first();

            $education[] = UserQualification::where('user_id', $application->user_id)->first();



            $application_data[] = $application;

        }

       

        

    } 

    $education = $education ? $education[0] : [];

    $experience = $experiences ? $experiences[0] : [];

    $applications = $application_data;

    return view('frontend.pages.employers.job-applications', compact('user', 'applicant', 'job', 'applications','experience', 'education', 'filter', 'expreience_data'));



}

It is giving error on the line: $applications = $query->where('job_id', $job->id)->get();
As per the solutions I could find over internet it's because I'm trying to assign a object type id to an array applications. I tried to change the first() to get() on $jobs variable but then it's giving the error that "property [id] doesn't exist on this collection instance". I hope I've made myself clear here. Please suggest something to resolve this error. Thanks.



via Chebli Mohamed

Adding page number to a PDF file using DOMPDF issue in laravel

When i upload a PDF file to add page number in it the function remove the all data in the file and add the page number.

Controller:

public function numbering(Request $request){
        $data = $request->all();
        if($request->hasFile('file')){
            $pdf = app('dompdf.wrapper');
            $pdf->getDomPDF()->set_option("enable_php", true);
            $pdf->loadView('numbering', $data);
            $name = time() . '.' . '.pdf';
            $destinationPath = public_path('/pdf_file');
            $numberfile = $destinationPath . '/' . $name;
            $pdf->save($numberfile);
            return response()->json(['code' => 200, 'success' => 'Data Updated Succesfully', 'file' => $name]);
        }
        else{
            return response()->json(['code' => 422, 'error' => 'NO File Found. ']);
        }
    }

BLade for Page Numbering

   <body>
<script type="text/php">
    if (isset($pdf)) {
        $x = 250;
        $y = 10;
        $text = "Page {PAGE_NUM} of {PAGE_COUNT}";
        $font = null;
        $size = 14;
        $color = array(255,0,0);
        $word_space = 0.0;  //  default
        $char_space = 0.0;  //  default
        $angle = 0.0;   //  default
        $pdf->page_text($x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle);
    }
</script>
</body>


via Chebli Mohamed

mercredi 22 juillet 2020

Where to put pagination logic in MVC

I am confused as to where the pagination logic belongs in MVC such as

  • Generating the limit and offset results - this should ideally be done in the model, where model is where all database queries are.
  • Generating metadata (next_page, last_page, total) - not sure

The framework I am currently using, laravel, uses a .paginate method on a query instance like:

DB::table('users')->paginate();

The paginate method is called from a query builder instance and returns the database results along with the page metadata. I am confused because this seems to do many things at once.

so the core of my question is: where should we put pagination logic in MVC?



via Chebli Mohamed

Tried to run php artisan migrate:fresh after install voyager it's give me this error

**Migrating: 2016_01_01_000000_add_voyager_user_fields

Illuminate\Database\QueryException

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'jaleed.users' doesn't exist (SQL: alter table users add avatar varchar(255) null default 'users/default.png' after email, add role_id bigint null after id)

at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671 667| // If an exception occurs when attempting to run a query, we'll format the error 668| // message to include the bindings with SQL, which will make this exception a 669| // lot more helpful to the developer instead of just the database's errors. 670| catch (Exception $e)

enter image description here

enter image description here



via Chebli Mohamed

Web Cam preview in Media Stream Recording API

I want to make a screencasting web application using MediaRecorder API, Laravel & Vue.js By using this application a user can record his system screen along with his webcam preview.

These are the functionality which I want to in the application

1.Webcam preview should always be visible on the screen even if the user minimizes the browser or opens any other application on the screen.

2.Webcam preview should be draggable and resizeable and can be changed from rectangular preview (default preview) to circular preview & users can have some option to change the border of the preview screen.

Can anyone please let me know it is possible to make something like this using MediaRecorder Recording API, Laravel & Vue.js

enter image description here



via Chebli Mohamed

Problem trying to use elements from main query in subquery (Eloquent)

I'm trying to write a query using Laravel Eloquent methods, the original query looks like this:

SELECT distinct
    a.*, b.*
FROM
   a
INNER JOIN b ON
   a.id = b.id
WHERE
    a.id > 10
    AND NOT EXISTS(
        SELECT c.id
        FROM c
        WHERE 
            c.id = a.id
    )

What I was trying is looking like this right now:

\DB::table('a')
    ->join('b', 'a.id', '=', 'b.id')
    ->select('a.*', 'b.*')
    ->whereRaw('a.id > 10')
    ->whereNotIn('a.id', function($id) {
        $id = \DB::table('c')
            ->where(function($query) {
                $query->where('c.id', '=', 'a.id');
             })
             ->get();
        })
    ->distinct()->get()->first();

The problem I'm having is that I get an error converting type nvarchar to bigint cause in the line where I do '$query->where('c.id', '=', 'a.id');', I can't use the 'a.id' since I'm in a subquery and the 'a' information is in the main query. Any ideas on how I could implement this?



via Chebli Mohamed

Laravel Intervention: Unable to init from given binary data

I'm using Laravel 5.6 to let users upload their profile photo. On production, I've got some cases that returned error

Unable to init from given binary data.

Got like 5 errors from the last 2,000 users uploads (0.25%). Pretty low, but these users are important users that I want to keep.

I use Dropzone as a frontend, and send only image data to Controller via Ajax Post.

Here is the Controller:

public function savePhotos(Request $request) {
    if(!$_FILES["file"]["error"]){
        $file = $request->file('file');
        $ext = $file->getClientOriginalExtension();
        $filename = Auth::user()->id . '.' . $ext;
        $filePathAndName = 'uploaded/'.$filename;

        Storage::disk('original_images')->put($filePathAndName, file_get_contents($file -> getRealPath()));

        //generate thumbnail
        try{
            $img = Image::make(Storage::disk('original_images')->get($filePathAndName));
            $img->orientate()->fit(200, 240);
            $newImg=Image::canvas(200, 240, '#ffffff')->encode('jpg',75); //create a blank image 200x240 px with white background
            $newImg->insert($img, 'center'); //paste resized img to new blank image
            Storage::disk('thumb_images')->put($filePathAndName, (string) $newImg->encode());
        } catch (ErrorException $e) {}
    }
}

The error happened at line with Image::make(), even it's in the try catch block. I've checked all uploaded files and there are 2 cases of error here.

  1. Some entry level Android phones upload 0 bytes image.

  2. iPhones (iOS13/Safari) upload images that I can download them from server, and view on my Windows machine. But Laravel somehow couldn't process them, and return said error.

For those images uploaded from iPhone, I can't share them since it's the facial of the uploaders. Can't break privacy law. Instead, I could share exifs. Both are .JPEG.

Upload from iPhone #1:

Camera: Apple iPhone 8
Lens:   iPhone 8 back camera 3.99mm f/1.8 Shot at 4 mm
Exposure:   Auto exposure, Program AE, 1/5 sec, f/1.8, ISO 100
Flash:  Off, Did not fire
File:   1,181 × 1,475 JPEG (1.7 megapixels)   504,666 bytes (493 kilobytes)
Color Encoding: WARNING: Embedded color profile: “(unrecognized embedded color profile 'Display P3')”
JFIF Version 1.01
Resolution  72 pixels/None
File Type   JPEG
File Type Extension jpg
MIME Type   image/jpeg
Exif Byte Order Big-endian (Motorola, MM)
Encoding Process    Baseline DCT, Huffman coding
Bits Per Sample 8
Color Components    3
File Size   493 kB
Image Size  1,181 × 1,475
Y Cb Cr Sub Sampling    YCbCr4:2:0 (2 2)

Upload from iPhone #2, surprisingly the image was taken by Canon 5D:

Camera: Canon EOS 5D Mark II
Lens:   85 mm
Exposure:   Manual, 1/125 sec, f/9, ISO 100
Flash:  none
File:   1,800 × 2,400 JPEG (4.3 megapixels)   589,171 bytes (575 kilobytes)
Color Encoding: WARNING: Embedded color profile: “(unrecognized embedded color profile 'Display P3')”
XMP Toolkit Adobe XMP Core 5.6-c140 79.160451, 2017/05/06-01:08:21
Creator Tool    Adobe Photoshop CS6 (Windows)
Photographic Sensitivity    100
Exif Image Size 1,800 × 2,400
Make    Canon
Camera Model Name   Canon EOS 5D Mark II
Software    Adobe Photoshop CS6 (Windows)
Exposure Time   1/125
F Number    9.00
Exposure Program    Manual
ISO 100
Shutter Speed Value 1/125
Aperture Value  9.00
Exposure Compensation   0
Metering Mode   Multi-segment
Flash   No Flash
Focal Length    85.0 mm
JFIF Version    1.01
Resolution  72 pixels/None
File Type   JPEG
File Type Extension jpg
MIME Type   image/jpeg
Exif Byte Order Big-endian (Motorola, MM)
Encoding Process    Baseline DCT, Huffman coding
Bits Per Sample 8
Color Components    3
File Size   575 kB
Image Size  1,800 × 2,400
Y Cb Cr Sub Sampling    YCbCr4:2:0 (2 2)

PHP.ini

upload_max_filesize = 10M


via Chebli Mohamed

Copy or create file on remote FTP

So, I have tried 4 different ways of doing this, none of them worked.

There's a 3rd party server that I can create and delete files on via Filezilla. This was for testing purposes however.

There's a script on my Laravel application that'll run once a day, create a few XML files and those need to automagically transfer to that same server.

When I create an ftp filesystem I get the error "ftp_rawlist(): php_connect_nonb() failed: Operation now in progress (115)" after a timeout.

When I try PHP's ftp_put or ftp_fput I get the error "ftp_put(): php_connect_nonb() failed: Operation now in progress (115)" (or ftp_fput, same error).

When I try PHP's fwrite with the ftp as a destination I get the error "failed to open stream: operation failed". This also fails in the browser.

I have made sure credentials are correct. I've copy/pasted them from the working Filezilla connection details.

Filesystem code:

        'ftp' => [
            'driver' => 'ftp',
            'host' => env('FTP_HOST'),
            'username' => env('FTP_USERNAME'),
            'password' => env('FTP_PASSWORD'),
            'root' => '/Production',
            'ssl' => true,
            'ignorePassiveAddress' => true,
        ],

I know about the server behind NAT problem, but it won't accept my changes to use original address in filesystems. I've cleared cache, and config and fed the hamsters, but nothing changes.

I'm honestly at the end of my knowledge right now. And asking the 3rd party to change their configuration/settings isn't an option. This server is one of many and they're all exactly the same, but different clients. They might help me by providing the logs on their end, but that's about it.

The only other that I see which could be a difference is that I'm running this code from command line (ie, as if it's run via cron). Not sure if that causes problems with connecting and creating files on a remote server. I'm not that experienced with writing Laravel commands.

Any help would be greatly appreciated.



via Chebli Mohamed

how stay in the current page after update a row with datables plugins and laravel

in this case , when I selected the 2+th page (for exemple the 5th page ) and update a row , the table return me to the first page , I dont get what happen , I used enter image description here

and

enter image description here

but the problem stay ,,, any idea please , thanks



via Chebli Mohamed

Laravel-5 SMTP mail

There isnt any error but dont send email this code. Why ?

public function sendEmailReminder() {

    `enter code here`Mail::send([],[],function($message){
    $message->from('destek@crm.gen.tr', 'Your Application');

    $message->to('birgul@laysos.com.tr')->subject('Your Reminder!');
   });

    return back()->with('success','email gönderildi');
}


via Chebli Mohamed

mardi 21 juillet 2020

Laravel: fwrite(): send of 18 bytes failed with errno=10054 An existing connection was forcibly closed by the remote host

I am trying to make the "forgot password" function work on Laravel. I am using mailtrap. it was working fine a couple of weeks ago but now it shows me this error that an existing connection was forcibly closed by the remote host. please help

enter image description here



via Chebli Mohamed

How to pass dynamic table name to model according user's input in Laravel

I have a project that the column_field is dynamic, it's generated according to the user's input. Now I want to set that table dynamically, according to the user's input also. And is this possible without doing php artisan migrate?

Here what I want to do inside my Model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    $tableName = 'users_input';

    protected $guarded = [];
    protected $table = $tableName;
    public $timestamps = false;
    protected $primaryKey = 'id';
}

Waiting for your suggestions.

Cheers



via Chebli Mohamed

Laravel API: Product filtering and sorting together

I want to filer product list and sort it too. I have 2 tables for product data.

Products -> [id, name, description, point, data, etc.]

in this table, data is a json object. This object contains all the specifications of a product. Ram, Camera, storage etc. I want to filter data using these specs too. Filter using ram for example.

Prices -> [id, porduct_id, link, price]

one product can have multiple prices but i need to filter using only minimum price. And if I want to sort it, minimum price will be considered for sorting.

I have implemented code for filter. But I'm stuck at implementing sort after filter. Price range filter with sorting by price seems difficult for me. can anyone help me out?

Current code for price range filter

        if (isset($filters['price'])) {
            $product = $product->whereHas('prices', function ($query) use ($filters) {
                $query->whereBetween('price', [$filters['price']['min'], $filters['price']['max']]);
            });
        }

Current code for other data filters:

        if ($request->has('filters') && !empty($filters = $request->get('filters'))) {
            $product = $product->filter($request->get('filters'));
        }

Current code for sorting by price

        if ($request->has('price')) {
            $direction = in_array($request->query('price'), ['asc', 'desc']) ? $request->query('price') : 'asc';

            return ProductResource::collection(
                $product
                    ->addSelect(['min_price' => Price::select('price')
                        ->whereColumn('product_id', 'products.id')
                        ->oldest('price')
                        ->take(1)
                    ])
                    ->orderBy('min_price', $direction)
                    ->paginate(self::PAGINATE_NUMBER)
            );
        }

I'm stuck at doing both of these operation together. If you need more info about this question, please comment.



via Chebli Mohamed

How to check an array value is available in session array in laravel?

How to check an array value is available in session array in laravel?

My Seesion array look like

Array ( 
       [0] => Array ( 
                     [id] => qwewa,
                     [prod_name] => p1
                    ) 
       [1] => Array ( 
                     [id] => asdsa,
                     [prod_name] => p2
                    )
      )

i want to check whether a particular id is available in my session array or not. i tried with pluck, has, data get

Suggest me how to in_array function in laravel effectively.



via Chebli Mohamed

Laravel same code was working but now giving "Found empty contents" error

here is my log data

#0 /home/path/to/project/vendor/simplesoftwareio/simple-qrcode/src/SimpleSoftwareIO/QrCode/BaconQrCodeGenerator.php(74): BaconQrCode\Writer->writeString(NULL, 'ISO-8859-1', 1)

#1 /home/path/to/project/app/Http/Controllers/TicketDPController.php(1405): SimpleSoftwareIO\QrCode\BaconQrCodeGenerator->generate(NULL)

#2 [internal function]: App\Http\Controllers\TicketDPController->ImplementationSheetPDF('62374')

#3 /home/path/to/project/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array(Array, Array)

#4 /home/path/to/project/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\Routing\Controller->callAction('ImplementationS...', Array)

#5 /home/path/to/project/vendor/laravel/framework/src/Illuminate/Routing/Route.php(212): Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), Object(App\Http\Controllers\TicketDPController), 'ImplementationS



via Chebli Mohamed

I need help whit laraver

Hello why i get this error?

I need small help!

There is Error code!

ErrorException Invalid argument supplied for foreach() (View: F:\server\htdocs\yii\yumypizza\resources\views\shop\shopping-cart.blade.php)

here is my code from shop.shopping-cart

@extends('layouts.master')

@section('title')

THE YUMMI PIZZA
@endsection
@section('content')
  @if(Session::has('cart'))

   <div class="row">
        <div class="col-sm-6 col-md-6 col-md-offset-3 col-sm-offset-3">
            
            <ul class="list-group">
                    @foreach($products as $product)
                    <li class="list-group-item">

                        <span class="badge"></span>
                        <strong></strong>
                        <span class="label label-success"></span>

                        <div class="btn-group">
                            <button type="button" class="btn btn-primary btn-xs dropdown-toogle" data-toggle="dropdown">Action <span class="caret"></span></button>
                            <ul class="dropdown-menu">
                                <li><a href="">Reduce by 1</a></li>
                                <li><a href="">Reduce All</a></li>
                            </ul>
                        </div>

                    </li>
                    @endforeach
            </ul>
            
        </div>
   </div>
   <div class="row">
    <div class="col-sm-6 col-md-6 col-md-offset-3 col-sm-offset-3">
        <strong> Total: </strong>
   
        </div>
   </div>
   <hr>
   <div class="row">
    <div class="col-sm-6 col-md-6 col-md-offset-3 col-sm-offset-3">
        <button type="button" class="btn btn-success">CheckOut</button>
   
        </div>
   </div>
@else
<div class="row">
    <div class="col-sm-6 col-md-6 col-md-offset-3 col-sm-offset-3">
        <h2>No Items in Cart!</h2>
</div>
</div>
@endif
@endsection

and here is my controller function code.

public function getCart() {
        if (!Session::has('cart')) {
            return view('shop.shopping-cart', ['products' => null]);
        }
        $oldCart = Session::get('cart');
        $cart = new Cart($oldCart);
        return view('shop.shopping-cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice]);
     } 
}

and Route.

    Route::get('/add-to-cart/{id}', [
        'uses' => 'ProductController@getAddToCart',
        'as' => 'product.addToCart'


]);

Route::get('/shopping-cart', [
    'uses' => 'ProductController@getCart',
    'as' => 'product.shoppingCart'


]);

If you can help me about this !



via Chebli Mohamed