Thursday, May 14, 2020

Laravel faker

/** @var \Illuminate\Database\Eloquent\Factory $factory */ $factory->define(App\Post::class, function (Faker\Generator $faker) { return [ 'title' => $faker->sentence, 'author_id' => function () { return factory(App\Author::class)->create()->id; }, 'body' => $faker->paragraphs(rand(3,10), true), ]; }); /** @var \Illuminate\Database\Eloquent\Factory $factory */ $factory->define(App\Author::class, function (Faker\Generator $faker) { return [ 'name' => $faker->name, 'bio' => $faker->paragraph, ]; }); $factory->define(App\Profile::class, function (Faker\Generator $faker) { return [ 'birthday' => $faker->dateTimeBetween('-100 years', '-18 years'), 'author_id' => function () { return factory(App\Author::class)->create()->id; }, 'city' => $faker->city, 'state' => $faker->state, 'website' => $faker->domainName, ]; });



public function run() { $authors = factory(App\Author::class, 5)->create(); $authors->each(function ($author) { $author ->profile() ->save(factory(App\Profile::class)->make()); $author ->posts() ->saveMany( factory(App\Post::class, rand(20,30))->make() ); }); }

// logging in appserviceprovider

DB::listen(function($query) { Log::info( $query->sql, $query->bindings, $query->time ); });

https://laravel-news.com/eloquent-eager-loading

Thursday, May 7, 2020

delete image from storage laravel

//Process one for single file delete
Storage::delete($request->old_picture);

//process two for single file delete
File::delete('images/post/'.$post->image);

// process three for multiple delete            
$files = array($file1, $file2);
File::delete($files);

Thursday, April 23, 2020

linux server environment setup step by step process

sudo apt update

sudo apt install curl wget php-cli php-zip php-mbstring git unzip php-xml php7.2-gd

sudo service apache2 restart


php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

HASH="$(wget -q -O - https://composer.github.io/installer.sig)"




