vendredi 29 mars 2019

Laravel 5.1 How to Log - PHP Fatal error: Allowed memory size of X bytes exhausted

I am having this random out of memory issue in my production for specific api's calls. Laravel log has nothing logged. I am not able to figure out for what parameters it is going out of memory.

Is there a way to setup register_shutdown_function and put it in Laravel somewhere, where in I can put the stack trace in the log. Or any other way to log the error and stack trace for the same?



via Chebli Mohamed

jeudi 28 mars 2019

Displaying base64 encoded image inside of laravel's Email Template

I have an image i converted to base 64 encoded image. I am sending the image via email in laravel. I have tried attaching it as an inline image as well as an attachment. But as an inline image the image does not display but shows the base 64 code on the email page. As an attachment the attached image has nothing inside of it. It work well if i render in laravel's blade template view. But in laravel's email template view. It does not work. Why??

Here is my code below



via Chebli Mohamed

mercredi 27 mars 2019

Cannot read property 'rows' of undefined

Getting Cannot read property 'rows' of undefined even after I have set the id to the table row

I have read through the questions posted related to this error but still could'nt solve my problem

Uncaught TypeError: Cannot read property 'rows' of undefined phonegap

Cannot read property 'row' of undefined

https://datatables.net/reference/option/rowId

$('#deliverytable').on( 'click', 'tr', function () {
var deliveryid = deliverytable.row( this ).data().deliveryform.Id;
});
console.log(deliveryid)

The console.log returns "undefined"

This is the table

deliverytable=$('#deliverytable').DataTable( {
 columnDefs: [{ "visible": false, "targets" :[1,2,3]},{"className": "dt-center", "targets": "_all"}],
          responsive: false,
          colReorder: false,
          dom: "Blftp",
          sScrollX: "100%",
          bAutoWidth: true,
          sScrollY: "100%",
          rowId:"deliveryform.Id",
          scrollCollapse: true,
          //The error comes from here
          fnInitComplete: function(oSettings, json) {
          $('#mypendingdeliverytab').html("My Pending Delivery" + "[" + 
          deliverytable.rows().count() +"]")

                                  },
columns: [
         { data: null, "render":"", title:"No"},
         { data: "deliveryform.Id"},
         { data: "deliverystatuses.Id"},
         { data: "requestor.Name", title:"Requestor"},
         { data: "roadtax.Vehicle_No",title:"Vehicle No"},
         { data: "roadtax.Lorry_Size",title:"Size"},
         { data: "driver.Name",title:"Driver"},
         { data: "deliveryform.delivery_date",title:"Date"},
         { data: "radius.Location_Name",title:"Site"},
         { data: "projects.Project_Name", title:"Project Name"},
         { data: "options.Option", title:"Purpose"},
         { data: "deliveryform.PIC_Name", title:"PIC Name"},
         { data: "deliveryform.PIC_Contact", title:"PIC Contact"},
         { data: "deliveryform.Remarks", title:"Remarks"},
         ],
         select: {
                   style:    'os',
                   selector: 'tr'
                  },

         buttons:[],
});

The error comes out whenever I try to retrieve the row id. From the row that I have commented // on I received this Cannot read property 'rows' of undefined



via Chebli Mohamed

lundi 25 mars 2019

Auto-fill in textbox based on select option

I am creating a table which when "Item" is selected, the description will be filled automatically based on select option.

I have referred to some other links like:

Auto fill field depending on the option selected

https://www.reddit.com/r/laravel/comments/adg9s5/make_a_text_box_automatically_fill_depending_on/

but none of them answer my question.

Here's my script

$('#item').change(function(e){
     var element = $(this).find('option:selected'); 
     var desc = element.attr("Description");
    $('#Description').text(desc);
    console.log(desc)

});

This is for the item

<select class="form-control select2" id="item" name="item">
<option value="" disabled selected>None</option>
@foreach ($deliveryitems as $items)
<option  value=""></option>
@endforeach
</select>

This is for the description

<input type="text" class="Description form-control" name="Description" id="Description" readonly>


This is my controller

$deliveryitems = DB::table('inventories')
        ->leftJoin('deliveryitem','inventories.Id','=','deliveryitem.inventoryId')
        ->select('inventories.Id','deliveryitem.formId','inventories.Item_Code','inventories.Description','inventories.Unit','deliveryitem.Qty_request')
        ->get();

How to auto fill in the item description based on the item selected from the select options?



via Chebli Mohamed

I am facing a problem deploying my Laravel project to subdomain in the server

