dimanche 30 juin 2019

Adding two created_at on one insert

I want to add another created_at column on the database columns for reference.

I want to have a created_at and created_at1 at the same time.

This is what I have in my Model:

const CREATED_AT = 'created_at1';

protected $dates = [created_at, created_at1];

But I'm receiving this error: Field 'created_at' doesn't have a default value.



via Chebli Mohamed

Laravel 5.6 eloquent get all item from relationship

let see my Model :

public function childs() {
        return $this->hasMany('App\Models\BusinessModel','parent_id','id') ;
    }

    public function parent() {
        return $this->hasOne('App\Models\BusinessModel','id','parent_id') ;
    }

    public function users() {
        return $this->hasManyThrough('App\Models\User','App\Models\BusinessModelUser','business_model_id','id') ;
    }

    public function get_team() {
        return $this->parent->childs;
    }

I want to get all users for team ( get by get_team() function ). Is there any way that can help me get all user in a team without use:

foreach ($abc->get_team as $item ){
   $item->users;
}
...

Sorry, my english so bad. Hope you understand. Please help me. thank you .



via Chebli Mohamed

local.ERROR: Unable to init from given url - Intervention Image, Laravel 5.8, but only in queued job

I have queued job, which saves images from given URLs (get them from remote and save in local) and everything works, but, if I put this code inside queued job, I am getting an error in storage/logs/.log:

local.ERROR: Unable to init from given url (url which exists and I can access via browser )...

I can access these URLs, allow_url_fopen is enabled and this code works WITHOUT queued job. This is part of the code:

try{

   $img = Image::make($photo->url);

   // SAVE BIG IMAGE
   $img->save($path . $filenameBig);


}catch (Intervention\Image\Exception\NotReadableException $e){
    var_dump($e->getMessage());
}

This $photo->url is http and I can see it in the error (it is not empty or something). I can access with a browser to the actual image.



via Chebli Mohamed

Queued job doesn't execute the actual code - Laravel 5.8

I have a queued job, which must runs a code for importing data, like images. I have followed the docs about Laravel 5.8 for creating a job. First crete tables:

php artisan queue:table
php artisan migrate

Then create a job:

php artisan make:job CarsJob

CarsJob:

public function handle() {
    $cars = new CarsLibrary();
    $CarsLibrary->importAll();
}

Dispatching a job in the controller:

$importCarsJob = (new ImportCarsJob())->onQueue('import_cars');
$this->dispatch($importCarsJob );

OR:

$importCarsJob = new importCarsJob();
$this->dispatch($importCarsJob);

This is my env file for Redis:

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=redis
SESSION_DRIVER=file
SESSION_LIFETIME=120
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=43216

This is config/queue.php:

'default' => env('QUEUE_CONNECTION', 'redis'),
'connections' => [

    'sync' => [
        'driver' => 'redis',
    ],
... other drivers like beanstalkd

    'database' => [
        'driver' => 'database',
        'table' => 'jobs',
        'queue' => 'default',
        'retry_after' => 90,
    ],


    'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
        'queue' => env('REDIS_QUEUE', 'default'),
    ],

],

, but when I access the URL for the action with queued job, nothing happen, nothing is imported and there is almost no delay for the response (without queued job, it takes more than a minute ).



via Chebli Mohamed

How to save multiple images in database Laravel?

I'm trying to save multiple images of products in database. I created the images table and set up the relationship with products table.

Here is how my store function in controller looks like