php -r "if (hash_file('SHA384', 'composer-setup.php') === '$HASH')
{ echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer



sudo a2enmod rewrite

sudo chown -R www-data:www-data /var/www/html/sitedomain

sudo nano /etc/apache2/sites-available/000-default.conf


//for centos7
sudo chmod -R gu+w storage/
sudo chmod -R guo+w storage/ sudo chmod -R gu+w bootstrap/cache/ sudo chmod -R guo+w bootstrap/cache/

//for centos7

then

DocumentRoot /var/www/html/sitedomain/public
ServerName sitedomain.com
CustomLog /var/log/apache2/sitedomain.com-access.log combined
ErrorLog /var/log/apache2/sitedomain.com-error.log

Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted

sudo service apache2 restart

https://docs.beyondco.de/laravel-websockets/1.0/basic-usage/starting.html#using-a-different-port

MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=apikey
MAIL_PASSWORD=password
MAIL_ENCRYPTION=null

truncate -s0 error.log //for truncate any file

vim /etc/mysql/mysql.conf.d/mysqld.cnf
systemctl restart mysql.service


[program:websockets]
command=/usr/bin/php /var/www/html/sitedomain/artisan websockets:serve --port=3030
numprocs=1
autostart=true
autorestart=true
user=root
stdout_logfile=/var/www/html/sitedomain/websockets.log



[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/html/sitedomain/artisan queue:work --sleep=3 --tries=3
autostart=true
autorestart=true
user=root
numprocs=8
redirect_stderr=true
stdout_logfile=/var/www/html/sitedomain/worker.log
stopwaitsecs=3600


https://stillat.com/blog/2016/12/07/laravel-task-scheduling-running-the-task-scheduler


[program:laravel_corn]
command=* * * * * php /var/www/html/sitedomain/artisan schedule:run >> /dev/null 2>&1
process_name=%(program_name)s_%(process_num)02d
numprocs=1
autostart=true
autorestart=true
startsecs=0
user=www-data
redirect_stderr=true
stderr_logfile = /var/www/html/sitedomain/laravel_corn_err.log
stdout_logfile = /var/www/html/sitedomain/laravel_corn_stdout.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=10


In SqsConnector.php line 26:

Class 'Aws\Sqs\SqsClient' not found


nano /etc/php/7.2/apache2/php.ini

max_execution_time = 120
max_input_vars = 2500
memory_limit = 128M
post_max_size = 32M
upload_max_filesize = 24M
max_file_uploads = 100

sudo service apache2 restart

ab -k -n 500 -c 50 http://sitedomain.com/ //apache branch mark testing for 500 request and 50 concurent user


Friday, March 20, 2020

Laravel ajax from submit by serializeArray

AJAX ` $(".submit").click(function(e) {
    e.preventDefault();

var formSelector = $(this).data("form");
    var form = $("#" + formSelector);
    var url = form.attr('action');
    var product = form.serializeArray();

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': csrf
        }
    });
 
    $.ajax({
        type: "POST",
        url: url,
        data: product,
        success: function(returndata){
            //debugger;
            location.reload();
        }
    });`
routes.php Route::group(['prefix' => 'admin'], function(){ Route::post('categories/add', BackendPagesController@addCategory'); });
BackendPagesController.php ` public function addCategory(Request $request){
    $name = $request->input('category-name');
    $categoryUrl = $request->input('category-url');
    $parentCategory = $request->input('kategorie');
    $categoryImageUrl = $request->input('category-image-url');

    if($parentCategory == "keine"){
        $parentCategory = 0;
    }

    $position = Categories::max('order_by');

    $category = new Categories;

    $category->name = $name;
    $category->url_alias = $categoryUrl;
    $category->parent_id = $parentCategory;
    $category->image_url = $categoryImageUrl;
    $category->meta_title = $request['meta-category-title'] ?? '';
    $category->meta_description = $request['meta-category-description'] ?? '';
    $category->order_by = $parentCategory;

    $category->save();

    if($category->id){                
        return $category->id;                   
    }else{                    
        return "wurde nicht eingetragen";
    }
        
}



Thursday, March 19, 2020

Laravel cron job

Running a cron job 3 times (1 pm, 2 pm and 3 pm) in Laravel


Open cronjob config with vim & add script bellow

m h dom mon dow command

  • 13,14,15 * * * php /var/www/project/artisan schedule:run >> /dev/null 2>&1

File upload using Laravel and Vue.js (The Right Way)

Ways to upload a file

Most articles showing how to upload a file using JavaScript actually teach how to encode the file contents in Base64 so it can be included in the JSON request. It works, but it's not as efficient as other methods. In this post I'll show how to upload a file using the multipart/FormData method using Vue.js together with axios.

Base64 inside JSON

Advantages:
  • No need to manually encode/decode your data in JSON (if using any frontend framework or client library)
  • File's content is just another field in the JSON object
Disadvantages:
  • Need to encode the file in Base64
  • Uses more CPU, more memory, and more network bandwidth (Base64 uses 33% more space than binary)
  • Little support from backend frameworks

Multipart

Advantages:
  • No need to encode the file in Base64
  • Uses less CPU, less memory, and less network bandwidth
  • Full support from backend frameworks
Disadvantages:
  • Need to manually encode/decode your data in JSON
  • File's content is separate from the JSON object

Getting the file

In one way or another, your page will have a file input element that lets the user choose a file. Vue will complain if you try to use v-model on it because file inputs are readonly, so we usually add an event handler for the change event.

     type="file" @change="selectFile">

Sending the file

File input elements have a files property that is an array of instances of the File class. It has some metadata about the selected file and methods to read its contents. Besides that, it can be used directly as a value in a FormData object. The FormData class allows one to use JavaScript to build the same request that a plain HTML form would create. You can use a FormData object as the request's body when using axios, jQuery or even plain XMLHttpRequest objects.
The following:
const data = new FormData();
data.append('photo', this.photo);
data.append('description', this.description);
data.append('productId', this.productId);
axios.post("/api/photo", data);
Is roughly the same as:
method="POST" enctype="multipart/form-data" action="/api/photo"> type="file" name="photo"/> type="text" name="description"/> type="text" name="productId">
If you have complex data as arrays or nested objects, you will have to convert them to JSON manually:
const data = new FormData();
data.append('photo', this.photo);
const json = JSON.stringify({
    description: this.description,
    productId: this.productId,
});
data.append('data', json);
axios.post("/api/photo", data);

Receiving the file

At the Laravel side, there is full support to handle file uploads transparently using the Request class. Uploaded files are fields like any other, presented by the framework as instances of the Illuminate\Http\UploadedFile class. From there on you can read the file's contents or store it somewhere else.
public function savePhoto(Request $request)
{
    // Validate (size is in KB)
    $request->validate([
        'photo' => 'required|file|image|size:1024|dimensions:max_width=500,max_height=500',
    ]);

    // Read file contents...
    $contents = file_get_contents($request->photo->path());

    // ...or just move it somewhere else (eg: local `storage` directory or S3)
    $newPath = $request->photo->store('photos', 's3');
}
If you had complex data that you manually converted to JSON, you need to decode it before use:
public function savePhoto(Request $request)
{
    $request['data'] = json_decode($request['data']);

    // Validate
    $request->validate([
        'data.description' => 'required|filled|size:100',
        'data.productId' => 'required|int|exists:App\Product,id'
    ]);

    // ...the rest is the same...
}

Link : https://dev.to/diogoko/file-upload-using-laravel-and-vue-js-the-right-way-1775