I am facing a problem deploying my Laravel project to subdomain in the server. I keep getting this error (There is no existing directory at "/Users/../../../storage/logs" and it’s not buildable: Permission denied.

I did exactly as described in this video (https://www.youtube.com/watch?v=2Rbpb56esyg) to deploy my larvel project to the subdomain. However, I keep getting this error (There is no existing directory at "/Users/../../../storage/logs" and it’s not buildable: Permission denied.

To solve this error I did:

php artisan route:clear php artisan config:clear php artisan cache:clear

then compress the project again and re-upload it to the server. However I got another error which is (500 Whoops, something went wrong on our servers

I expect the laravel project to work properly in the subdomain.



via Chebli Mohamed

dimanche 24 mars 2019

Getting issue like "Class 'App/Category' not found"

I am just trying to post for frontend page, everything was working perfectly, when I created category then it's showing error.

ErrorException (E_ERROR) Class 'App/Category' not found (View: C:\xampp\htdocs\CA\resources\views\welcome.blade.php)



via Chebli Mohamed

mercredi 20 mars 2019

Laravel's localization on JavaScript Variables

I have some JavaScript variables that I output on a rating scale as shown below.

I now want to achieve Laravel's localization therefore translate the variables before outputting them on the browser.

How can I achieve this? I tried as below but it does not get converted.

var ratingScale = {1: 'Terrible, 2: 'Poor', 3: 'Average', 4: 'Good', 5: 'Excellent'}; 

I would want to Localize the variables Terrible, Poor, Average, Good, and Excellent.

I tried this

var one = "<?php echo trans('form.one'); ?>";

var ratingScale = {1: one, 2: 'Poor', 3: 'Average', 4: 'Good', 5: 'Excellent'};

But on the browser this is outputted <?php echo trans('form.one'); ?>

Anyone lead me here?



via Chebli Mohamed

Getting issue "Class 'App/Category' not found"

In Category.php

namespace App;

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

and in Controller.php

namespace App\Http\Controllers;

use App\Models\Category;

use App\Setting;

use App\Post;

use function GuzzleHttp\Promise\all;

use Illuminate\Http\Request;



via Chebli Mohamed

samedi 16 mars 2019

Save data generated to a specific table in database

This is the output in my view

This is the code in my controller

public function showFinalYear(){

    $finalyear_students = Matrix::get()->where('total_subject_left','<',10);

    return view('admin.final_year_list')->with(compact('finalyear_students'));}

This is the code in my model

class Matrix extends Model
{
  protected $table = 'matrices';
  public $timestamps = false;

  public function getSubjects()
  {
    $subjects = [];
    $subjects[] = $this->S1 == 1 ? 'S1' : null;
    $subjects[] = $this->S2 == 1 ? 'S2' : null;
    $subjects[] = $this->S3 == 1 ? 'S3' : null;
    $subjects[] = $this->S4 == 1 ? 'S4' : null;
    $subjects[] = $this->S5 == 1 ? 'S5' : null;
    $subjects[] = $this->S6 == 1 ? 'S6' : null;
    .... and so on

    $subjects = array_filter($subjects);

    return implode(',', $subjects);
   }
 }

This is my code in the view

<tbody>
  @foreach ($finalyear_students as $fy)
    <tr class="gradeX">
      <td></td>
      <td></td>
    </tr>
  @endforeach
</tbody>

the problem happened when I want to save the student name and subjects based on the output where the code save the student name and subject doesn't work.

This is what I have tried but it does not work.

public function showFinalYear(){

    $finalyear_students = Matrix::get()->where('total_subject_left','<',10);

    DB::table('finalyear_students')
        ->updateOrInsert(
            ['student_name'=>$finalyear_students->student_name],
            ['subject'=>$finalyear_students->getSubjects()]
        );

    return view('admin.final_year_list')->with(compact('finalyear_students'));
}

Hopefully, someone can help me to solve this, Thanks in advance



via Chebli Mohamed

jeudi 14 mars 2019

Getting error when click in my second post for the single page

When I am trying to open first post in single page, it's opening and when trying to open my second post in single page it;s showing "Trying to get property 'title' of non-object"

Here is code

FrontendController

public function singlePost($slug)
{

    $post= Post::where('slug', $slug)->first();


    return view('single')->with('post', $post)


        ->with('title', $post->title)
        ->with('settings', Setting::first())
        ->with('categories', Category::take(4)->get());

}

single.blade.php

in that I am using same frontend controller for same page @extends('layouts.frontend')

@section('content')

<div id="product-post">
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="heading-section">

                    <img src="" alt="" />
                </div>
            </div>
        </div>
        <div id="single-blog" class="page-section first-section">
            <div class="container">
                <div class="row">
                    <div class="product-item col-md-12">
                        <div class="row">
                            <div class="col-md-8">

                                <div class="product-content">
                                    <div class="product-title">
                                        <h3></h3>
                                        <span class="subtitle">4 comments</span>
                                    </div>
                                    <p>
                                        {!! $post->content!!}

                                    </p>
                                </div>



                                <div class="leave-form">
                                    <form action="#" method="post" class="leave-comment">
                                        <div class="row">
                                            <div class="name col-md-4">
                                                <input type="text" name="name" id="name" placeholder="Name" />
                                            </div>
                                            <div class="email col-md-4">
                                                <input type="text" name="email" id="email" placeholder="Email" />
                                            </div>
                                            <div class="subject col-md-4">
                                                <input type="text" name="subject" id="subject" placeholder="Subject" />
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="text col-md-12">
                                                <textarea name="text" placeholder="Comment"></textarea>
                                            </div>
                                        </div>
                                        <div class="send">
                                            <button type="submit">Send</button>
                                        </div>
                                    </form>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




@endsection



via Chebli Mohamed

mercredi 13 mars 2019

Laravel Optimise sum query

I would like to get sum go deposit, withdraw and net count. Currently, I have ~10,335,633 rows data(~1.8GB), it takes more than 7 seconds to calculate the sum. How should I improve my query to make it faster?

Query:

        $depositQuery = Deposit::whereBetween('created_at', [$start, $end])->approved();
        $withdrawQuery = Withdraw::whereBetween('created_at', [$start, $end])->approved();
        if($request->has('user_id')){
            $depositQuery = $depositQuery->where('user_id', $request->user_id);
            $withdrawQuery = $withdrawQuery->where('user_id', $request->user_id);
        }
        $deposits = $depositQuery->sum('amount');
        $withdraws = ($withdrawQuery->sum('amount'))*-1;
        $net = $deposits + $withdraws;

Result:

Deposit     Withdraw     Net Amount
20,946.00   15,066.00    5,880.00



via Chebli Mohamed

mardi 12 mars 2019

Apply middleware when URL pattern matches in Laravel

I am trying to add a simple middleware to my project that checks if a user is allowed to access a project. My approach is:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


class UserProjectFit
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if ($request->is('*/projects/*')) {

            $projectUserId = DB::table('project_user')
                ->where('project_id', '=', $request->project['id'])
                ->where('user_id', '=', Auth::user()->id)
                ->first();

            if (is_null($projectUserId)) {
                abort(404);
            }

        }

        return $next($request);
    }
}

It basically works, but I have also routes like e. g. projects/create and here the middleware kicks in too. The idea would be that the middleware only takes action in case the URL contains the string project and an id, e. g. …projects/1/…

What would be a good way to solve that? If my approach isn't good, I am happy to read your suggestions.



via Chebli Mohamed

samedi 9 mars 2019

Composer update issues

I ran php composer.phar update using ssh on my shared hosting, it installed/updated the dependencies and upgraded my laravel 5.1 to 5.7 but then i got these fatal errors when i opened my site that was previously returning 404 error on all pages except the homepage, now it's saying it can't find some files

Class 'Illuminate\Routing\ControllerServiceProvider' not found [Symfony\Component\Debug\Exception\FatalThrowableError]

Now even the homepage is not working anymore.

Note: i followed instructions from previous question here and removed the entries from config/app but that did not fix it.



via Chebli Mohamed

mercredi 6 mars 2019

How can i install composer.json and all the dependencies without creating a new project on shared hosting

I already have composer.phar installed at /home3/username/laravel folder but it is still requesting for composer.json and composer.lock which i do not have. How can i get these without running composer create-project laravel/laravel {directory} "5.0.*" --prefer-dist I already have an existing laravel project i just need the composer.json and all the dependencies



via Chebli Mohamed

Loop Multidimensional array in Controller

I need to loop in a mulitidemnsional array being consumed in an outbound API. After consuming the API in a controller, I need to insert the looped records in a Model.

So, the response recieved from the external API is the following:

enter image description here

So, what Im doing in my controller function is the following:

public function index()
{

    $client = new \GuzzleHttp\Client();
    $response = $client->request('GET', 'http://api', [
        'headers' => [
             'x-authtoken' => '0275d',
             'cache-control' => 'no-cache'],
             'decode_content' => false
    ]);

     //get body content
    $body = $response->getBody()->getContents();
    $data = json_decode($body, true);

    foreach ( $data['content']['Propiedades'] as $propiedades )
        {
            $id = Arr::get($propiedades, 'Id');
            $Moneda = Arr::get($propiedades, 'Precio.Moneda');
            $Precio = Arr::get($propiedades, 'Precio.Valor')
        }

}

The problem is that im looping just one instance of "propiedades" array.

enter image description here

1. How can I loop all "propiedades" array and retrieve key values from it?

2. How can access each "propiedades" array to the next nested array and bring back those nested values realted to the first array level? For example, my result must be for each property record:

Propiedades.Id

Propiedades.Precio.Moneda

Propiedades.Precio.Valor

3. Ones I get all the "propiedades" with their values, do I need to create an array to insert those records in a Model? How do I pass the data to the model? My Models will have the structure as the array recevied from the API with the corresponding child entities for "propiedades"


Thanks in advance! Regards



via Chebli Mohamed

Laravel 5 session disappearing after redirection

In laravel 5.7, session is getting disappeared after redirecting to another page. I am working on an application in which I am pushing users to the payment gateway page before which I am storing the data in a session as per laravel documentation. After coming back from the payment gateway when I try to retrieve that session it returns empty. Can anyone please tell me how can I resolve this issue.

My code is something like this

public function processPayment(Request $request)
 {
    //...........
    session()->put('order_checkout_data', [
        'gateway' => 'paypal',
        'data' => $paypalData
    ]);

    //$request->session()->save();  <!-- This i tried after reading some solution but didnt help

    //print_r(session('order_checkout_data')) <!-- I can see the session here

    $paypal = new PayPal();
    $response = $paypal->purchase($paypalData);

    if ($response->isRedirect()) {
        $response->redirect(); //This is where redireting to paypal
            }
}

public function handleGatewayResponse(Request $request){
    print_r(session('order_checkout_data')); //No data
}

I tried with session global function and facade as well , like these

Session::put('order_checkout_data', [
            'gateway' => 'paypal',
            'data' => $paypalData
        ])

and also

session(['order_checkout_data'=>[
            'gateway' => 'paypal',
            'data' => $paypalData
        ]])

But no value. My env settings likes this

SESSION_DRIVER=file
SESSION_LIFETIME=360

I tried to go through some of the links with a similar problem but that didn't help. Here are the links that I have followed :



via Chebli Mohamed

mardi 5 mars 2019

Laravel 5 : Ajax response download not working

Tried below code:

$headers = [
        'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0',
        'Content-type'        => 'text/csv',
        'Content-Disposition' => 'attachment; filename=list.csv',
        'Expires'             => '0',
        'Pragma'              => 'public'   
      ];

    $list = List::all()->toArray();

    # add headers for each column in the CSV download
    array_unshift($list, array_keys($list[0]));
    $FH = fopen(storage_path('list.csv'),'w');
    foreach ($list as $row) { 
        fputcsv($FH, $row);
    }
    fclose($FH);

    $path = storage_path('list.csv');

    return response()->download($path, 'list.csv', $headers);

Below will out put in inspect element network call

enter image description here

I have got the same issue in Stack overflow but not working for me. Exporting CSV response laravel 5.5 and download as csv file

Can have any idea regarding this what I have missing in here?



via Chebli Mohamed

lundi 4 mars 2019

Passing data to the intermediate table using sync() in Laravel 5.1

I've got the following, which works as expected:

$aircraft->logbook_entries()->sync($request['tasks']);

I want to add "work_order_id" to my pivot table, so I've done the following:

  • Added ->withPivot('work_order_id') to the Aircraft and Task models in the appropriate belongsToMany relationships
  • Updated my query to read $aircraft->logbook_entries()->sync([1 => ['work_order_id' => $workorder->id], $request['tasks']]);

This does not add the work_order_id to the pivot table as desired. Instead I get the error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (pams_amo.airframe_logbook_entries, CONSTRAINT airframe_logbook_entries_work_order_id_foreign FOREIGN KEY (work_order_id) REFERENCES work_orders (id)) (SQL: insert into airframe_logbook_entries (aircraft_id, created_at, task_id, updated_at) values (1, 2019-03-04 22:11:48, 12, 2019-03-04 22:11:48))

I followed the Laravel 5.1 Documents: Many To Many Relationships - syncing for convenience that says:

Syncing For Convenience

You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the array will exist in the intermediate table:

$user->roles()->sync([1, 2, 3]);

You may also pass additional intermediate table values with the IDs:

$user->roles()->sync([1 => ['expires' => true], 2, 3]);



via Chebli Mohamed

What is the best way to secure Laravel/MySQL-API server from hackers?

Everyone we are working in a application. Where backed is laravel 5.1 and database is mysql. Both are under csf firewall and protected from the public. Below is the technology stack :-

Technology :

1) Laravel 5.1 backend Hosting : AWS/ EC2

2) Databse mysql 5.5 Hosting : RDS

3) Fronend Wordpress around 40 sites consuming api from backend.

Currently implemented Security :-

1) CSF firewall on backend.

2) Ip restrictions on RDS.

is there anything else we can do make it secure. Becuase we are saving customer personal and identification details.

Any suggestion will be appreciated.



via Chebli Mohamed