public function store(Request $request) 
{ 
    $formInput=$request->all();
    $image=array();
    if($files=$request->file('image')){
        foreach($files as $file){
            $name=$file->getClientOriginalName();
            $file->move('images',$name);
            $image[]=$name;

        }
    }

    //dd($formInput);

    Product::create(array_merge($formInput,
   [
   // 'product_id'=>$product->id, 
     'image' => what to put here 
     'seller_id'=> Auth::user()->id,
    ])); 
    return redirect()->back(); 

here is image model

class Image extends Model
{
//

protected $table='images';
protected $fillable=['product_id','image'];

public function product()
{
  return $this->belongsTo('App\Product','product_id');
 }
}

here is product model

class product extends Model
{
  protected $table='products';
  protected $primaryKey='id';
  protected $fillable= ['seller_id','pro_name','pro_price','pro_info','stock','category_id'];

  public function images()
  {
   return $this->hasMany('App\Image', 'product_id');
  }

}

When i dd($formInput); i'm seeing all the details including images but how do i submit them to the database? (images to images table and products details to products table)



via Chebli Mohamed

Laravel - 5.8 - background job is not in the background

I am trying to use Laravel background jobs. I have a library, which imports lots of images.

For queued jobs, I am following Laravel documentation:

First (create table):

php artisan queue:table

php artisan migrate

Then configuration in .env file for Redis:

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=43216

Create a job:

php artisan make:job CarsJob

CarsJob:

public function handle(){
    $cars = new CarsLibrary();
    $CarsLibrary->importAll();
}

Dispatching a job in a some action in the controller:

First what I have tried:

    $importCarsJob = (new ImportCarsJob())->onQueue('import_cars');
    $this->dispatch($importCarsJob );

Second what I have tried:

    $importCarsJob = new importCarsJob ();
    $this->dispatch($importCarsJob );

I have enabled Redis in my hosting. It is shared hosting.

If I access the URL, I see that this job is not in the background, because it needs more than a minute to finish the request.



via Chebli Mohamed

Docker - Nginx - Laravel: unable to load image, js, css 404

So, I've been working on this for quite a while, I'm not sure where is the problem lies (docker, Nginx or laravel) - so I have laravel file structure like this:

enter image description here

I dont have issue accessing *.php files (e.g. http://localhost:8888/css/phpinfo.php --> this work fine)

but other than that, I can't access my css file (app.css), my js (app.js), and even my images (in images folder) --> it return me 404

so i did a quick check in docker, i go inside docker: docker exec -t -i container_name /bin/bash goto to the respective folder and list it, all looks good (the files are there):

enter image description here

so why i received 404, and my site, just show a plain html (processed from PHP) without any js, css and image.

here is my nginx vhost.conf:

server {
    listen 80;
    index index.php index.html;
    root /var/www/public;

    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;

    location / {
        try_files $uri /index.php?$args;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

here is my docker compose file:

version: '3.7'

services:
  # The Web Server
  web:
    container_name: emm_web
    build:
      context: ./
      dockerfile: web.dockerfile
    volumes:
      - ../log/:/var/log
    ports:
      - 8888:80

  # The Database
  database:
    container_name: emm_dat
    image: mysql:5.7
    volumes:
      - dbdata:/var/lib/mysql
    environment:
      - "MYSQL_HOST=localhost"
      - "MYSQL_PORT=33061"
      - "MYSQL_DATABASE=bdb"
      - "MYSQL_USER=busr"
      - "MYSQL_PASSWORD=pass"
      - "MYSQL_ROOT_PASSWORD=word"
    ports:
      - "33061:3306"

  # The PHP Application
  app:
    container_name: emm_app
    build:
      context: ./
      dockerfile: app.dockerfile
    volumes:
      - ../www/:/var/www
    depends_on:
      - web
      - database
    environment:
      - "DB_PORT=3306"
      - "DB_HOST=database"

volumes:
  dbdata:

what's went wrong here?

here is the access log that show 404:

172.18.0.1 - - [30/Jun/2019:15:34:01 +0000] "GET /images/logo.png HTTP/1.1" 404 37828 "http://localhost:8888/register" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.170"
172.18.0.1 - - [30/Jun/2019:15:34:01 +0000] "GET /css/app.css HTTP/1.1" 404 37764 "http://localhost:8888/register" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.170"
172.18.0.1 - - [30/Jun/2019:15:34:03 +0000] "GET /images/bg.jpg HTTP/1.1" 404 37803 "http://localhost:8888/register" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.170"
172.18.0.1 - - [30/Jun/2019:15:36:42 +0000] "GET / HTTP/1.1" 200 40898 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.170"
172.18.0.1 - - [30/Jun/2019:15:37:40 +0000] "GET / HTTP/1.1" 200 41275 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.170"
172.18.0.1 - - [30/Jun/2019:15:38:54 +0000] "GET /css/info.php HTTP/1.1" 404 27 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.170"
172.18.0.1 - - [30/Jun/2019:15:39:09 +0000] "GET /css/phpinfo.php HTTP/1.1" 200 92428 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.170"
172.18.0.1 - - [30/Jun/2019:15:39:19 +0000] "GET /css/app.css HTTP/1.1" 404 37830 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.170"



via Chebli Mohamed

Getting the sum of columns in a Laravel raw select statement

I am trying to get the sum of the records that are returned in a Laravel select statement but I can't seem to get it right.

My original statement is as follows;

$results = DB::table('polls')->select('polls.id as poll_id', 'poll_votes.vote_count as vote_count', 'poll_options.id as poll_option_id')
    ->join('poll_options','polls.id','=','poll_options.poll_id')
    ->join('poll_votes', 'poll_options.id', '=', 'poll_votes.poll_option_id')
    ->where([['polls.status','=','1'], ['poll_options.status','=','1'],])
    ->get();

I have tried adding the following after the last element on the ->select line but i keep getting errors;

DB::raw('sum(poll_votes.vote_count) total_votes')

Any help would be greatly appreciated



via Chebli Mohamed

How to get product Id from hidden field Laravel

I'm trying to get the Id of a product when I submit the form using the hidden input field but am getting an error Trying to get property of non-object . How can I fix this issue?

code

Controller

 Image::create(array_merge($formInput,
   [

    $id=$request->input('id'),
    $product=Product::find($id),
     'product_id' =>$product->id,

    ])); 

blade

  <input type="hidden" name="id" value="" />

Any help will be appriciated.



via Chebli Mohamed

How to check the data already exists or not laravel

I have 2 tables. Patient table and reservation table.

Patient table:

  • ID
  • name
  • medical record number (norekmed)

Table of reservations

  • ID
  • idpatient
  • idroom

How do I check patient data already or not if I make a reservation?

Checking is by comparing between a reservation form field with norekmed in the patient table.

If patient data already exists, we can make a reservation. And if there is no patient data, we cannot make a reservation.

If it turns out this is not good, and there is a better method, I accept that.

Reservation controller (store)

$this->validate($request,
            [
                'idpatient' => 'required|unique:reservation,idpatient',
                'idroom' => 'required',
            ]);

        Patient::where(function($query) { 
            $query->has('id')
            ->orHas('norekmed');
        })->find(1);

        $reservasi = new Reservasi();
        $reservasi->idpatient = $request->idpatient;
        $reservasi->idroom = $request->idroom;
        $reservasi->save();



via Chebli Mohamed

How to get product Id from database in laravel

I'm trying to get the product Id from the database by using the hidden input but am stuck, I'm getting the error General error: 1366 Incorrect integer value: '[{"id":1}]' for column 'product_id'. How do I get the product Id from the database?

Code

Blade

   <input type="hidden" name="id" value="" />

Controller

     Image::create(array_merge($formInput,
   [
    $id=$request->input('id'),
    $product_id=Product::get('id'),
    'product_id' =>$product_id,

    ])); 

Any help will be appriciated.



via Chebli Mohamed

Select specific column value from multiple relational table using where condition in Laravel ORM

I have two tables named contacts and clients. Both tables have group_id as foreign_key. Now, I want to get phonecolumn value from both tables when user $request->groupid will found a group from groupstable. I am trying something like this. But getting empty array. Would someone help me please!

$getPhoneNumbers = Group::with(['hasContacts' => function($query){
                             $query->select('phone')->where('is_active', 1);
                        }])->with(['clients' => function($q){
                             $q->select('phone')->where('status', 1);
                        }])->where('id', $request->groupid)->get();

In Group model -

public function clients()
{
    return $this->hasMany('App\Client', 'group_id', 'id');
}

public function hasContacts()
{
    return $this->hasMany('App\Contact', 'group_id', 'id');
}



via Chebli Mohamed

how to find available dates with laravel query?

I have multiple halls. I have to search halls for booking with given dates and time (morning or evening). If these dates and time(morning or evening) are available in any hall it will return all those halls which are available for booking.It will check all booking and return all those halls which are available on these dates and time. At the time of booking user can book 3 days like 25 to 28 .. In these dates 26 and 27 are not available dates. I hope you understand my scenario. I have other table "events" where all halls are added. I have to return all halls which are available on these dates. You can see in image i have posted... if i want to book dates from 20-02-2019 to 25-02-2019.. then it will return me event_id 2 details because it is available on these dates. I have issue with my query.

Booking table

public function getAvailableEvents(Request $request)
{
    try {
        $allInputs = Input::all();
        $categoryID = $request->input('category_id');
        $startDate = $request->input('start_date');
        $endDate = $request->input('end_date');
        $time = $request->input('time');

        $validation = Validator::make($allInputs, [
            'category_id' => 'required',
            'start_date' => 'required',
            'end_date' => 'required',
            'time' => 'required',
        ]);
        if ($validation->fails()) {
            DB::rollback();
            return $response = (new apiresponse())->customResponse('Fields required!',
                422,
                $validation->errors()->toArray());
        } else {

            $getEvents = Booking::where('category_id', '=', $categoryID)
                ->where(function ($q) use ($endDate,$startDate,$time) {
                    $q->where('date_to','!=',$endDate)
                        ->orWhere('date_from','!=',$startDate)
                        ->orWhere('booking_time','!=',$time);
                })->get();


            if (count($getEvents) > 0) {

                for ($i = 0; $i < count($getEvents); $i++) {
                    $data[] = array(

                        "booking_id" => $getEvents[$i]->id,
                        "ref_no" => $getEvents[$i]->ref_no,
                        "category_id" => $getEvents[$i]->category_id,
                        **"event_id" => $getEvents[$i]->event_id,**
                        "user_id" => $getEvents[$i]->user_id,
                        "phone" => $getEvents[$i]->phone,
                        "booking_status" => $getEvents[$i]->booking_status,
                        "type" => $getEvents[$i]->type,
                        "date_from" => $getEvents[$i]->date_from,
                        "date_to" => $getEvents[$i]->date_to,
                        "booking_time" => $getEvents[$i]->booking_time,
                        "price" => $getEvents[$i]->price,
                        "rating" => $getEvents[$i]->rating,
                        "date_time" => $getEvents[$i]->date_time ?? "",

                    );
                }
                return $response = (new apiresponse())->customResponse('Events found!',
                    200,
                    $data);

            } else {
                DB::rollback();
                return $response = (new apiresponse())->customResponse(
                    'These dates are not available!',
                    422,
                    (object)[]);
            }
        }

    } catch (\Illuminate\Database\QueryException $ex) {
        return $response = (new apiresponse())->customResponse(
            'Fail!',
            422,
            $ex);
    }
}



via Chebli Mohamed

How to update multiple row at a time in laravel?

I want to update multiple rows at a time. I reform array as follows:

Array
(
    [0] => Array
        (
            [id] => 13
            [up] => 1
            [down] => 2
            [status] => 1
        )

    [1] => Array
        (
            [id] => 14
            [up] => 1
            [down] => 3
            [status] => 1
        )

    [2] => Array
        (
            [id] => 15
            [up] => 1
            [down] => 4
            [status] => 1
        )

)

This array is assigned to $update variable. And trying to update as follows:

      $hierarchyInstance = new Hierarchy;
      Batch::update($hierarchyInstance, $update, 'id');

But I am getting fatal error. Whats wrong in my approach?

I am using laravel 5.7. Thanks in advance.



via Chebli Mohamed

Creating a default object from empty value while updating user profile record

I want to update user profile record, but while submitting, an error popped up with a message "Creating default object from empty value", when i remove if statements,and type only var_dump($data),,, it is running smoothly, and show all data, but in the presence of if commands, error popped up. i don't know, why it's happening, any help please,

class home extends Model {

protected $table="homes";
public static function upstore($data){
$firstname=Input::get('fname');
$lastname=Input::get('lname');
$phone=Input::get('phone');
$address=Input::get('address');
$profileimage=Input::get('pimage');
$password=Input::get('pswrd');
$confirmpassword=Input::get('cpswrd');

  if( $firstname != '' ){
    $homes->fname    = $firstname;
  }
 if( $lastname != '' ){
    $homes->lname    = $lastname;
  }
 if( $phone != '' ){
    $homes->phone    = $phone;
  }
 if( $address != '' ){
    $homes->address    = $address;
  }
 if( $profileimage != '' ){
    $homes->pimage    = $profileimage;
  }
 if( $password != '' ){
    $homes->pswrd    = $password;
  }
 if( $confirmpassword != '' ){
    $homes->cpswrd    = $confirmpassword;
  }

     $homes->save();
 }

}

It shows this error "Creating a default object from empty value"



via Chebli Mohamed

check file exists not work in laravel on the online host

I need to check if a file exists in my host ,but value returns method file_exists() always false in host . this code work in localhost (and returns true)🤔



via Chebli Mohamed

samedi 29 juin 2019

Using with() function of laravel model i want take array object of other which is not null

Here is my code in controller and the output but i want that order which is not null.

$ordered_products = Product::with('order')->get();

Output:

[ { "id":1, "breed_id":1, "weight":"70", "price":"49000", "quantity":1, "no_of_sold_out_items":0, "image":"sojat11561700682.jpg", "description":"Sojat is a breed of Bakra. This bakra can be used for Bakri Eid, Eid, Sadqa, Aqeeqa etc.", "status":1, "created_at":"2019-06-28 05:44:43", "updated_at":"2019-06-28 05:44:43", "deleted_at":null, "order":null }, { "id":2, "breed_id":1, "weight":"70", "price":"49000", "quantity":1, "no_of_sold_out_items":0, "image":"sojat21561700788.jpg", "description":"Sojat is a breed of Bakra. This bakra can be used for Bakri Eid, Eid, Sadqa, Aqeeqa etc.", "status":1, "created_at":"2019-06-28 05:46:28", "updated_at":"2019-06-28 05:46:28", "deleted_at":null, "order":null }, { "id":3, "breed_id":1, "weight":"70", "price":"49000", "quantity":1, "no_of_sold_out_items":0, "image":"sojat31561700834.jpg", "description":"Sojat is a breed of Bakra. This bakra can be used for Bakri Eid, Eid, Sadqa, Aqeeqa etc.", "status":1, "created_at":"2019-06-28 05:47:14", "updated_at":"2019-06-28 05:47:14", "deleted_at":null, "order":null }, { "id":4, "breed_id":2, "weight":"35", "price":"17000", "quantity":1, "no_of_sold_out_items":0, "image":"sirohi11561701212.jpg", "description":"Rirohi Desi is type of breed of bakra. This Bakra can be used for Eid, Bakri Eid, Sadqa, Aqeeqa etc.", "status":1, "created_at":"2019-06-28 05:53:32", "updated_at":"2019-06-28 05:53:32", "deleted_at":null, "order":null }, { "id":5, "breed_id":3, "weight":"50", "price":"25000", "quantity":0, "no_of_sold_out_items":1, "image":"barbara11561701251.jpg", "description":"Barbara is type of breed of bakra. This Bakra can be used for Eid, Bakri Eid, Sadqa, Aqeeqa etc.", "status":1, "created_at":"2019-06-28 05:54:11", "updated_at":"2019-06-28 10:56:47", "deleted_at":null, "order":{ "id":2, "product_id":5, "user_id":2, "quantity":1, "status":"processed", "created_at":"2019-06-28 10:56:47", "updated_at":"2019-06-28 10:56:47", "deleted_at":null } }, { "id":6, "breed_id":4, "weight":"32", "price":"15200", "quantity":1, "no_of_sold_out_items":0, "image":"desi11561701294.jpg", "description":"Desi is type of breed of bakra. This Bakra can be used for Eid, Bakri Eid, Sadqa, Aqeeqa etc.", "status":1, "created_at":"2019-06-28 05:54:54", "updated_at":"2019-06-28 05:54:54", "deleted_at":null, "order":null }, { "id":7, "breed_id":5, "weight":"100", "price":"70000", "quantity":0, "no_of_sold_out_items":1, "image":"tota pari alwar11561701353.jpg", "description":"Tota - Pari Alwar is type of breed of bakra. This Bakra can be used for Eid, Bakri Eid, Sadqa, Aqeeqa etc.", "status":1, "created_at":"2019-06-28 05:55:53", "updated_at":"2019-06-28 07:29:34", "deleted_at":null, "order":{ "id":1, "product_id":7, "user_id":2, "quantity":1, "status":"processed", "created_at":"2019-06-28 07:29:33", "updated_at":"2019-06-28 07:29:33", "deleted_at":null } } ]



via Chebli Mohamed

Why laravel returns class not exist error? However everything seems fine

I created service in the App/Services folder and then I am using it controller.

So in the services folder I have following file

namespace App\Services;
use GuzzleHttp\Client;
class SubscriptionService
{
    private $subUsername    = 'M****************b';
    private $subPassword    = 'V********g';
    private $subSource      = 'o*********k';
    private $subMinisite    = 'a*******m';

    public function pinVerify($request){
        $DataArray = [];
        $client     = new Client();
        $route = 'http://b*******e.com/****/P***y.php';
        $params = [
            'form_params' => [
                'Username'      => $this->subUsername,
                'Password'      => $this->subPassword,
                'userID'        => $request->user_id,​
                'pincode'       => $request->pin_code
            ]
        ];      
        $result = $client->request(​'POST'​, $route, $params);       
        $body = $result->getBody();       
        $bodyContent = $body->getContents();
        if($bodyContent === 1){
            $DataArray['message']   = 'Failed because of system error';
            $DataArray['status']    = 'failed';  
        }else{
            $DataArray['message']   = 'Sorry provided pincode is wrong.';
            $DataArray['status']    = 'failed';  
        } 
        return $DataArray;
    }
}

And then in the controller in am using it in one method as like below

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\SubscriptionService as Subscription;
class XyzController extends Controller
{
    public function verifyPinCode(Subscription $Subscription, Request $request){
        $serviceResponse = $Subscription->pinVerify($request);
        return response()->json($serviceResponse, 200); 
    }
}

But in the result I am getting error Class does not exist, I am not sure where I am doing mistake. Can someone kindly guide me how to fix the issue, would appreciate it.

Thank you

Error

ReflectionException
Class App\Services\SubscriptionService does not exist
Previous exceptions
syntax error, unexpected ''pincode'' (T_CONSTANT_ENCAPSED_STRING)



via Chebli Mohamed

How to download spatie/browsershot generated file into User/Downloads?

In laravel 5.8 app I use https://github.com/spatie/browsershot

and if I save file as

$save_to_file= 'file.pdf';
Browsershot::html(htmlspecialchars_decode($pdf_content))
               ->showBackground()
               ->save($save_to_file);

it is downloaded and saved in /public dir of my app at my local OS

If I try to set path to ‘Downloads’ directory of my Kubuntu 18 as

$save_to_file= '/home/currentuser/Downloads/file.pdf';
Browsershot::html(htmlspecialchars_decode($pdf_content))
               ->showBackground()
               ->save($save_to_file);

I got error:

Symfony \ Component \ Process \ Exception \ ProcessFailedException
The command "PATH=$PATH:/usr/local/bin NODE_PATH=`npm root -g` node '/mnt/_work_sdb8/wwwroot/lar/votes/vendor/spatie/browsershot/src/../bin/browser.js' '{"url":"file:\/\/\/tmp\/0906513001561868598\/index.html","action":"pdf","options":{"path":"\/home\/serge\/Downloads\/file.pdf","args":[],"viewport":{"width":800,"height":600},"displayHeaderFooter":false,"printBackground":true}}'" failed. Exit Code: 1(General error) Working directory: /mnt/_work_sdb8/wwwroot/lar/votes/public Output: ================ Error Output: ==============

1) If there is a way to download generated file into ‘Downloads’(OS independently) ?

2) I think that I can use php remove function but again how define ‘Downloads’(OS independently) directory ?



via Chebli Mohamed

how to join two tables in database Laravel

I'm trying to join two tables (products table and Images table), so in products table each product has multiple images(stored in a row named image) so I want to display images of each product in images table. In images table I have a foreign key named product_id references(id) on products table, The problem is it can't store images in images table,(it keeps storing images in the row(image) in products table). How do I solve this?

Codes

Product.php

public function images()
 {
   return $this->hasMany('App\Image', 'product_id');
 }

Image.php

public function product()
{
  return $this->belongsTo('App\Product','product_id');
 }

Controller

 public function store(Request $request) 
 { 

$Input=$request->all();
$image=array();
if($files=$request->file('image')){
foreach($files as $file){
    $name=$file->getClientOriginalName();
    $file->move('images',$name);
    $image[]=$name;
  }
  } 
 product::create(array_merge($Input,
 [
 'image' => json_encode($image),

 ])); 
return redirect()->back(); 

}

Any help will be appriciated.



via Chebli Mohamed

Undefined property: stdClass::$images

In products table I have image row which stores images of every product and looks like this in database ["4.jpg","5.jpg"] in each product. Now I want to display the product and the images which belongs to that product in the view but am stuck it shows an error Undefined property: stdClass::$images how can I fix this ?

Here are the codes

blade view

   @foreach($products as $product)
   @foreach($product->images as $image)
      <img src="" alt="">
     @endforeach
     @endforeach

Controller

public function store(Request $request) 
{ 

$Input=$request->all();
$image=array();
if($files=$request->file('image')){
    foreach($files as $file){
        $name=$file->getClientOriginalName();
        $file->move('images',$name);
        $image[]=$name;

    }

} 
 product::create(array_merge($Input,
 [
'image' => json_encode($image),

])); 
return redirect()->back(); 

}

Any help will be appriciated.



via Chebli Mohamed

Eloquent where clause based on other tables

One of my Laravel models is called Property, which contains all the Real Estate properties within my application. Each Property contains a city and country.

Therefor I have the following relational tables:

City_property (holds city of properties)

| id | city_id | property_id |
|----|---------|-------------|
| x  | 2       | 1           |

City_country (holds country of city)

| id | country_id | city_id |
|----|------------|---------|
| x  | 3          | 2       |

So when fetching all my Properties, I want to where clause on the Country of the properties, so I'm able to only fetch Properties where country = 5 (for example).



via Chebli Mohamed

Selection of unique records by one field

I need to select only entries with a unique values 'who_id'

    $history_today = DB::table('view_history')
            ->select('girl_id', 'who_id', 'girls.name as name', 'girls.main_image', 'view_history.time', 'girls.age',
                'cities.name as city_name', 'girls.city_id')
            ->where('girl_id', $girl->id)
            ->where('who_id', '!=', null)
            ->where('who_id', '!=', $girl->id)
            ->leftJoin('girls', 'girls.id', '=', 'view_history.who_id')
            ->leftJoin('cities', 'girls.city_id', '=', 'cities.id_city')
            ->orderBy('time', 'DESC')
            ->distinct('who_id')
            ->paginate(15);

But in this case, I get all the records.



via Chebli Mohamed

Excel Export using laravel with vuejs

I am Doting Excel export using Laravel with Vuejs, somehow the Code is returning true value but can not Download Excel file, if I do normal request it will download the file, but in axios request, it will not export the file

I am using php artisan make:export to export file

In App/Export/studentexport.php

public function collection()
{
    return Student_master::all();
}

then in controller i will do a function

public function export()
{
    return Excel::download(new StudentExport, 'users.xlsx');
}

In my Vue file i will write a code that cal call the controller and export the file

axios.get('api/export')
            .then(()=>{
                toast({
                    type: 'success',
                    title: 'Export the Data'
                })
            })
            .catch(()=> {
                toast({
                        type: 'warning',
                        title: 'Can not Export'
                        })
            })

but the result is like that enter image description here

that will return True, I really don't know how to solve this,plase help me



via Chebli Mohamed

Integration to paypal at local server

In laravel 5.8 app I make integration to paypal with paypal/rest-api-sdk-php and I make as :

                            // Set up a payment
                            payment: function(data, actions) {
                                return actions.payment.create({

                                    return_urls : {
                                        return_url : 'http://local-votes.com/paypal_payment'
                                    },

                                    transactions: [{
                                        amount: {
                                            total: '0.01',
                                            currency: 'USD'
                                        }
                                    }]
                                });
                            },
                            // Execute the payment

if return_urls is uncomment I got error in console :

VM19:1 POST https://www.sandbox.paypal.com/v1/payments/payment 400 (Bad Request)
(anonymous) @ VM19:1
(anonymous) @ http.js:147
ZalgoPromise @ promise.js:41
request @ http.js:48
(anonymous) @ rest.js:243
_loop @ promise.js:162
_proto.dispatch @ promise.js:153
_proto.then @ promise.js:242
(anonymous) @ rest.js:225
_loop @ promise.js:162
_proto.dispatch @ promise.js:153
_proto.then @ promise.js:242
(anonymous) @ rest.js:217
_loop @ promise.js:162
_proto.dispatch @ promise.js:153
_proto.resolve @ promise.js:96
_loop @ promise.js:213
_proto.dispatch @ promise.js:153
_proto.resolve @ promise.js:96
(anonymous) @ promise.js:43
(anonymous) @ http.js:117
load (async)
(anonymous) @ http.js:78
ZalgoPromise @ promise.js:41
request @ http.js:48
Object.time @ rest.js:37
(anonymous) @ util.js:54
createPayment @ rest.js:209
(anonymous) @ serialize.js:34
ZalgoPromise.try @ promise.js:401
(anonymous) @ serialize.js:33
(anonymous) @ types.js:68
ZalgoPromise.try @ promise.js:401
_RECEIVE_MESSAGE_TYPE.(anonymous function) @ types.js:56
receiveMessage @ index.js:114
messageListener @ index.js:140
serialize.js:175 Uncaught Error: Error: Request to post https://www.sandbox.paypal.com/v1/payments/payment failed with 400 error. Correlation id: 987ea0c89740a, 987ea0c89740a

{
    "name": "MALFORMED_REQUEST",
    "message": "Incoming JSON request does not map to API request",
    "information_link": "https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST",
    "debug_id": "987ea0c89740a"
}

    at XMLHttpRequest.<anonymous> (http.js:114)
    at Object._RECEIVE_MESSAGE_TYPE.(anonymous function) [as postrobot_message_response] (https://www.paypalobjects.com/api/checkout.js:4206:27)
    at receiveMessage (index.js:114)
    at messageListener (index.js:140)
    at Object._RECEIVE_MESSAGE_TYPE.(anonymous function) [as postrobot_message_response] (https://www.paypalobjects.com/api/checkout.js:4206:27)
    at receiveMessage (index.js:114)
    at messageListener (index.js:140)
    at serialize.js:175
    at serialize.js:212
    at util.js:140
    at util.js:102
    at util.js:116
    at replaceObject (util.js:138)
    at util.js:147
    at util.js:109
    at util.js:118
    at replaceObject (util.js:138)

where http://local-votes.com is my local host LAMP/Ubuntu 18

if to comment return_urls payment works ok but I do not have payment retun action. If there is a way to work with it locally. Looking at some example code, looks like that is possible...



via Chebli Mohamed

Laravel Form Request - Validation issues

I'm attempting to create a single error response message for array input:

This is my form:

    <div class="form-group  col-md-12">
        <div class="row">
            <div class="col-md-6">
                <label for="client-type">Client Type</label>
                <input type="text" name="client_type[]" class="form-control" value="Panelist" readonly>
            </div>
            <div class="col-md-6">
                <label for="commission-percentage">Commission Percentage</label>
                <input type="number" name="commission_percentage[]" class="form-control">
            </div>
        </div><br>
        <div class="row">
            <div class="col-md-6">
                <label for="client-type">Client Type</label>
                <input type="text" name="client_type[]" class="form-control" value="Non Panelist" readonly>
            </div>
            <div class="col-md-6">
                <label for="commission-percentage">Commission Percentage</label>
                <input type="number" name="commission_percentage[]" class="form-control">
            </div>
        </div>

Here's my controller:

public function store(StoreCommissionsList $request)
{
    $attributes = $request->validated();

    dd($attributes);
}

And finally my StoreCommissionsList form request:

public function rules()
{
    $commission = request('commission_percentage');

    $rules = [];

    $rules['role_id'] = 'required';
    $rules['client_type'] = 'required';

    if ( $commission[0] == null && $commission[1] == null ) 
    {
        $rules['commission_percentage'] = 'required';
    }

    return $rules;
}

public function messages()
{
    return [
        'role_id.required' => 'Please select a user role',
        'client_type.required' => 'Please input a client type',
        'commission_percentage.required' => 'Please fill in a percentage commission for each client type',
    ];
}

What is happening is: If all the fields in my form are blank, only the role_id seems to be passing the validation check in terms of returning the required validation message. The commission_percentage is not validated at all and after inputting role_id, the form submits meaning the commission_percentage validation is overlooked for some reason.

Kindly assist.



via Chebli Mohamed

php ZipArchive::close() not working on webserver

I am building a folder with files in it. At the end, I want to Zip this folder. On my local machine using homestead, everything works correctly. However, on my webserver I am getting the error

ZipArchive::close(): Can't remove file: No such file or directory

Why? The folder is filled with all files...

My Code

$zip_file = storage_path('app\\takeouts\\takeout_' . $this->dataExports->uuid . '.zip');
        $this->zip = new \ZipArchive();
        $this->zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        $this->addAllFilesToZipArchive($this->folder_name);
        $this->zip->close();

        Storage::deleteDirectory($this->folder_name);


private function addAllFilesToZipArchive($dir)
    {
        $dirs = Storage::directories($dir);
        $files = Storage::files($dir);
        foreach ($files as $file)
        {
            if(Storage::exists(storage_path("app\\" . $file))) {
                $this->zip->addFile(storage_path("app\\" . $file), str_replace($this->folder_name,"","/" . $file));
            }
        }
        foreach ($dirs as $dir2) {
            $this->addAllFilesToZipArchive($dir2);
        }
    }



via Chebli Mohamed

vendredi 28 juin 2019

Laravel : Property [name] does not exist on this collection instance

i'm trying to fetch some data from my users table, for my profile page. But when i click the profile page it give me some error :

Property [name] does not exist on this collection instance.

Where is the problem? am i do it wrong or some code missing?

User Model

protected $fillable = [
    'name', 'email', 'password', 'nim', 'phone_number', 'department'
];

protected $hidden = [
    'password', 'remember_token',
];

public function dropcv(){
    return $this->hasMany('App\Dropcv');
}

public function registration(){
    return $this->hasMany('App\Registration');
}

Controller

public function index()
{
    $users = User::all();
    return view('users.profile')->with('users',$users);
}

public function show($id)
{
    $users = User::find($id);
    return view('users.profile')->with('users',$users);
}

View

<h3></h3>

In the view section i'm just do some test to fetch simple data from the users table.

i'm so frustrated finding the solution for my problem. i've search and try so many solution in the web but nothing works.i'm kinda new to laravel and really appreciate some help.



via Chebli Mohamed

How to exclude table names while importing all existing table names

I am trying to get all table names in db, It is working fine but just want to exclude or ignore migrations, user, password_resets and any other default table names. I know it can be done by filtering array, but it's better if there is any eloquent function for this situation.

        $tables = DB::select('SHOW TABLES');



via Chebli Mohamed

Laravel deployment via Envoyer to Cpanel

I have a VPS running WHM and Cpanel. I have multiple domains hosted there. Say one of them is example.com

What I am intending to do is have two versions of the application. Production: example.com > /public_html/ Development: staging.example.com > /public_html/staging/

Right now, I am trying to deploy my application to the development environment, i.e to the staging folder.

Envoyer, with a lot of struggle with my hosting provider, is working fine. Its uploading the files as expected. The only issue now is the symbolic link current

Right now the folder structure is:

-staging
    - releases
        -release1
        -release2
    - current

My subdomain clearly points out to the staging folder, which will lead it into displaying all the contents of the folder rather than the application.

Since the application is inside the release folder, how do I make sure that my application runs when we hit the subdomain.

Do I have to modify my virtual hosts file in Apache?



via Chebli Mohamed

Using serviceprovider to conect to memcached(laravel app)

I have a laravel app which exposes a serviceprovider that creates connections to memcached servers. Would like to use the connections in my app. Currently the memcached configs are defined in config/cache.php.

Any suggestions on how to proceed.

Thanks



via Chebli Mohamed

Laravel - 5.8 one to many relation returns null

I have Cars model which belongs to two other models Region, Subregion. Cars Model:

function region(){
    return $this->belongsTo('App\Models\Region');
}
function subRegion(){
    return $this->belongsTo('App\Models\Subregion');
}

Subregion model:

class Subregion extends Model{

public $timestamps = false;

protected $fillable = [
    'name'
];

public function cars(){
    return $this->hasMany('App\Models\Car');
  }
}

Region:

class Region extends Model{

public $timestamps = false;
protected $fillable = [
    'name'
];

public function cars(){
    return $this->hasMany('App\Models\Car');
  }
}

I have query which selects Cars with their region and subregion:

$queryCar= Car::with(array(
        'region'=>function($query){
            $query->select(['id', 'name']);
        },
        'subregion'=>function($query){
            $query->select(['id', 'name']);
        }
))->orderBy('id', 'DESC');

return $queryCar->get();

Table cars has columns region_id, subregion_id.

When I try to loop the cars result:

    foreach ($cars as $p){
        var_dump($p->subregion);
        var_dump($p->region);
    break;
    }

For the region, I see the result, which is not NULL, but there is no subregion. I am sure that there is, because, if I do:

var_dump($p);

I can see and subregion_id and if I query database with that id, there is a subregion row.

It is strange, because everything is equal for these two - Subregion/Region.



via Chebli Mohamed

How to resolve "could not write block of temporary file: No space left on device" in postgresql?

I have local database in postgres. In which single table contains data of "74980435".

When I have tried to execute SELECT query it is throwing an error "could not write block 657567 of temporary file: No space left on device". I am trying to execute select query in laravel.

Anyone can help me?



via Chebli Mohamed

Laravel 5.8 SMTP Mail Sending Not Working

My Laravel 5.8 is always giving this error

Expected response code 354 but got code "554", with message "554 5.5.1 Error: no valid recipients\r\n

I have found this message content is generated

Message-ID: <40e964c6528c7ece80bcc182263806e0@127.0.0.1>
Date: Fri, 28 Jun 2019 19:37:23 +0000
Subject: Reset Password Notification
From: Test <test@test.com>
To: user@gmail.com
MIME-Version: 1.0
Content-Type: multipart/alternative;
 boundary="_=_swift_1561750643_60482b477e4f08f4c29e9e4da779fd64_=_"


--_=_swift_1561750643_60482b477e4f08f4c29e9e4da779fd64_=_
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

[Laravel](http://localhost)

# Hello!

You are receiving this email=
 because we received a password reset request for your account.

This = password reset link will expire in 60 minutes.



via Chebli Mohamed

Invalid view. Send email - Laravel - 5.8

I am trying to send an email with Laravel. I have a view in folder: views/emails/user.blade.php with simple HTML.

I have created Mailable: php artisan make:mail UserEmail. In my Controller where I am sending email:

Mail::send($request->user())
    ->queue(new PropertyAsk());

Mailable:

public function build()
{
    return $this->from('some email')
                ->view('emails.user');
}

, but when I try it says:

"message": "Invalid view.",
"exception": "InvalidArgumentException",
"file": "...vendor/laravel/framework/src/Illuminate/Mail/Mailer.php",
"line": 310,

I am sure that I have that view. I can return it with some method controller.



via Chebli Mohamed

image does not exist on this collection instance

I am trying to display multiple images from the row called image in products table from the database to the view, but am getting this error Property [image] does not exist on this collection instance., I have tried other solutions but they don't work.

Here are the codes

Controller

  public function store(Request $request) 
  { 

    $Input=$request->all();
    $image=array();
    if($files=$request->file('image')){
        foreach($files as $file){
            $name=$file->getClientOriginalName();
            $file->move('images',$name);
            $image[]=$name;

        }

    } 
   product::create(array_merge($Input,
   [
    'image' => json_encode($image),

    ])); 
    return redirect()->back(); 

    }

Blade view

     @foreach(json_decode($products->image, true) as $product)
      <img src="" alt="">
     @endforeach

Any help will be appriciated.



via Chebli Mohamed

ReactJS and Laravel 5.8 deployment on a real server

I started learning Laravel 5.8 and before I learned ReactJS. In the Laravel + ReactJS tutorials no one showed what are the steps to deploy the whole project.

In ReactJS + NodeJS I know that you have to do npm run build and the files that are created, after running this command, in the dist folder, you have to upload on the production server from your computer.

I bought some space on a php/mysql server, where I have cpanel, but in the same time I can use FileZilla to upload files.

So I pushed, using FileZilla, all the folders and files on server, but doesn’t work. If I run in the browser the project, I get all folders. This is a screenshot for what I get.

Please someone tell me what steps to follow, to deploy the React + Laravel project, from my computer on the sever?



via Chebli Mohamed

ErrorException Undefined variable After moving to laravel helper functions

I've got an old website which once was in vanilla php. I migrated to laravel putting the whole code under a 'legacy-folder' in views and I had a folder with a lot of functions in it.

Everything was running fine at this point.

In order to go one step further I moved the functions from the folder inside views into helpers. Now I get a few type of errors repeated everywhere in the codebase, I'm debugging them but they are a lot and I don't know why they are thrown now and not before.

For example errors are now thrown if:

  • undefined index of an array is accessed

    $a = $_GET['a'];

  • undefined property of object is accessed

    $a = $b->c;

  • I try to enqueue an unset variable to itself

    $a .= " example";

  • foreach on unset variable is called

  • function is passed an unset variabile

This is my routes/web.php

Route::get('{path?}', 'LegacyPagesController@show')->where('path', '.+');
Route::post('{path?}', 'LegacyPagesController@show')->where('path', '.+');

LegacyPagesController

public function show($path='index.php')
{
  ob_start();
  require(base_path('resources/views/legacy-pages/').$path);
  return ob_get_clean();
}

I've put the helpers in App\Helpers\ExampleHelper.php as classless collection of functions and in composer.json

"autoload": {
    "files": [
        "app/Helpers/ExampleHelper.php",

I'm not sure if these errors are related to the new helpers or a mistake in my routing or if anything else might be involved like php version or php.ini configuration. Any suggestion is appreciated.



via Chebli Mohamed

Laravel Virgin: Inject a Model In Controller as Dependency

In my inherited code in the Models there's some serious logic and I want to use the Laravel's Dependencuy Injection in order to load the mkodels as Dependencies into the controller instead of Using the Laravel's provided Facades.

So here's a sample Controller:

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return View
     */
    public function show($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

But Instead of using the Facade User I want to be able to load it as dependency into the controller:


namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;
user App\Models\User

class UserController extends Controller
{

     /**
     * @var User
     */
     private $user=null;

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


    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return View
     */
    public function show($id)
    {
        return view('user.profile', ['user' => $this->user->findOrFail($id)]);
    }
}


The reason why I want to do that is because I come from Symfony Background where the Dependency Injection Pattern Is heavily Erdosed. Also Dependency Injection is the Unit Test's best buddy, so I want to be able to unitilize the Dependency Injection that I am familiar with.

So I wanted to know whether I can inject the models where the logic exists in the Controllers Instead of using the Facade Pattern provided by laravel.



via Chebli Mohamed

How to display category name from different table instead of category id

I have 2 tables - one with forum category name field called "disp_name" and "ID" called "forum_cat" and onother with forum posts id, forum post content and cat_id and more called "forum"

I have model "Forum_cats"

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Forum_cats extends Model
    {

    protected $table = 'forum_cat';

    public $timestamps = false;

    }

and model "Forum"

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Forum extends Model
{   

protected $table = 'forum';

public $timestamps = false;

}

Controller :

public function index(){


    $forum = Forum::orderBy('timestamp', 'desc')->paginate(20);

//next variable is for different place
    $news = Neww::orderBy('date', 'DESC')->paginate(20);


    return view ('lapas.pamata.index',[
        'news'=>$news,
        'forum'=> $forum,
    ]);
}

Blade:

@foreach($forum as $forums)
          <li>
            <div class="media">
              <div class="media-body"> <a href="#" class="catg_title"> 
              </a> </div>
              <i class="far fa-comment-alt"></i>&nbsp; 
              Kategorija:
            </div>
          </li>
        @endforeach

so the view at the moment is like this where after "Kategorija" i have only category id

How to make after name "Kategorija" output field "disp_name" from table "forum_cat".

Someone can tell that there are lots of posts about my problem but i am trying to solve this problem all day. I know that its about hasOne, belongsTo and hasMany but i dont understand how correct us them on my code.



via Chebli Mohamed

In laravel 5 problem with checking/reading uploaded file

In laravel 5.7 app uploading file under storage

   // $dest_image = "/page-contents/-page-content-1/1.png"
    Storage::disk('local')->put($dest_image, File::get($page_content_file_path));

file is uploaded as

myapp/storage/app/page-contents/-page-content-1/1.png

Reading file I want to check if file exists and read it with all its props( size, width, height, system full path)

//$file_full_path= ‘page-contents/-page-content-1/1.png’
$file_exists    = ( !empty($image) and Storage::disk('local')->exists( $file_full_path) );

I got false, but file really exists

1) I can check as :

$file_exists    = ( !empty($image) and Storage::disk('local')->exists('public/' . $file_full_path) );

if shows true if file exists, but I am not sure if it a valid way ?

2) Reading full fiel path

 $image_full_path = storage_path( $image_path);

I got string “myapp/storage/page-contents/-page-content-1/1.png”, but it is without “/app/” as it was stored

I have all storage options default.

Which is valid way ?



via Chebli Mohamed

SQL error when loading empty laravel blade file

This is an app that previous developers have worked on and might have something hidden I'm not aware of.

There's a simple route that uses no middleware and loads a view.

public function index(Request $request)
{
    return view('media');
}

This returns

SQLSTATE[42S22]: Column not found: 1054 Unknown column

This happens even if media.blade.php is empty and stops happen if I comment out return view('media').

This is media.blade.php

@extends('layouts.app')

@section('title', __('Files and Links'))

@section('content')
    <media :privacy=""></media>
@endsection

Even when I empty the file it's the same.

Where can queries be happening if that's all there is?



via Chebli Mohamed

How to store multiple images in database and show them in the view Laravel

I'm trying to store multiple images in database and also show them in the view. I have products table and images table which are related, in the images table I have a foreign key named(image). So far it just store and show only one image instead of multiple.

Here are the codes

Controller

  public function store(Request $request) 
  { 

    $formInput=$request->all();
    $image=array();
    if($files=$request->file('image')){
        foreach($files as $file){
            $name=$file->getClientOriginalName();
            $file->move('images',$name);
            $image[]=$name;
            $formInput['image']=$name; 
        }

    }

Blade

  <input type="file" name="image[]" multiple class="form-control">

Product.php

   public function products()
 {
    return $this->belongsTo('App\Images', 'image');
  }

Images.php

   public function images()
   {
     return $this->hasMany(Product::class, 'image');
    }



via Chebli Mohamed

Laravel-Visitors Counter

this code repeats one IP hits every time when I visit this IP... if I visit repeatedly with one IP hits increment, not IP increment

how can I solve this ?? can anyone guide?

   $date = new \DateTime;

    $check_if_exists = DB::table('visitors')
    ->where('ip',$_SERVER['REMOTE_ADDR'])->first();

    $get_visit_day = DB::table('visitors')->select('created_at')
    ->where('ip', $_SERVER['REMOTE_ADDR'])->first();

   $value = date_create($get_visit_day->created_at);
    if(!$check_if_exists)
    {
        DB::table('visitors')->insert(array('ip' => 
        $_SERVER['REMOTE_ADDR'], 'hits' => '1', 'created_at' => $date));
    }else{
        DB::table('visitors')->where('ip', $_SERVER['REMOTE_ADDR'])
        ->increment('hits')->insert('updated_at', $date);
        // DB::table('visitors')->insert('updated_at', $date);
    }

    // $value = date_create($get_visit_day->created_at);
    if ($check_if_exists && date_format($value, 'd') != date('d')) {
        DB::table('visitors')->insert(array('ip' => $_SERVER['REMOTE_ADDR'], 'hits' => '1', 'created_at' => $date));
    }[enter image description here][1]



via Chebli Mohamed

'TypeError: $(...).sortable is not a function' summernote and sortable conflict?

I use summernote (https://summernote.org/) and sortable (https://jqueryui.com/sortable/) in my project in my own cms.

if I don't link the app.js from laravel I get the error: Uncaught TypeError: $(...).summernote is not a function But then my sortable functions as it should

But when I link the app.js I get the error: Uncaught TypeError: $(...).sortable is not a function

I already checked the order of loading jquery and jquery UI and that is correct.

What I found on google is that I need to add the jquery plugin sortable in app.js ? but I can't get that to work.

Layout blade

  <!-- Scripts -->
    <script src="" defer></script>
    <!-- when linked error with sortable, without error with summernote -->

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.js"></script>
    <script src="/js/jquery-3.4.1.min.js"></script>
    <script src="/js/jquery-ui.min.js"></script>
    <script src="/js/summernote.js"></script>
    @yield('script')


edit.blade


@section('script')
  <script src="/js/sortable.js"></script>
@endsection

<div class="form-group">
                            <label for="content">Content:</label>
                            <textarea name="content" class="summernote" rows="10" cols="30"></textarea>
                        </div>

  <ul class="sortable-posts list-unstyled">
                        @foreach($imgs as $img)
                        <li class="list-group-item" id="">
                            <img src="../../../" alt="" class="img-sortable">
                        </li>
                        @endforeach
                    </ul>

sortable.js

$(document).ready(function(){
  $(function() {
      $(".sortable-posts").sortable({
        placeholder: 'drop-placeholder',
          stop: function() {
              $.map($(this).find('li'), function(el) {
                  var id = el.id;
                  var sorting = $(el).index();
                  $.ajax({
                      url: '../../sortImgs',
                      type: 'GET',
                      data: {
                          id: id,
                          sorting: sorting
                      },
                  });
              });
          }
      });
  });
});

summernote.js

$(document).ready(function() {
  $('.summernote').summernote({
    toolbar: [
      // [groupName, [list of button]]
      ['style', ['bold', 'italic', 'underline', 'clear']],
      ['font', ['strikethrough', 'superscript', 'subscript']],
      ['color', ['color']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['height', ['height']],
      ['insert', ['video']],
      ['view'], ['codeview']
    ]
  });
});

Anyone an idea of what is causing the conflict between the 2? and how to solve it



via Chebli Mohamed

Laravel 5.8 schema time format hh:mm

I am beginner in Laravel. I have my project in Laravel 5.8.

This is my schema file:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->time('v_day1a')->default('00:00');
            $table->time('v_day1b')->default('00:00');
            $table->time('v_day2a')->default('00:00');
            $table->time('v_day2b')->default('00:00');
            $table->dateTime('last_activity')->nullable();
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';

In database in v_day1a, v_day1b, v_day2a, v_day2b I have this format of time: 00:00:00. I need change this to 00:00 (hh:mm).

How can I make it?



via Chebli Mohamed

Validating forms in laravel

I want to replace between:min,max min and max using variables containing row values from the table instead of hard coding row the values.


$this->validate($request, [
            'borrower_id' => 'required',
            'loan_limit' => 'required',
            'loan_amount' => 'required|numeric|between:min,max',
            'interest_rate' => 'required',
            'duration' => 'required',
            'duration_term' => 'required',
        ]);

It doesn't show the actual min and max values one should enter in the input field instead it throws an validation error on the input field.

screenshot

The loan amount must be between min and max.

I want it to display the variables containing the minimum and maximum values stored in the database.

Any help guys would be much appreciated.



via Chebli Mohamed

"Array to string conversion" in Laravel 5 [duplicate]

This question already has an answer here:

I'm trying to upload multiple images in a single row called image in database, and access them to the view page. So far when I dd, I see the images array like this

"image" => array:2 [▼ 0 => UploadedFile {#289 ▶} 1 => UploadedFile {#291 ▶} ]

But I don't see them in database(it is showing null) and in the view it gives this error "Array to string conversion". How can I make them show in database also in the view.

I tried this from How to upload multiple image in laravel but am stuck.

Here are the codes

Controller

 public function store(Request $request) 
  { 

    $formInput=$request->all();
    $image=array();
    if($files=$request->file('image')){
        foreach($files as $file){
            $name=$file->getClientOriginalName();
            $file->move('images',$name);
            $image['image']=$name;
        }
    }
    //dd($formInput);

View.blade

   <div class="form-group" ">
               <label for="image">Image</label>
               <input type="file" name="image[]" multiple   class="form-control">
               <span class="text-danger"></span>
            </div>



via Chebli Mohamed

Vue compnent doesn't show registers from api

Please help with this problem I'm trying to show registers from an api route (/api/orders) When I call them from axios, I use get petittion to /api/orders

This is my method:

 `listarOrdenesIngreso (page,buscar,criterio){
                let me=this;
                var url= '/api/orders?page=' + page + '&buscar='+ buscar + '&criterio='+ criterio;
                axios.get(url)
                    .then(function (response) {
                        var respuesta= response.data;
                        me.arrayOrders = respuesta.orders.data;
                        me.pagination = respuesta.pagination;
                        // handle success

                    })

`........

Here is the API route routes/api.php file

Route::resource('orders', 'EntryOrderController',['except' => ['create','edit']]); 

and here the code of controller (EntryOrderController.php file)

 public function index(Request $request) 
{ if (!$request->ajax()) return redirect('/');
 $entries = EntryOrder::all(); 
//return response()->json(['data' => $entries], 200); 

return $this->showAll($entries); 
} 

enter image description here

The problem It shows in image 1, where not show any register in my vue component When I call them from the URL in the browser, show me correctly the array with data. enter image description here

I hope you can help me Thanks



via Chebli Mohamed

jeudi 27 juin 2019

Have another form and want to post for category in website

I have two form, In first form I have content, info, title, pic and columns category AND in another form I have name, category column.

First form of data is showing in website under menu and sub-menu.

Now I want to show the data of another form in sub-menu with id=13, and here is table image

post table https://ibb.co/s3bLMdg another table https://ibb.co/gPZ73Zz.

my view is for 2nd form like where i am storing the value of my id 13

        <div class="form-group table-dark text-white">
                                                               <input type="hidden" id="category" name="category_id" value="13">
                                                        </div>

but, still it' not showing on website



via Chebli Mohamed

Laravel Scheduler not working in Dreamhost VPS

enter image description here

Laravel scheduler doesn't work in Dreamhost VPS.

Dreamhost has a limitation of not allowing every minute calls so I am doing it in a 10 minute call instead. However, the scheduler doesn't fire in any case.

I have tried the following cron commands:

php ~/site.com/artisan schedule:run >> /dev/null 2>&1

and

cd / site.com && php artisan schedule:run >> /dev/null 2>&1

But both do not work.

Here's what I have inside my kernel.php

protected $commands = [
    'App\Console\Commands\DailyStatus',
];

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{

    $schedule->command('status:daily')
        ->timezone('Asia/Manila')
        ->dailyAt('6:50');

    $schedule->command('status:daily')
        ->timezone('Asia/Manila')
        ->daily()
        ->between('12:00','12:30')
        ->appendOutputTo(public_path().'status_daily_output.log')
        ->withoutOverlapping(60);

    $schedule->command('status:daily')
        ->timezone('Asia/Manila')
        ->dailyAt('12:15')
        ->appendOutputTo(public_path().'status_daily_at_output.log')
        ->withoutOverlapping(60);
}

The logs are also not being generated. I have put some echo commands and its not firing.

How can I test if my scheduler is properly configured?

Can someone help me fix my current setting?

Thank you.



via Chebli Mohamed

Searching in cache data gives array first index 1

$this->getCachedCategories();
//Above code Stores the data in cache for future use. So, it goes to the database only 
//one time and next time pick the data from cache. So far everything is good.

//I have a search criteria which is in the form of array. I filter above cache data based 
//upon the search criteria and gets the data.
foreach ($userInputsForFilter as $key => $value) {
    $this->Categories = $this->Categories->where($key, $value);
}

Here is the screenshot. If you notice the data retrieved has first index from 1 instead of 0. Actually the second record came up after cache data was filtered.

enter image description here

Can you please tell why this happens when searching the cache data? This not happening when going to the database.

Array to JSON Code

$CategoryResponse = $this->iCategory->All([], []);
return \Response::json($CategoryResponse, 200);



via Chebli Mohamed

Laravel: Copy models/rows from one connection to another

I want to copy an eloquent model from one connection to another.

The way I have done this so far is as so:

$users = User::on('connection1')->where('tenant', 'foo')->get();
User::on('connection2')->insert($users->toArray());

This works most of the time. But there are cases where this does not work. For example:

  • When the model has $hidden attribute
  • When the toArray method for a model is overrided

What is a reliable way to simply copy over some rows to another connection?



via Chebli Mohamed

Laravel 5.8 Password Reset Email Not Working

The config in config/mail.php and .env are same like below-

 MAIL_DRIVER=smtp
 MAIL_HOST=smtp.gmail.com
 MAIL_PORT=587
 MAIL_USERNAME=user@gmail.com
 MAIL_PASSWORD=password
 MAIL_ENCRYPTION=tls

I am getting the following error-

500 5.5.1 Invalid command



via Chebli Mohamed

Laravel reponses giving incorrect code 200 instead of 401

I am having issues trying to get Laravel (5.8) to return a 401 HTTP status code.

Route (api.php)

route::get('test','testController@test');

Controller

public function test(){

   return response("error",401)->header('Content-Type','text/plain');

   // Also not working.
   // header("Content-Type: test/plain", 401);
   // print "error";
   // exit();
}

The result I am getting is a 200 instead the desired 401. I also test the plain PHP way with header() and terminate the execution with exit(), but no luck. Any help will be appreciated.



via Chebli Mohamed

Laravel With() relation querying - condition to main table

I need to query a nested relation using 'with' construction, but I have no idea how to use main table's fields in relation condition. Example:

Order::with([
    'products',
    'statuses' => function($statuses) {
        $statuses->where('id', LAST_STATUS_ID_FROM_ORDERS_TABLE);
    }
])->get()

Any suggestions?



via Chebli Mohamed

Using browser back button to return to previous view

Just looking for a starting point on this problem. I have a view with a weekly calendar, if I click through the calendar, say back 2 weeks, and then click on a link to a new page, I want the back button to take me back to the last week I was viewing. Currently, the back button returns me to the calendar but shows the current week. Is there a way (cookie?) to return to the last viewed week instead of the current week? Or, is using the browser's back button not a viable option?



via Chebli Mohamed

Fatal:Class Illuminate\Routing\RouteCollection contains 1 abstract method and must therefore be declared abstract or implement the remaining methods

I didn't change any backend code .I dont know it triggers when I hit any url of laravel app it will show this error.I dont know why this happend and also need solution for this .My laravel version in 5.8 and php 7.2 Fatal error : Class Illuminate\Routing\RouteCollection contains 1 abstract method and must therefore be declared abstract or implement the remaining methods C:\xampp\htdocs\pmf\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php on line 14 this is file it is saying.



via Chebli Mohamed

Error in Updating data, caused by unknown column in Laravel REST API

I already finished the create and read in my laravel rest api project.

But when I tried to test the "PUT" method for updating it shown me an error. The error itself i dont know how to resolve that bcs I am still new to laravel. My table name is "tb_peminjaman", but the update method read it as a column of its table. Anyway, I didn't create the tables using migration cause I have my own table created directly using phpmyadmin, so basically the migration filled with default value.

Here is the Screenshot of my Error shown by Postman>

"I've tried to change my code also disable the timestamps because it could be caused any error for my project. Here I show you my Update code in controller."

public function updatePinjam(Request $request, $id){
        if(Pinjam::where('no_pengajuan',$id)->exists()){
            $pinjam = Pinjam::find($id);
            $pinjam->ketua_kegiatan = is_null($request->ketua_kegiatan) ? $pinjam->ketua_kegiatan : $request->ketua_kegiatan;
            $pinjam->lab = is_null($request->lab) ? $pinjam->lab : $request->lab;
            $pinjam->level = is_null($request->level) ? $pinjam->level : $request->level;
            $pinjam->tanggal_mulai = is_null($request->tanggal_mulai) ? $pinjam->tanggal_mulai : $request->tanggal_mulai;
            $pinjam->tanggal_selesai = is_null($request->tanggal_selesai) ? $pinjam->tanggal_selesai : $request->tanggal_selesai;
            $pinjam->jam_mulai = is_null($request->jam_mulai) ? $pinjam->jam_mulai : $request->jam_mulai;
            $pinjam->jam_selesai = is_null($request->jam_selesai) ? $pinjam->jam_selesai : $request->jam_selesai;
            $pinjam->daftar_nama = is_null($request->daftar_nama) ? $pinjam->daftar_nama : $request->daftar_nama;
            $pinjam->keperluan = is_null($request->keperluan) ? $pinjam->keperluan : $request->keperluan;
            $pinjam->kontak_ketua = is_null($request->kontak_ketua) ? $pinjam->kontak_ketua : $request->kontak_ketua;
            $pinjam->app_laboran = is_null($request->app_laboran) ? $pinjam->app_laboran : $request->app_laboran;
            $pinjam->app_kalab = is_null($request->app_kalab) ? $pinjam->app_kalab : $request->app_kalab;
            $pinjam->app_kajur = is_null($request->app_kajur) ? $pinjam->app_kajur : $request->app_kajur;
            $pinjam->app_pudir = is_null($request->app_pudir) ? $pinjam->app_pudir : $request->app_pudir;
            $pinjam->save();
            return response()->json([
            "message" => "Perubahan Berhasil DiLakukan!"
        ], 200);
        } else {
        return response()->json([
            "message" => "Pinjam not found"
        ], 404);
    }
    }

And here is the ERROR MESSAGE:

Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column &#039;tb_peminjaman.id&#039; in &#039;where clause&#039; (SQL: select * from `tb_peminjaman` where `tb_peminjaman`.`id` = 15 limit 1) in file C:\xampp\htdocs\coba_api_laravel\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 664

Please kindly help me to solve this Error, cause this is an important thing for me to continue to finish my project soon. Thank you so much



via Chebli Mohamed

Ckeditor5 fails to automatically update the value of the element in Laravel

When I try to insert a new record into my database I get the following error I am using ckeditor5 to add some basic functionality to the textarea. I am using the classic build and according to the documentation, the plugin is meant to automatically update the textarea to what ever was typed when the form is submitted. However laravel gives me this error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'long_description' cannot be null (SQL: insert into jobs (date_closing, title, user_id, short_description, long_description, location, category_id, updated_at, created_at) values (1986-03-03, Sunt ipsam eum in au, 6, Nam qui duis soluta, , Perspiciatis laboru, 5, 2019-06-27 13:13:26, 2019-06-27 13:13:26))

my view with some fields removed for clarity

@extends('home')
@section('dashboardContent')
<script src="https://cdn.ckeditor.com/ckeditor5/12.2.0/classic/ckeditor.js"></script>
<h1>New Job:</h1>
<div class="row">
  <div class="col">
    <form action="" method="POST">
      @csrf
      <div class="form-group">
        <label for="jobDescription">Description</label>
        <textarea class="form-control" name="jobDescription" id="jobDescription" rows="6"></textarea>
      </div>
      <button type="submit" class="btn btn-primary">Save</button>
    </form>
  </div>
</div>

<script>
  ClassicEditor
      .create( document.querySelector( '#jobDescription' ) )
      .catch( error => {
          console.error( error );
      } );
</script>
@endsection

The textarea gets replaced successfully but I cannot figure out why when the form is submitted the text area content is still null/empty



via Chebli Mohamed

php artisan migrate No suitable servers found (`serverSelectionTryOnce` set): [connection timeout calling ismaster on '10.0.0.106:27017']

I am trying to do

php artisan migrate 

but I got this

  No suitable servers found (`serverSelectionTryOnce` set): [connection timeout calling ismaster on '10.0.0.106:27017']  

how to fix it ?



via Chebli Mohamed

No hint path defined for [mail] - problem with send email in Laravel 5.8

I am beginner in Laravel. I use in my project Laravel 5.8:

I have this code:

$mailTitle = "Masz wiadomość ze strony " . env('APP_NAME');
        $message = "
        <b>Dane wiadomości:</b> $dateTime [IP: $ip]<br/>
        <b>Tytuł wiadomości:</b> $title<br/>
        <b>Imię:</b> $userName<br/>
        <b>Adres email:</b> $userEmail<br/>
        <b>Wiadomość:</b> $txt<br/>";

        $data['slot']= $message;
        $data['adminEmail']= $adminEmail;
        $data['title']= $mailTitle;
        $data['user']= $userEmail;
        Mail::send('vendor.mail.html.message', $data, function($message) use($data) {
            $message->to($data['adminEmail']);
            $message->subject($data['title']);
            $message->replyTo($data['user']);
            $message->from($data['user']);
        });

When I run this code I have error:

No hint path defined for [mail]. (View: /var/www/vanessa/resources/views/vendor/mail/html/message.blade.php)

How can I fix it?



via Chebli Mohamed

reuse controller / model in laravel

I want to reuse my code so I'm not repeating me self. I have made PostController and Post model. Now I want to create admin view page where I can CRUD my posts. Problem is here how to reuse Postcontroller to my admin view ?

to mentioned I'm new to laravel


use Illuminate\Http\Request;

use App\Post;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::all();

        return view('posts.post', compact('posts'));
    } ...


namespace App\Http\Controllers;

use App\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\PostsController;

class AdminController extends PostsController
{

    public function index()
    {
        $posts = Post::all();

        return view('admin.index', compact('posts'));
    }

}



via Chebli Mohamed

How I can optimize this laravel query builder query?

How I can optimize this query. This is working but I want optimal solution.

$query = AppUser::leftJoin( DB::raw('(SELECT user_id,question_id,answer FROM onlinetherapy_onboarding where question_id =8 GROUP BY user_id) b'), function($join) { $join->on('app_users.id', '=', 'b.user_id'); }) ->leftJoin( DB::raw('(SELECT user_id,status as verification_status FROM confirmation_codes GROUP BY user_id) c'), function($join) { $join->on('app_users.id', '=', 'c.user_id'); }) ->where('status','=', $user_status);

I expect optimal query.



via Chebli Mohamed

Overwrite function to the Controller in laravel Cashier

i getting 1 problem. the quetion is subscription the customer . when i use stripe cashier in the laravel. https://appdividend.com/2018/12/05/laravel-stripe-payment-gateway-integration-tutorial-with-example/ this link give me perfect answer. but now i want to remove some column on subscriptions table which is the cashier provided. i want to remove quantity on table.

My controller:

 //SubscriptionController.php

 class SubscriptionController extends Controller
    {
        public function create(Request $request, Plan $plan)
        {
            $plan = Plan::findOrFail($request->get('plan'));
            $stripeToken = $request->stripeToken;
            $user = $request->user();
            $stripeplan = $request->stripe_plan;
            $planid = $request->plan;
            $user->newSubscription($user->name, $planid)->create($stripeToken);
            return redirect()->route('home')->with('success', 'Your plan subscribed successfully');
        }
    }

now stripe Cashier

//Billable

    public function subscription($subscription = 'default')
        {
            return $this->subscriptions->sortByDesc(function ($value) {
                return $value->created_at->getTimestamp();
            })->first(function ($value) use ($subscription) {
                return $value->name === $subscription;
            });
        }

//subscriptionBuilder.php

    public function create($token = null, array $options = [])
        {
            $customer = $this->getStripeCustomer($token, $options);

            $subscription = $customer->subscriptions->create($this->buildPayload());

            if (in_array($subscription->status, ['incomplete', 'incomplete_expired'])) {
                $subscription->cancel();

                throw SubscriptionCreationFailed::incomplete($subscription);
            }

            if ($this->skipTrial) {
                $trialEndsAt = null;
            } else {
                $trialEndsAt = $this->trialExpires;
            }

            return $this->owner->subscriptions()->create([
                'name' => $this->name,
                'stripe_id' => $subscription->id,
                'stripe_plan' => $this->plan,
                'quantity' => $this->quantity,
                'trial_ends_at' => $trialEndsAt,
                'ends_at' => null,

            ]);
        }

I want to delete this three:

 'quantity' => $this->quantity,
 'trial_ends_at' => $trialEndsAt,
 'ends_at' => null,

from using subscription controller. how to overwrite



via Chebli Mohamed

Undefined Index - even though it seems to be defined? HELP, PLEASE :)

This is absolutely driving me insane, when i try to define the the filename within my array, using an index from the feed 'url' i get 'Undefined Index'

XML

    <images>
        <image id="1"><url>https://media.inmobalia.com/imgV1/B98Le8~d7M9k3DegpEFZhS0lI_F8U4XZVz~HWxt~mGgYekxX9nCAxh0ZipZlAjNxEM6s1ur~IyRoHkUHvRIKXOjuLeAihIByqSrPmMwRzskZNx1a12uD1e5Q9J3VkMbNMIhcfXGgDMEAXDNSVEZu.jpg
            </url>
        </image>
        ...

PHP

//Get the urls form images   
    public function collectKyeroImages($imagesData){
        //dd($imagesData);
        \Log::info("Collecting Images");

        $images = [];

        foreach ($imagesData as $image){
        //            dd($image);
            $obj = [
                'filename' => $image
                ];
                    $images[] = $obj;
                }

                dd($images);

            return $images;
    }

DD Result -

array:19 [
  0 => array:1 [
    "filename" => array:2 [
      "@attributes" => array:1 [
        "id" => "1"
      ]
      "url" =>"https://media.inmobalia.com/imgV1/B98Le8~d7M9k3DegpEFZhS0lI_F8U4XZVz~HWxt~mGgYekxX9nCAxh0ZipZlAjNxEM6s1ur~IyRoHkUHvRIKXOjuLeAihIByqSrPmMwRzskZNx1a12uD1e5Q9J3VkMbNMIhcfXGgDMEAXDNSVEZu.jpg"
    ]
 ]

Approach

        if (isset($val['images'])) {$pictures = $this->collectKyeroImages($val['images']['image']);} elseif (isset($val['images']['image'])) 

        public function collectKyeroImages($imagesData){
            //dd($imagesData);
            \Log::info("Collecting Images");
                foreach ($imagesData as $image){
        //            dd($image);
                    $obj = [
                    'filename' => $image['url']
                    ];
                $images[] = $obj;
            }
        //dd($images);

        return $images;

        }

Result = Undefined index;



via Chebli Mohamed

How to make a one to one eloquent relation in Laravel?

I created my migration by using the artisan command

php artisan make:model Player -m

My migration then looked like this:

public function up()
{
    Schema::create('players', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id')->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete$
        $table->string('username');
        $table->timestamps();
    });
}

Which left me no errors when I ran

php artisan migrate

I then updated my Player model App/Player.php to include the fillables and one to one relation

class Player extends Model
{
    protected $fillable = ['user_id', 'username'];

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

I then ran the Tinker artisan and my output when I try to access the player model is this

>>> User::find(1)->player;
=> null

What am I missing?



via Chebli Mohamed

Standard registration and logging in Laravel - adding a logo in the activation email

I'm beginner in Laravel. I have project in Laravel 5.8. I use in my project standard Laravel registration and login system.

I have a question, I would like to add the logo of my application to the activation email.

I would like to replace the standard "Application name" in the email logo of the application.

How can I do this?



via Chebli Mohamed

How can I view my Updated Data in blade.php from Cookies without onpage loading?

I'm working on a project called Online Food Order with laravel Framework. Here I am storing my data into cookie from menu after onclick add to cart. Now I want to show those data in may cart without on page loading. Because, if I load the page, it return me to the top, which is not user friendly. So how can I solve this problem...??

I just want to view the data immediately after clicking "Add To Cart" button.



via Chebli Mohamed

how to disable sociallite logs in laravel 5?

I Want to disable sociallite logs in laravel 5, how i can do this? i try diffrent ways but same result and not working it for me. how i can do this, How I can disable log file in Laravel 5 ?

I just dont want to disable only (sociallite) not other logs.

I Want to disable sociallite logs in laravel 5, how i can do this? i try diffrent ways but same result and not working it for me. how i can do this, How I can disable log file in Laravel 5 ?

I just dont want to disable only (sociallite) not other logs.



via Chebli Mohamed

mercredi 26 juin 2019

deleting data from database, "The GET method is not supported"

Trying to delete data from database and this is how I am using controller and route for this:

controller

public function articleDelete($id)
{

    return $article = Article::destroy($id);

    // return response()->json([
    //     "article" => $article,
    //     "message" => "Deleted Successfully"
    // ]);

}

api

Route::group(['prefix' => 'v1'], function(){
    /* fetch */
    Route::get("/articles", "Api\ArticlesController@allArticles");
    Route::get("/articles/{id}", "Api\ArticlesController@singleArticle");

    /* add new & delete */
    Route::post("articles/add", "Api\ArticlesController@newArticle");
    Route::post("articles/delete/{id}", "Api\ArticlesController@articleDelete");
});

and this is my method in vue components:

methods: {
    deleteArticle(article, id){
        axios.post("api/v1/articles/delete/" + article.id).then(response => {
            let index = this.articles.indexOf(article);
            this.articles.splice(index,1);
            console.log(response.data);
        })
    },
}

when I adding new article there no problem. But when I try to delete article there are errors. First in console my id is being undefined which is .../api/v1/articles/delete/undefined

and the this is the error.

The GET method is not supported for this route. Supported methods: POST.

I am already using post for the route why it s keep saying "get method is not supported." I am not using get for the route. And I cleared route:clear and checked, there is no problem route is on post.

What I am missing here? Thank you.

Additionally I am giving the key prop when I looping the datas. <tr :key="item.id" v-for="(item, index) in fetchArticle">

I don't understand why ID part is being undefined.



via Chebli Mohamed

How to hide color/size elements in Laravel

How do I hide the color or size if their values are empty?

SCREENSHOT

<p class="lx-sizes">
                        <span>SIZE :</span> @foreach ($produit->sizes as $size)
                        <a data-id="" href="javascript:;" class=""></a> @endforeach
                    </p>
                    <p class="lx-colors">
                        <span>COLOR :</span> @foreach ($produit->colors as $color)
                        <a data-id="" href="javascript:;" class=""></a> @endforeach
                    </p>



via Chebli Mohamed