samedi 29 février 2020

Laravel 5.5 : SimplePaginate get the lastPage

We implemented the simplePaginate in our application but our version of laravel is 5.5 which is lastPage() is not yet available.

Question: Any guide where I can get the lastPage of my pagination?

View

<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 col-lg-12">
    <div class="table-responsive">
        <table class="table table-striped table-bordered table-hover general-journal-report-table" id="gj-report">
            <thead class="thead-global">
                <tr>
                    <th id="pj_sequence">Sequence No.</th>
                    <th id="pj_date">Posting Date</th>
                    <th id="pj_op">Transaction No.</th>
                    <th id="4">Document Reference</th>
                    <th id="5">Remarks</th>  
                    <th id="6">Amount Due</th>
                </tr>
            </thead>
            <tbody class="general-journal-report-details">
                @if($defined_gj)
                <?php $counter = 0; ;?>
                <?php $total_debit = 0; ?>
                @foreach($defined_gj as $key => $value)
                    <?php $counter++;?>
                    <?php $total_debit += $value->debit ;?>
                    <tr>
                        <td class="pj_sequence"></td>
                        <td class="pj_date"></td>
                        <td class="pj_op">{!! $value->number !!}</td>
                        <td></td>
                        <td></td>
                        @if($value->debit == '0')
                        <td></td>
                        @else
                        <td align="right"> </td>
                        @endif
                    </tr>
                @endforeach
                    <tr>
                        <td><b>Total</b></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td align="right"> </td>
                    </tr>
                @endif
            </tbody>
        </table>
    </div>
    <p style="font-size: 12px;"><i>page  out of</i></p> 
    
</div>


via Chebli Mohamed

Use Auth in AppServiceProvider

I need the ID of the user who is logged in to get a photo in the profile table, here I am trying to use View but only in the index function that gets $ profile, I want all files in the view to have $ profile

 public function index()
 {
  $profil = Profil_user::where('user_id',$auth)->first();
  View::share('profil', $profil);
  return view('user.index');
}

I have also tried AppServiceProvider but I get an error in the form of a null value if I don't log in, is there a solution to my problem?

 public function boot()
{
    $auth = Auth::user();
    dd($auth);
}


via Chebli Mohamed

laravel public variable for different controllers

I want to set a public variable so I can use it in different controllers. I tried this but it is not successful.

class HomeController extends Controller
{
 public $TravelId;
public function __construct()
{
 $this->TravelId=0;
}
}

then I used the same variable in another contorller

class HomeController extends Controller
{
public function index($cus_id)
{
    //unique key for each user
    $this->TravelId = $cus_id;
}
}
class Helper

{public static function Update($id){

$user_idd = auth()->user()->id;
 $user = User::find($user_idd);
 if ($user->isAdmin ==1){ 
  $user_id = $this->TravelId;
  self::$staticTravelId = $user_id;
 }
 else{
   $user_id = $user_idd;
 }

I want to use the user_id Inside the public variable here



via Chebli Mohamed

Failed to restore eloquent model after it has been un-serialized (Laravel 5.4)

I cannot understand why an un-serialized eloquent model cannot be saved in the database table.

I am trying to restore previous versions of a "document" which are represented by an App\Document model. Before each document model is updated the previous "version" is serialized and stored in a different table so it can be retrieved in the future.

When I retrieve the serialized model and un-serialize it (unserialize()) I am calling the save() method on the model but nothing happens.

The code:

$targetModel = unserialize($serializedModel);                       
$modelSaved = $targetModel->save();

$modelSaved is always true but the row in the database table does not change.

After looking at the API i saw that when we call save() on a model then only if the model exists and is dirty will be updated.

Please note that if I 'dump' the $targetModel the properties attributes and original are the same and the call to isDirty() returns false.

I have also tried modifying an attribute of the un-serialized model so that isDirty() returns true but that has not changed anything.

Any ideas on how I can save the un-serialized model in the database? I am doing something wrong here, for sure.



via Chebli Mohamed

vendredi 28 février 2020

How to update DOM after on axios return React JS and Laravel

I want to update my entire dashboard when select date as like as the attached imageenter image description here

After select the date the entire page info will be updated. I am using React JS and axios to pick the date and Laravel to process the result and returning all arrays. But I am unsure how to embed the return results in the view (Blade).

Dashboard Blade:

<div class="container">
    <div class="row">
        <div class="col-lg-12 mb-4">
            <div class="row">
                <div class="col-lg-4 ml-auto" id='select-date'>
                </div>
            </div>
        </div>
    </div>
    <div id='dashboard-content'>
        .....
    </div>
</div>

Select Date:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

export default class SelectDate extends Component {

    constructor() {
        super();
        this.state = {
            value: ''
        }
    }

    selectDate(e) {
        let url = window.location.href
        let date = e.target.value
        this.setState({value: date})
        axios.get(url+ '/' +date).then(response => {
            alert(response.data)
            document.getElementById('dashboard_content').innerHTML = response.data
        }).catch(error => {
            alert(error)
        })
    }

    render() {
        return (
            <div>
                <select className="custom-select custom-select-sm" onChange={this.selectDate.bind(this)} value={this.state.value}>
                    <option selected value='7'>Last Week</option>
                    <option value="1">Today</option>
                    <option value="30">Last Month</option>
                </select>
            </div>
        );
    }
}

if (document.getElementById('select-date')) {
    ReactDOM.render(<SelectDate />, document.getElementById('select-date'));
}


via Chebli Mohamed

Im developing a laravel website and when i deployed on server im getting this database error

This is the error im getting

this is the url of the site http://graphixvilla.com/login



via Chebli Mohamed

Laravel Unautorized error on random browser

I have create my project using laravel. It work well, but in random browser it give me error like this:

[0] "Unautorized" on line 35 of file /vendor/laravel/framework/src/Illuminate/Foundation/helpers.php

In my device the program run so well, but in some client browser, sometimes it gives that error. I use laravel 5.5.* in this project.

How to solved this issue? Thanks in advance



via Chebli Mohamed

How to show up an alert message depending of the browser using LAravel?

I would like to show up an alert message remmending to use Google Chrome or Mozilla if a user open my app using Internet Explorer... I would like a kind of alert message or something like that.



via Chebli Mohamed

Subdirectory Laravel and Vue

I'm working with Laravel and VueJS, the laravel is in a subdirectory (https://ift.tt/39aCysf), I changed the settings of my apache vHost so that accessing that name would be redirected to the 'subdirectory / public' folder, however when I access it vuejs I run into this error:

enter image description here

when I access any sub route of the vue it can connect normal, but the main one gives this problem.

router/index.js

import Router from 'vue-router';
import Login from '@/components/Login';
import ForgotPassword from '@/components/ForgotPassword';
import Index from '@/components/Index';

Vue.use(Router);

export default new Router({
  mode: 'history',
  base: '/subdirectory',
  routes: [
    {
      path: '/',
      name: 'Index',
      component: Index,
      children: [
        {
          path: '',
          name: 'Login',
          component: Login,
        },
        {
          path: 'forgot-password',
          name: 'forgotPassword',
          component: ForgotPassword,
        },
      ],
    },

  ],
});

routes/web.php

<?php
//use Illuminate\Routing\Route;

use App\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

Route::get('/{any}', 'FrontendController@app')->where('any', '^(?!api).*$');```



via Chebli Mohamed

Why isn't the file being validated in Laravel on Android?

Laravel 5.1, Android any

There is a Controller with Request'om in which it is checked that the field is a file. On PC, ios everything works fine. But when you send a request from any Android device, the validation on the file does not pass. What could be the problem?

Headers Android:

:authority: *hide*
:method: POST
:path: /api/storage-files/upload
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
authorization: Bearer *hide*
content-length: 3454764
content-type: multipart/form-data; boundary=----WebKitFormBoundaryYr0MZZ0rMJLl5sm9
cookie: __stripe_mid=cfc323d6-af83-430e-9f6f-d33e8cc1ffc3; __stripe_sid=35e6d7a1-f2bf-4d0b-b199-d852d127a476; messagesUtk=8ee0c450327645a2a3c82b7186f825a0; __remjt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI5MDUyLCJpc3MiOiJodHRwczovL2Rldi53b290ZXIuY28vYXBpL2F1dGhlbnRpY2F0ZSIsImlhdCI6MTU4Mjg4NDAwNSwiZXhwIjo1OTk0MDYwMTU4Mjg4Mzk0NSwibmJmIjoxNTgyODg0MDA1LCJqdGkiOiIxdDBQcTRIZ1k4VlBBUWZRIn0.3fy4aQ-6_ZlQ24iRK_gYsJNRI6kavl6YliIraen33Eg;
origin: *hide*
referer: *hide*
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-origin
user-agent: Mozilla/5.0 (Linux; Android 9; Redmi Note 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.119 Mobile Safari/537.3

Headers PC:

:authority: *hide*
:method: POST
:path: /api/storage-files/upload
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,ru;q=0.8
authorization: Bearer *hide*
content-length: 23479
content-type: multipart/form-data; boundary=----WebKitFormBoundaryXgKf5soaXwGBBSlH
cookie: __insp_wid=1445796083; __insp_slim=1582884323068; __insp_nv=true; __insp_targlpu=aHR0cHM6Ly9vcmRlci53b290ZXIuY28v; __insp_targlpt=V29vdGVyIEFwcGFyZWw%3D; messagesUtk=5a1d38d712584ff0b2a51e293a16d324; __insp_pad=1; __insp_sid=2050589431; __insp_uid=1850924571; __stripe_mid=bea6de0b-e04e-48bf-8350-e1a5f3036b5b; __stripe_sid=945fea97-8153-493e-a013-61c6cabd7bf6; __hstc=219564742.ff885e014dec86c4b6961bfa88dbef06.1582884329546.1582884329546.1582884329546.1; hubspotutk=ff885e014dec86c4b6961bfa88dbef06; __hssrc=1; __remjt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI5MDUyLCJpc3MiOiJodHRwczovL2Rldi53b290ZXIuY28vYXBpL2F1dGhlbnRpY2F0ZSIsImlhdCI6MTU4Mjg4NDMzOCwiZXhwIjo1OTk0MDYwMTU4Mjg4NDI3OCwibmJmIjoxNTgyODg0MzM4LCJqdGkiOiI2cXRhc0dWdjZwa29DekxsIn0.Xsby0U0jndyJQuQUHtSd8i3_16tO2bN0MWGFMa3Idxo; __hssc=219564742.4.1582884329547; hs-messages-hide-welcome-message=true
origin:  *hide*
referer:  *hide*
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/70.0.3538.67 Chrome/70.0.3538.67 Safari/537.36


via Chebli Mohamed

Override parent including classes from child [duplicate]

I trying to create a child class to override parent method and I want to override parent included classes.

Example of parent class:

use \App\Core\Mapping\Status;

class ParrentClass {
    function map($array) {
        return [
            'id' => $array['id'];
            'status' => Status::map($array['status_id'])
        ];
    }
}

Example of child:

use \App\Core\Mapping\Child\Status;

class ChildClass extends ParentClass {}

so when i create ChildClass instance:

$child = new ChildClass();
$result = $child->map($some_array); // [id => 1, status => instance of \App\Core\Mapping\Status]

its working but child Status not overriding ParentClass Status. Is there any way to solve this? For child->map I want to get a \App\Core\Mapping\Child\Status instance.



via Chebli Mohamed

jeudi 27 février 2020

Laravel Auth return different data

Sorry, anyone please help me. I use Laravel 5.4. I just wanna echo auth()-user()->role in view, but the result is different when I echo auth()->user()->role in controller. This is the code.

if(!empty(auth()->user())){
   echo auth()->user()->role;
}

result from controller

<li class="">
   <a href="#withdraw" data-toggle="tab" aria-expanded="false">
     <i class="material-icons">archive</i>
     Withdraw 
     <div class="ripple-container"></div>
   </a>
</li>

result from view

The correct data is 3. Does anyone know the problem? I've tried to clear cache, but no changes. Thanks



via Chebli Mohamed

Laravel resource return null or db value

I need help, I want assistance with my api, I want to return an image if its available on the database or return null if no value on db.

Th is is my resource code

 return [
             'id'    => $this->id,
            'name' => $this->name,
            'photo' => isset($this->photo) ? url('/storage',$this->photo) : "",
        ];

Here is my json that is returns

"data": [
        {
            "id": 1,
            "name": "Public Safety",
            "photo": "https://xxxxxxxxxxxxx/storage"
        },
        {
            "id": 2,
            "name": "Severe / Extreme Weather",
            "photo": "https://xxxxxxxxxxxxx/storage"
        },

I want it to return photo data only if there is a value on db column, if nothing is there then return null.



via Chebli Mohamed

Laraval - Model Fields Is Returning Null

I have a weird issue that is causing my unit tests to fail in Laravel. I have a table that is created like this:

Schema::create('message_threads', function (Blueprint $table) {
            $table->string('id')->primary();
            $table->timestamps();
            $table->softDeletes();
            $table->string('user_id');
            $table->string('folder_id')->nullable();
            $table->boolean('starred')->default(false);
            $table->string('thread_id')->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('folder_id')->references('id')->on('message_folders')->onDelete('cascade');
        });

And in its associated model, when I call the getAttributes() function, the fields starred and folder_id are not present.

//The code
$messageThread = factory(MessageThread::class)->create();
print_r($messageThread->getAttributes());

Outputs the followings:

(
    [user_id] => USR-258995103d8c4d37bd6ec3a38dfe9312
    [id] => MTD-cb4f8f66ddfc4385b31155212cb57f91
    [updated_at] => 2020-02-27 14:15:55
    [created_at] => 2020-02-27 14:15:55
)

Why are these fields missing, especially the starred field, which has a default value of false?



via Chebli Mohamed

Laravel + CKEditor + Laravel File Manager – do not display images

my form:

<form>
    <textarea name="editor1" id="editor1" rows="10" cols="80">
    </textarea>
</form>

<script src="https://cdn.ckeditor.com/4.13.1/standard/ckeditor.js"></script>
<script>
    var options = {
        filebrowserImageBrowseUrl: '/laravel-filemanager?type=Images',
        filebrowserImageUploadUrl: '/laravel-filemanager/upload?type=Images&_token=',
        filebrowserBrowseUrl: '/laravel-filemanager?type=Files',
        filebrowserUploadUrl: '/laravel-filemanager/upload?type=Files&_token='
    };

    setTimeout(function(){
        CKEDITOR.replace( 'editor1', options );
    },100);
</script>

my route:

Route::middleware(['auth'])->group(function () {
    Route::get('/laravel-filemanager', '\UniSharp\LaravelFilemanager\Controllers\LfmController@show');
    Route::post('/laravel-filemanager/upload', '\UniSharp\LaravelFilemanager\Controllers\UploadController@upload');
});

enter image description here

Ckeditor is displayed. When I click on the img icon a window will open. But no files will be displayed.



via Chebli Mohamed

How to avoid repeated data in a select using Laravel?

I have this select

enter image description here

I'm getting all of this information from a table in my database... so I have some repeated rows... I would like to found a kind of if or something to avoid the repeated information in the select... this is my select

<div class="form-group row col-xs-3 col-md-4" >
<label class="control-label col-md-4" >Cartera: </label>
<div class="col-md-8">
 <select name="carteras_id" id="carteras_id" class="form-control">
@foreach ($carteras as $cartera)
  <option value="" class="form-control"></option>
@endforeach
</select>
</div>


via Chebli Mohamed

I want to display dynamic marker on google map using JS

var locations = '<?php print_r(json_encode($locations)) ?>'
console.log(locations); 
var mymap = new GMaps({ 
el: '#mymap', 
lat: 31.5204, 
lng: 74.3587, 
zoom:6 }); 



mymap.addMarker({ 
lat: 31.5204, 
lng: 74.3587, 
click: function(e) { alert('This Is Lahore, Pakistan.'); } });

this is response

[{"id":1,"user_id":2,"latitude":"37.33068424","longitude":"37.33063124","attacked_by":"1","created_at":"2020-02-09 00:00:00","updated_at":"2020-02-16 00:00:00"}]

how can i add multiple pointers using this response lang lat?



via Chebli Mohamed

Laravel Botman: Can't send anything but texts

  • BotMan Version: 2.5
  • PHP Version: 7.2.28
  • Messaging Service(s): Telegram, Facebook
  • Cache Driver: LaravelCache

I wanted to integrate Botman to one of my Laravel projects, but when I want to send for example image like in the documentation:

    $attachment = new Image('https://thenextdoor.org/wp-content/uploads/2016/11/placeholder-815x458.png');

    $message = OutgoingMessage::create('foo')
                ->withAttachment($attachment);

    // Reply message object
    $bot->reply($message);

It doesn't send anything and no log was generated. I implemented the bot like this:

 $config['telegram']['token'] = env('TELEGRAM_TOKEN');
 DriverManager::loadDriver(TelegramDriver::class);

 $bot = BotManFactory::create($config, new LaravelCache());

And it's working with base text messages, but if I want to send or receive an attachment somewhy it doesn't works.



via Chebli Mohamed

fwrite(): send of 6 bytes failed with errno=32 Broken pipe Laravel and Mailtrap

I am using laravel and Mailtrap for testing emails. Everything was working fine until only recently the app give the error below upon trying to send a mail

 ErrorException (E_NOTICE)
fwrite(): send of 6 bytes failed with errno=32 Broken pipe
Previous exceptions

    Expected response code 250 but got an empty response (0)

My last successful email was 8 days ago (19th Feb 2020). I have not made any change to my .env during this time so I don't understand why it is not working. I have tried port 25, 587 and 2525 with no success. Below is my .env entry

QUEUE_CONNECTION=sync

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=blahblah
MAIL_PASSWORD=blahblah
MAIL_ENCRYPTION=null

MAIL_FROM_ADDRESS=subscription@blah.com
MAIL_FROM_NAME='Subscription'

MAIL_REPLY_TO_ADDRESS=noreply@blah.com
MAIL_REPLY_TO_NAME='Subscription'

Please any ideas how to solve this issue?



via Chebli Mohamed

Laravel 5.4 one belongs to relationship not working

Currently I'm trying to make a belongsTo relation work

I'm trying to show some data in a table like this:

                        <tr>
                            <td> <?php echo e($exam->id); ?> </td>
                            <td> <?php echo e($exam->name); ?> </td>
                            <td> <?php echo e(($exam->exam_type_on == 2) ? __('External') : __('Internal')); ?> </td>
                            <td> <?php echo e(($exam->groupsExams != null) ? $exam->groupsExams->pluck('name')->implode(',') : ''); ?> </td>
                            <td> <?php echo e($exam->createdBy->name); ?> </td>
                            <td> <?php echo e($exam->updatedBy->name); ?> </td>
                            <td align="center">
                                <a href="<?php echo e(url('exams/'.$exam->id.'/edit/')); ?>"><i class="fa fa-pencil"></i></a>
                                &nbsp;&nbsp;<a class="remove-obj" data-action="<?php echo e(route('exams.destroy', [ 'id' => $exam->id])); ?>"  data-title="<?php echo app('translator')->getFromJson('Are you sure to delete this exam?'); ?>" data-true="<?php echo app('translator')->getFromJson('yes, delete'); ?>" data-false="<?php echo app('translator')->getFromJson('No, cancel please!'); ?>" data-deleted="<?php echo app('translator')->getFromJson('Deleted!'); ?>" data-text="<?php echo app('translator')->getFromJson('You will not be able to recover this exam!'); ?>" data-success-message="<?php echo app('translator')->getFromJson('Exam has been deleted.'); ?>"><i class="fa fa-trash"></i></a>
                            </td>
                        </tr>

But I keep getting this error:

Trying to get property 'name' of non-object

This is the model

public function createdBy() {
    return $this->belongsTo(User::class, 'created_by');
}

public function updatedBy() {
    return $this->belongsTo(User::class, 'updated_by');
}

The error is at the line with createdBy->name but updatedBy seems to work. I don't know what's wrong with the code



via Chebli Mohamed

laravel not show new image after editing only if remove cache

When I modify the images, the editing process succeeds, but no changes are made to the pictures and the new image does not appear after the edit except when I delete the cache



via Chebli Mohamed

Connecting method/function in laravel

I'm trying to create a class function which resembles how we used to fetch database listing and convert into a dropdown listing.

eg: DB::table()->where()->get()

what i would like to achieve in laravel custom class or through model is this

Dropdown::fetch()->toArray()

Dropdown::fetch()->toDropdown()

I tried to figure out how this can be done through google. But couldn't find any solution to it.

I'm using laravel 5.8



via Chebli Mohamed

From validation Throws error The GET method is not supported for this route. Supported methods: POST."

i am new to laravel..Kind of stuck at this place. Tried many solutions for this but none worked yet, There are similar question but most unresolved, or proper evident solution not posted yet(from google,stackoverflow ..etc)

i have defned a custom route

Route::post('/ComplaintGenerate', 'ComplaintsController@generate'); 

whenever i submit the view with 'POST' method as

<form action="/ComplaintGenerate" method="POST" > 

without any validation rule in my Complaintscontroller everything works fine and i can save data. but when i put validation either through Requests or direct it throws error Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException The GET method is not supported for this route. Supported methods: POST.

if i remove validation everything works fine. I also tried with GET method but still dint work. A little peace of advice will be very much appreciated.

Web.route

Route::middleware(['auth'])->group(function(){
Route::post('/Complaint', 'ComplaintsController@find'); 
Route::post('/ComplaintGenerate', 'ComplaintsController@generate');
Route::post('/Complaint/{Complaint}', 'ComplaintsController@save_customer');
Route::resource('Complaints', 'ComplaintsController');
Route::resource('Occupancies', 'OccupanciesController');
Route::resource('Customers', 'CustomersController');
Route::resource('Services', 'ServiceController');
Route::resource('ServiceTeams', 'ServiceTeamController');
Route::get('/home', 'HomeController@index')->name('home');});

My controller:

public function generate(GenerateInitialComplaintRequest $request)
{  
    $complaint = Complaint::find($request->complaint_id);
    $complaint->update([
        'complaint_date'=>$request->complaint_date,
        'complaint_description'=>$request->complaint_description,   
    ]);

    return redirect(route('Complaints.index')->with('complaint', Complaint::all()));           
}

my View:

<div class="container my-5">

<div class="col d-flex justify-content-center my-4">
    <div class="card">
        <div class="card-header">

            <form action="/ComplaintGenerate" method="POST" >
          @csrf
          @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li></li>
                        @endforeach
                    </ul>
                </div>
            @endif
          <div class="form-row">
            <div class="form-group col-md-6">
              <label for="complaint_id">Complaint Number</label>
              <input type="text" class="form-control" id="complaint_id" name="complaint_id" value="" readonly >
            </div>
            <div class="form-group col-md-6">
              <label for="complaint_date">Complaint Date</label>
              <input type="text" class="form-control" id="complaint_date" name="complaint_date">
            </div>
          </div>

          <div class="form-row">
            <div class="form-group  col-md-12">
              <label for="complaint_description">Complaint Description</label>
              <textarea class="form-control" id="complaint_description" name="complaint_description" rows="5"></textarea>
            </div>
          </div>             
         <div class="text-center">
             <button type="submit" class="btn btn-primary">Save</button>                
         </div>
    </form>
        </div>
    </div>
</div>


via Chebli Mohamed

mercredi 26 février 2020

How to check if a user is already created, if not, create, else show an error message that a user is created Laravel

I have a registration form in my front page and the goal is to check if a user is already created, if a user already exists, show an error message that a user is already created with given values.

My RegisterController create method now looks like this:

public function create(Request $request) {

    $create = User::create([
        'email' => $request['email'],
        'paypal_email' => $request['paypal_email'],
        'password' => Hash::make($request['password']),
    ]);

    if($create){
        Company::create(['user_id' => $create->id]);
        return redirect('/dashboard');
    }
}

How to check if a user is already created and if yes, show an error message?



via Chebli Mohamed

buenas tardes, amigos. soy nuevo utilizando php con framework laravel y quiera saber como hacer una consulta multitabla con eloquent

quisiera saber como hacer una consulta multiple con tablas spatie laravel permisssion usando eloquent



via Chebli Mohamed

Laravel using vagrant: php artisan migrate --seed giving errors

homestead version: 9.2.0 vagrant version: 2.2.7 php version: 7.2.21 mysql version: 8.0.18

I created a new laravel project. I created a database called tickets. I've added the third party code from https://github.com/creativetimofficial/material-dashboard-laravel. When I get to step where you run "php artisan migrate --seed" I'm getting two different errors depedning on how I set db port in .env file.

Here's a picture of my db users and their hosts.

enter image description here

when DB_HOST=127.0.0.1 and I run the artisan migrate I get an error saying Connection refused. I only tried using 127.0.0.1 because I saw online people saying to use this instead of localhost. Since the connection is refused I have a feeling this isn't correct.

When DB_HOST=localhost and I run artisan migrate I get an error saying

No such file or directory (SQL: select * from information_schema.tables where table_schema = tickets and table_name = migrations and table_type = 'BASE TABLE') {"exception":"[object] (Illuminate\\Database\\QueryException(code: 2002): SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = tickets and table_name = migrations and table_type = 'BASE TABLE') at /Applications/MAMP/htdocs/ticket-dashboard/vendor/laravel/framework/src/Illuminate/Database/Connection.php:669)

Questions: 1) should I be using the IP instead of localhost and if so why do I get connection refused with using the IP? 2) If using localhost is fine, what needs to be fixed to bypass this error?

I've been testing everything I can find online to help, but this is the closest I've gotten. Any advice or ideas would be greatly appreciated



via Chebli Mohamed

Laravel White Screen of Death on Windows 10

I have installed a fresh copy of laravel on my localhost in windows 10 with xampp environment but I am getting white screen of death issue. All I can see after running the server is white screen. I have checked my permissions and permissions are set accordingly. Can anyone help me out finding the issue.

Edited I have checked my apache error log and I find these errors.

[Wed Feb 26 15:58:52.043075 2020] [ssl:warn] [pid 17336:tid 728] AH01909: 
www.example.com:443:0 server certificate does NOT include an ID which matches 
the server name
[Wed Feb 26 15:58:52.076066 2020] [mpm_winnt:notice] [pid 17336:tid 728] 
AH00354: Child: Starting 150 worker threads.
[Wed Feb 26 17:57:25.500711 2020] [core:warn] [pid 17308:tid 568] AH00098: 
pid file C:/xampp/apache/logs/httpd.pid overwritten -- Unclean shutdown of 
previous Apache run?
[Wed Feb 26 17:57:25.978439 2020] [mpm_winnt:notice] [pid 17308:tid 568] 
AH00455: Apache/2.4.28 (Win32) OpenSSL/1.0.2l PHP/7.1.10 configured -- 
resuming normal operations
[Wed Feb 26 17:57:25.978439 2020] [mpm_winnt:notice] [pid 17308:tid 568] 
AH00456: Apache Lounge VC14 Server built: Oct  4 2017 11:36:32
[Wed Feb 26 17:57:25.978439 2020] [core:notice] [pid 17308:tid 568] AH00094: 
Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache'
[Wed Feb 26 17:57:25.989432 2020] [mpm_winnt:notice] [pid 17308:tid 568] 
AH00418: Parent: Created child process 2184
[Wed Feb 26 17:57:28.260244 2020] [mpm_winnt:notice] [pid 2184:tid 760] 
AH00354: Child: Starting 150 worker threads.

I have also changed the serverName from

www.example.com

to

localhost

in httpd-ssl.conf



via Chebli Mohamed

How to split given Google API getName value into first_name and last_name using Laravel and Google API login system?

I have created a user table and trying to implement Google API Login system.

My users table has fields for first_name and last_name, but Google API provides only a getName request, how could I split the given value of getName to two pecies and fill my migration table with given values?

LoginController:

    public function handleProviderCallback()
{
    try {
        $user = Socialite::driver('google')->user();
    } catch (\Exception $e) {
        return redirect()->to('/');
    }

    $existingUser = User::where('email', $user->getEmail())->first();

    if ($existingUser) {
        auth()->login($existingUser, true);
    } else {

        $newUser                    = new User;
        $newUser->provider_name     = 'google';
        $newUser->provider_id       = $user->getId();
        $newUser->first_name        = $user->getName();
        $newUser->last_name         = $user->getName();
        $newUser->email             = $user->getEmail();
        $newUser->email_verified_at = now();
        $newUser->save();

        auth()->login($newUser, true);
    }

    return redirect($this->redirectPath());
}
}

I know there is a way to make it happen with custom Php script and the answer is here Split text string into $first and $last name in php

But can't figure out how to implement it with my LoginController function handleProviderCallback

P.S I would not want to change my users_table to have only one column for name



via Chebli Mohamed

Laravel DB::raw query using multiple WHERE clauses

So I have a query that I would want to add some extra conditions to.

Query:

$providers = BusinessDetail::select(
    'business_details.name as description', 
    DB::raw('SUM(review_details.param_value) / COUNT(review_headers.id) AS avgUserReview')
)
->leftJoin('review_headers', 'business_details.id', '=', 'review_headers.business_detail_id')
->leftJoin('review_details', 'review_headers.id', '=', 'review_details.review_header_id')
->leftJoin('rate_params', 'review_details.rate_param_id', '=', 'rate_params.id')
->get();

I would want to add the following to the query DB::raw query DB::raw('SUM(review_details.param_value) / COUNT(review_headers.id) AS avgUserReview') alone.

->whereIn('rate_params.id', [1, 3, 4, 5])
->where('review_details.param_value', '<>', NULL)
->where('review_details.param_value', '<>', '')
->where('review_headers.review_status', '=', 1)

How do I go about that?

Anyone?



via Chebli Mohamed

Handling Laravel Eager Loading between Models in Controllers

I am struggling to get my head round how to structure eager loading between Models in my controllers

To start off I have two models which have a Many to Many relationship between them:

class HelpOption extends Model
{

    ...

    public function issue()
    {
        return $this->belongsToMany(Issue::class, 'issues_help_options', 'help_option_id');
    }
}

class Issue extends Model
{

    ...

    public function helpOption()
    {
        return $this->belongsToMany(HelpOption::class, 'issues_help_options', 'issue_id');
    }

}

Both the Issue and Help Option classes are defined within their own controllers, utilising typically CRUD methods, however to define the relationship I then defined an IssueHelpOptionController. I did this so I can easily return all Issues with their associated HelpOptions, however would this have been better to define in the IssueController's index method? I primarily did this so I could still retain the ability to retrieve the Issues without eager loading the other data.

class IssueHelpOptionController extends BaseController
{

    public function index()
    {
        $issues = Issue::with('messages')->get();

        // return response
        return $this->sendResponse($issues->toArray(), 'Escalated Issues retrieved successfully.');
    }

    public function show(Issue $issue)
    {
        $issue = Issue::where('id', '=', $issue->id)->with('messages')->first();

        // return response
        return $this->sendResponse($issue->toArray(), 'Escalated Issues retrieved successfully.');
    }
}

I feel that this method makes the Routes I defined around issues-help-options very clunky and not obvious to someone else who might pickup my code:

Route::get('/issues', 'IssueController@index');
Route::get('/issues/monthly', 'IssueController@getByMonth');
Route::get('issues/{escalatedIssue}', 'IssueController@show');
Route::patch('issues/{escalatedIssue}', 'IssueController@update');
Route::post('issues/{escalatedIssue}', 'IssueController@store');
Route::delete('issues/{escalatedIssue}', 'IssueController@destroy');

Route::get('/issues-help-options', 'IssueHelpOptionController@index');
Route::get('/issues-help-options/{escalatedIssue}', 'IssueHelpOptionController@show');

I would be grateful if someone could help clarify if I am currently going the correct way, or whether I need to adjust my approach at all. I have been struggling to find a lot of up-to date documentation about how to structure these controllers.



via Chebli Mohamed

Laravel how to manage many to many relationship for FAQs

I am working on adding FAQs in database using laravel 5.6 many to many relationship. Here are my migrations:

Faq Category: (List of all the types of FAQs)

Schema::create('faq_categories', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->softDeletes();
                $table->timestamps();
            });

Faq Table:

 Schema::create('faqs', function (Blueprint $table) {
                $table->increments('id');
                $table->string('title', 160);
                $table->longText('description');
                $table->boolean('published')->default(0);
                $table->softDeletes();
                $table->timestamps();
            });

Faq Types: (All the FAQs categories for particular FAQ)

Schema::create('faq_types', function (Blueprint $table) {
               $table->increments('id');
                $table->integer('faq_id')->unsigned();
                $table->foreign('faq_id')->references('id')->on('faqs')->onDelete('cascade');
                $table->integer('faq_category_id')->unsigned();
                $table->foreign('faq_category_id')->references('id')->on('faq_categories')->onDelete('cascade');
                $table->timestamps();
            });

I have defined relationship like this:

App\FaqCategory

class FaqCategory extends Model {

    use SoftDeletes;

    public function faqs() {
        return $this->belongsToMany('App\Faq');
    }
}

App\Faq

class Faq extends Model {

    use SoftDeletes;

    public function categories() {
        return $this->belongsToMany('App\FaqCategory');
    }

}

I want all the FAQs by their category. Suppose there General, Other category in faq_categories table then I want faqs grouped by General, Other.

But I am not able to retrieve all faqs grouped by category. I did following but facing error:

$faq = FaqCategory::find(1);
        return $faq->faqs;
        dd($faq);

Error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db_name.faq_faq_category' doesn't exist.

Can anyone suggest me how to deal with this situation or best way to handle this?



via Chebli Mohamed

Laravel-generated email not formatting HTML correctly

I am struggling with email formatting issue, with Laravel. I get the email content (HTML) from the database, which doesn't really matter, but then quotes get added around, the format is wrong and my email looks like this:

t formatting my email corres

Here is my code, thanks a lot for your help!

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cookie;

class InsuranceEmail extends Mailable
{
    use Queueable, SerializesModels;
    protected $attacheddoc;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($attacheddoc)
    {
        $this->attacheddoc=$attacheddoc;
    }

    /**
     * Build the message.rubr
     *
     * @return $this
     */
    public function build()
    {
        $name = Auth::user()->nom . " " .  Auth::user()->prenom;

        $sqlContent="SELECT texte from blabla";

        $content = DB::connection('blabla')->select( DB::connection('blabla')->raw($sqlContent))[0]->texte;
        $content = str_replace('#memberName#', $name, $content);
        $content = str_replace('"', '', $content); //I tried this, without any hope ;)

        return $this->from('contact@blabla.net')
                ->markdown('emails.blabla')->with([
                    'title' => "Email onject",
                    'memberName' => $name,
                    'content' => $content,
                ])
                ->attach($this->attacheddoc, array(
                    'as' => 'attacheddoc.pdf', 
                    'mime' => 'application/pdf'));
    }
}


via Chebli Mohamed

how to put schedule task jobs in chain in laravel?

I am using laravel task scheduling inside it queue jobs or working i want to put these jobs in chain kernel.php

    $schedule->job(new \App\Jobs\FetchEmailAttachment)->dailyAt('16:15')->timezone('Australia/Melbourne');
    $schedule->job(new \App\Jobs\UploadFileFTP)->dailyAt('16:15')->timezone('Australia/Melbourne');
    $schedule->job(new \App\Jobs\SplitAttachment)->dailyAt('16:15')->timezone('Australia/Melbourne');           
    $schedule->job(new \App\Jobs\ResendAttachment)->dailyAt('16:15')->timezone('Australia/Melbourne');

I tried to use laravel withChain method but its not working .

I want to run these job in chain



via Chebli Mohamed

how can i get array value with javascript

I made a questionnaire and the user can choose more than one choice. this is my source code here I add ajax to store data.

@foreach($answer as $a)
<div class="col-6 mt-3">
<button data-icon="#" data-plhn="" class="btn btn-white btn-block border-0 answer"></button>
<span class="field-icon"><i class="fa " id=""></i></span>
</div>
@endforeach
<script type="text/javascript">
    $(document).ready(function(){
        $('.answer').click(function(){
            $('.answer').removeClass('selected');
            $('.fa-check-circle').removeClass('fa-check-circle text-white').addClass('fa-circle-o text-dark');
            $($(this).attr("data-icon")).removeClass('fa-circle-o text-dark').addClass('fa-check-circle text-white');
            $(this).addClass('selected');
            var jawaban = $(this).attr('data-plhn');
            var id_kuis = ;
            var token = '';
            var html_id = '.' + $(this).attr('id');
            $.ajax({
                url: "",
                type: "POST",
                data: {jawaban:jawaban,id_kuis:id_kuis,_token:token},
                dataType: 'json',
                success: function(data){
                }
            });
        });
    });
</script>

and this my button to next quiz

<a href="" class="btn btn-asdp border-0 px-5 py-2 shadow ml-3">Next</a>

I want to take the answer from the user but I am confused how to retrieve data arrays like this. can you help me, thank you



via Chebli Mohamed

Laravel how to use service globally without injection to all classes

The task is to create SmsService, which will be used everywhere. To use it inside any class, I have to inject it or create an instance. It works but I think there is a better solution. Does exist the mechanism to do it globally or maybe there are any other suggestions for this task?



via Chebli Mohamed

mardi 25 février 2020

Unsupported SSL request - Php artisan serve

After running command php artisan serve it prompt Laravel development server started: http://127.0.0.1:8000 but after run the same address in browser showing error 127.0.0.1:49938 Invalid request (Unsupported SSL request)

.env file APP_url=APP_URL=http://127.0.0.1:8000/

Already done clear cache,view,config, routes



via Chebli Mohamed

How would I decode this JSON to insert into a json column? ErrorException: Object of class stdClass could not be converted to string in file

What would be the proper way to decode this json?

my model has

 protected $casts = [
        'items' => 'array'
    ];

my json items:

{
    "data": [
    {
        "name": "Google",
        "link": "http://google.com"
    }, 
    {
        "name": "ALink",
        "link": "http://link.org"
    }
  ]
}

json_decode($request->items) returns the error: ErrorException: Object of class stdClass could not be converted to string in file



via Chebli Mohamed

Rutas relativas y absolutas en Laravel PHP URL's

el problema consiste en que cuando las rutas o directorios se extienden mass alla del directorio raiz, hay funcionalidades que no las reconoce. Adjunto archivo de rutas.

En el caso de esta ruta, me toma el estilo de Css, pero no los archivos Js donde tengo una tabla dinamica:

Route::get('/pacientes/listado', 'PersonaController@showTablePacientes')->name('listadoPacientes');

Pero en este caso me toma los archivos CSS y el JS

Route::get('/pacientes/', 'PersonaController@showTablePacientes')->name('listadoPacientes');

Estaria tendiendo problema con la declaracion rutas alternativas y absolutas.

Todos los archivos se encuentran dentro de la carpeta public/style_template y las rutas para que me funcionen son todas absolutas.

  <link href= rel="stylesheet">

Esta ruta se encuentra en App/public/styles_template

De que manera se representan en Laravel las relativas para acceder desde todo el proyecto?

Saludos.



via Chebli Mohamed

how to get week +4 in this day with carbon

I have a problem here I want to get the +4 week date from the current date using carbon, the +4 week plan will be dynamic depending on the input entered by the user, how do I make it, I've tried using this code but it's time to step back

 $dt = Carbon::now();
        dd($dt->week(4)->format('Y-m-d'));


via Chebli Mohamed

Login only with phone number without password - Laravel

I'm working in Laravel, So far I created two logins using guard. Now I'm trying to login via Google using socialite. So successful authentication from google, I get a users profile. So from that I can get users email Id. Now I want to login via same guard with password.

'adminpanel' => [
            'driver' => 'session',
            'provider' => 'adminusers',
        ],
         'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ]
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
'adminusers' => [
            'driver' => 'eloquent',
            'model' => App\VendorUser::class,
        ],
    ],

So is there is any tricks to make a authentication, I tried a alot.



via Chebli Mohamed

How to pass array result to angular grid

this is the example script of angular grid,in my laravel blade

<script type="text/javascript">
  angular.module('app', ['ngTouch', 'ui.grid'])
  .controller('MainCtrl', MainCtrl);

function MainCtrl() {
  this.myData = [
    {
        firstName: "Cox",
        lastName: "Carney",
        company: "Enormo",
        employed: true
    },
    {
        firstName: "Lorraine",
        lastName: "Wise",
        company: "Comveyer",
        employed: false
    },
    {
        firstName: "Nancy",
        lastName: "Waters",
        company: "Fuelton",
        employed: false
    }
  ];
}
</script>

its looks like below. enter image description here

I want to pass my query result to this table and display with corresponding columns.

controller

        $userObjs = works::getWorksFull();
        return view('admin.works.full_assign',['userObjs'=>$userObjs]);

Model works.php

    public static function getWorksFull()
{ 
    $results = self::select('ID','Number','Name','Type','District','Segment','status')
    ->where('status','=',"Open" )       
    ->get();
    return $results;
}

My blade view

<html ng-app="app">
<div ng-controller="MainCtrl as $ctrl">
    <div ng-controller="MainCtrl as $ctrl">
      <div id="grid1" ui-grid="{ data: $ctrl.myData }" class="grid"></div>
    </div>
</div>    
</html>


via Chebli Mohamed

Laravel - Calculated query with join inside it

I'm beginning with Laravel ORM Eloquent and i would like to do a query with some calculated fields that depend on 2 tables. So i have to do a subquery inside the calculated query but i don't know how to do that with the Eloquent query builder.

Example of query that i want to do :

select * , 
(select activites.id_activites from activites inner join insc_ses on insc_ses.id_activites=activites.id_activites where id_session=1 
and insc_ses.id_inscription=inscriptions.id_inscription) activite_session1, 
(select activites.id_activites from activites inner join insc_ses on insc_ses.id_activites=activites.id_activites where id_session=2 
and insc_ses.id_inscription=inscriptions.id_inscription) activite_session2, 
(select activites.id_activites from activites inner join insc_ses on insc_ses.id_activites=activites.id_activites where id_session=3 
and insc_ses.id_inscription=inscriptions.id_inscription) activite_session3 
from inscriptions

Is that possible to do ?



via Chebli Mohamed

To create and update attendance system in laravel.. Having issue in array storing

I have undergoing a project of student management system where i have certain number of batches for month so each batch will have a max of 20 students, As well as each batch will have certain dates (Morning session and Afternoon session). For Example : Batch A will have 18 Students and will have 3 dates like DD-MM-YYYY, DD-MM-YYYY, DD-MM-YYYY. As a admin i need to register attendance for each student, each batch, each date and each session.

It means i have a consolidated screen for one batch including students, dates and sessions.

when i click batch it should show the batch students as well as batch dates, under batch dates there should be check box when i click the checkbox it should be marked as present, if not should be marked as absent.

It is in the table view where header consists of dates. While the body rows consists of student name and checkbox matching the dates column.

All the datas should be posted in one go and also need to retrieve and update the datas.

I have tried using array to store the datas but all the datas storing into the database are not stored according to the need.

How to achieve this?

Tried codes are below..

In Controller..

public function get_add($id)
{
    $module = $this->module;

    $singleData = $this->batch->find($id);
    return view('admin.'.$module.'.add_edit', compact('singleData', 'module'));
}

public function post_add(Request $request, $id)
{
    $module = $this->module;
    // $this->attendance->fill($request->all());

    $dd = $request->schedule_id;
    if($dd){
        foreach($request->schedule_id as $key => $v){
            $data = array(
                'batch_id' => $id,
                'schedule_id' => $request->schedule_id [$key],
                'user_id' => $request->user_id [$key],
                'am_attendance_status' => isset($request->am_attendance_status [$key]) ? 1 : 0,
                'pm_attendance_status' => isset($request->pm_attendance_status [$key]) ? 1 : 0,
                'created_at' => new DateTime,
                'updated_at' => new DateTime,
            );
            // dd($data);
            Attendance::insert($data);
        }
      return redirect('admin/'.$module.'/')->with('success', 'Data has been updated');
    }else{
      return redirect('admin/'.$module.'/')->with('error', 'Data has not been updated');
    }

}

In Modal..

<?php namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;

class Attendance extends Authenticatable
{
   use SoftDeletes;
   protected $dates = ['deleted_at'];

   protected $table = 'attendance';
   protected $fillable = ['batch_id', 'schedule_id', 'user_id', 'am_attendance_status', 'pm_attendance_status'];

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

  public function batch()
   {
    return $this->belongsTo('App\Batch', 'batch_id');
   }

   public function schedule()
   {
     return $this->belongsTo('App\Schedule', 'schedule_id');
   }

 }

In Route..

 //Attendance
Route::get('attendance', 'Admin\AttendanceController@get_index');
Route::get('attendance/{id}/add', 'Admin\AttendanceController@get_add');
Route::post('attendance/{id}/add', 'Admin\AttendanceController@post_add');

In View..

<div class="table-responsive text-center">
<table id="dataTable" class="table table-bordered table-hover" style="white-space: nowrap;">
    <thead>
        <th>#</th>
        <th>NRIC</th>
        <th>Student Name</th>
        @foreach($singleData->schedule as $list)
        <th class="text-center" colspan="2"></th>@endforeach
    </thead>
    <thead>
        <th></th>
        <th></th>
        <th></th>
        @foreach($singleData->schedule as $list)
        <th class="text-center"></th>
        <th class="text-center"></th>
        @endforeach
    </thead>
    @php $students = App\StudentHasCourse::with('user')->where('batch_id', $singleData->id)->get(); @endphp
    <?php $count = 0; ?>
        @foreach($students as $row)
        <?php $count++; ?>
            <tr>
                <th style="font-weight: normal;"></th>
                <th style="font-weight: normal;">@foreach($row->user->student as $stud)  @endforeach</th>
                <th style="font-weight: normal;"></th>
                @foreach($singleData->schedule as $list)
                <input type="hidden" name="batch_id[]" value="">
                <input type="hidden" name="user_id[]" value="">
                <input type="hidden" name="schedule_id[]" value="">
                <td>
                    <input type="checkbox" name="am_attendance_status[]" value="1">
                </td>
                <td>
                    <input type="checkbox" name="pm_attendance_status[]" value="1">
                </td>
                @endforeach
            </tr>
            @endforeach
</table>

Database Fields..

id 
user_id 
batch_id 
schedule_id 
am_attendance_status 
pm_attendance_status 
created_at 
updated_at 
deleted_at

View image link.. https://ibb.co/r485jYX



via Chebli Mohamed

How to call a particular function while leaving a specific route in laravel?

I want to call a particular function that can be anywhere liken in any ServiceProvide or in any Middleware whenever user leaves from a specific route in Laravel?



via Chebli Mohamed

lundi 24 février 2020

How to send message on whatsup group using Gupshup API

I have send whatsup message to single user using Gupshup API, Can we send message on given whatsup group?

Referred link : https://www.gupshup.io/



via Chebli Mohamed

Sending html content as mail body laravel mail sending application

My controller is

public function basic_email() {
  $data = array('name'=>"Virat Gandhi",'roll'=>"123");
  Mail::send(['text'=>'mail'], $data, function($message) {
     $message->to('xyz@gmail.com', 'Basil Baby')->subject
     ('Laravel Basic Testing Mail');
     $message->from('abc@yahoo.com','Virat Gandhi');
  });
  echo "Basic Email Sent. Check your inbox.";

}

My blade is

Hi, 
  your roll number is 
  please click on the link to <a href="#">verify your account</a>

Mail is being received. but the mail body is displaying html content as such. How to make verify you account a html link in mail body



via Chebli Mohamed

Larvel with google map is not showing markers from lattitude and longitude values in databse

I am trying to show markers on Google map from already stored values (lattitude and longitude) in mysql databse. but when i try to load it markers are not showing in google map. Am new to laravel. please help me to implement it.

Following is the code in view page

@extends('user.layout.app')

@section('content')
    <script src=""></script>
    <div class="container-fluid add-location">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <form method="post" action="" name="clinicssview" id="clinicssview" enctype="multipart/form-data" novalidate>
                        
                        <div class="card-header">
                            <h4 class="card-title"> View Clinics </h4>
                        </div>
                        @if(!empty($errors->all()))
                            <div class="row"> @foreach ($errors->all() as $error)
                                    <div class="col-lg-12">
                                        <div class="alert alert-danger"> <span></span> </div>
                                    </div>
                                @endforeach </div>
                        @endif
                        <div class="card-content">
                            <div class="row">
                                <div class="col-xs-12 col-sm-12 col-md-6">
                                            <div class="form-group hide">
                                                <label class="control-label">Location
                                                    <star>*</star>
                                                </label>
                                                <input id="pac-input" name="location" class="controls form-control" type="text" placeholder="Search Box">

                                            <!-- <div id="map" height="1000" width="1000"></div> -->

                                            </div>
                                            <h4 >Preview</h4>
                                            <div class="form-group">
                                                <div id="regularMap" class="map"></div>
                                            </div>
                                        </div>
                                <div class="col-xs-12 col-sm-12 col-md-12">
                                    <div class="form-group">
                                        <label class="control-label">Clinic Name
                                            <star>*</star>
                                        </label>
                                        <input disabled id="user_name" name="user_name" class="controls form-control" type="text" placeholder="Clinc Name" value="">
</div>
                                </div>

                                <div class="col-xs-12 col-sm-12 col-md-12">
                                    <div class="form-group">
                                        <label class="control-label">Contact First Name
                                            <star>*</star>
                                        </label>
                                        <input disabled id="contact_fname" name="contact_fname" class="controls form-control" type="text" placeholder="Contact First Name" value="">
                                         </div>
                                </div>

                                <div class="col-xs-12 col-sm-12 col-md-12">
                                    <div class="form-group">
                                        <label class="control-label">Contact Second Name
                                            <star>*</star>
                                        </label>
                                        <input disabled id="contact_sname" name="contact_sname" class="controls form-control" type="text" placeholder="Contact Second Name" value="">
                                        </div>
                                </div>

                                <div class="col-xs-12 col-sm-12 col-md-12">
                                    <div class="form-group">
                                        <label class="control-label">Contact Address
                                            <star>*</star>
                                        </label>
                                        <input disabled id="contact_address" name="contact_adress" class="controls form-control" type="text" placeholder="Contact Address" value="">
                                         </div>
                                </div>

                                <div class="col-xs-12 col-sm-12 col-md-12">
                                    <div class="form-group">
                                        <label class="control-label">Contact City
                                            <star>*</star>
                                        </label>
                                        <input disabled id="contact_city" name="contact_city" class="controls form-control" type="text" placeholder="City" value="">
                                        </div>
                                </div>

                                <div class="col-xs-12 col-sm-12 col-md-12">
                                    <div class="form-group">
                                        <label class="control-label">Contact State
                                            <star>*</star>
                                        </label>
                                        <input disabled id="contact_state" name="contact_state" class="controls form-control" type="text" placeholder="State" value="">
                                       </div>
                                </div>

                                <div class="col-xs-12 col-sm-12 col-md-12">
                                    <div class="form-group">
                                        <label class="control-label">Clinic Zip
                                            <star>*</star>
                                        </label>
                                        <input disabled id="zip" name="zip" class="controls form-control" type="text" placeholder="Zip" value="">
                                      </div>
                                </div>

                                <div class="col-xs-12 col-sm-12 col-md-12">
                                    <div class="form-group">
                                        <label for="email" class="control-label">Email
                                            <star>*</star>
                                        </label>
                                        <input disabled id="email" type="email" class="form-control" name="email" placeholder="Email" value="">
                                    </div>
                                </div>

                                <div class="col-xs-12 col-sm-12 col-md-12">
                                    <div class="form-group">
                                        <label class="control-label">Clinic Phone Number
                                            <star>*</star>
                                        </label>
                                        <input disabled id="phone" name="phone" class="controls form-control" type="text" placeholder="Phone Number" value="">
                                       </div>
                                </div>

                                <div class="col-xs-12 col-sm-12 col-md-12">
                                    <div class="form-group">
                                        <label class="control-label">Clinic Website
                                            <star>*</star>
                                        </label>
                                        <input disabled id="clinic_website" name="clinic_website" class="controls form-control" type="text" placeholder="Website" value="">
                                 </div>
                                </div>


                            </div>
                            <div class="row">



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

    <script>
      var customLabel = {
        restaurant: {
          label: 'R'
        },
        bar: {
          label: 'B'
        }
      };

        function initMap() {
        var map = new google.maps.Map(document.getElementById('regularMap'), {
          center: new google.maps.LatLng(-33.863276, 151.207977),
          zoom: 12
        });
        var infoWindow = new google.maps.InfoWindow;

          // Change this depending on the name of your PHP or XML file
          downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('marker');
            Array.prototype.forEach.call(markers, function(markerElem) {
              var id = markerElem.getAttribute('id');
              var name = markerElem.getAttribute('name');
              var address = markerElem.getAttribute('address');
              var type = markerElem.getAttribute('type');
              var point = new google.maps.LatLng(
                  parseFloat(markerElem.getAttribute('lat')),
                  parseFloat(markerElem.getAttribute('lng')));

              var infowincontent = document.createElement('div');
              var strong = document.createElement('strong');
              strong.textContent = name
              infowincontent.appendChild(strong);
              infowincontent.appendChild(document.createElement('br'));

              var text = document.createElement('text');
              text.textContent = address
              infowincontent.appendChild(text);
              var icon = customLabel[type] || {};
              var marker = new google.maps.Marker({
                map: map,
                position: point,
                label: icon.label
              });
              marker.addListener('click', function() {
                infoWindow.setContent(infowincontent);
                infoWindow.open(map, marker);
              });
            });
          });
        }



      function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
          if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
          }
        };

        request.open('GET', url, true);
        request.send(null);
      }

      function doNothing() {}
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
    </script>
@endsection

I will get latitude and longitude values by <?php echo $loc->lat ?> & <?php echo $loc->long ?> in this same page but i dont know how to pass it, please help me



via Chebli Mohamed

how to retrive maximun version related to post?

I have two tables:

table posts
id
text

table old_posts
id 
post_id
text
version

the relation is one to many between post and old_posts when the user edits his/her post I save the old version in old_posts but I need to increment the version number so I have first to get the maximum version for that post.

how I achieve this?



via Chebli Mohamed

Remove Laravel Package routes and add new

I installed this package https://github.com/jeremykenedy/laravel-roles on my Laravel 6.X application, I wanted to disable the routes so I would like to add a prefix of admin/ before the set routes... Changing the routes in Vendor folder doesn't help because it will get updated and gone if you run composer update, any idea on how to solve this issue, other than forking the repo?

thanks in advance.



via Chebli Mohamed

getting error Fatal error: in vendor/laravel/framework/src/Illuminate/Foundation/Application.php on line 25

I am using laravel 5.5, My project was working fine. Suddenly it start showing below error.

Fatal error: in /home/user/sandbox/project/vendor/laravel/framework/src/Illuminate/Foundation/Application.php on line 25

Here is image of log. enter image description here

I have tired below solution. But nothing worked

php composer.phar dump-autoload
php composer.phar install --no-scripts
php composer.phar update

Tired removing vendor folder and again running above command.

But to no avial. Please help.



via Chebli Mohamed

lavavel using redis as cache driver in production and storing many hash values

I'm using redis as cache driver for laravel application and laravel is store a lot of hash value into redis. But it's only happened in production env config and not in local env. Because of this, it leads to stop the laravel with out of memory error. But it doesn't store such hash values in local environment. The format of the hash value is app_name_database_database_name_cache:a04208811167972b6d621ea7e058a236



via Chebli Mohamed

laravel preg_replace Compilation failed: invalid range in character class

Please take a look at blew error and my code.Something Am I missing anything?

call stack

in /app/Http/Controllers/Controller.php line 217
at HandleExceptions->handleError('2', 'preg_replace(): Compilation failed: invalid range in character class at offset 13', '/app/Http/Controllers/Controller.php', '217', array('string' => 'gegegeg', 'separator' => '-'))
at preg_replace('/[^a-z0-9_\-\s-ءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]/u', '', 'gegegeg') in Controller.php line 217
at Controller->make_slug('gegegeg') in AdsController.php line 153
at AdsController->FormAds('14', '71', '97', object(Request))
at call_user_func_array(array(object(AdsController), 'FormAds'), array('main_id' => '14', 'sub_id' => '71', 'typ_id' => '97', object(Request))) in Controller.php line 80

Code

 echo preg_replace('/[^a-z0-9_-s-ءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]/u', '', 'gegegeg');

Error:

preg_replace(): Compilation failed: invalid range in character class at offset 13

Best Regards



via Chebli Mohamed

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'items.box_box_barcode' in 'where clause'

I am trying to display specific data from 2 database tables (boxes and items) that have 2 models with a hasMany belongsTo relationship in Laravel 5.8 but I get the error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'items.box_box_barcode' in 'where clause' (SQL: select * from items where items.box_box_barcode = TRTB0001 and items.box_box_barcode is not null)

See my code:

Box.php (model)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Box extends Model
{

    protected $guarded = [];


    protected $primaryKey = 'box_barcode';
    public $incrementing = false;
    protected $keyType = 'string';



    public function items(){

        return $this->hasMany(Item::class);
    }
}

Item.php (model)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{

    protected $primaryKey = 'item_barcode'; // or null

    public $incrementing = false;

    // In Laravel 6.0+ make sure to also set $keyType
    protected $keyType = 'string';


    public function company(){

        return $this->belongsTo(Company::class);
    }
}

create_boxes_table.php (migration 1)

<?php

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

class CreateBoxesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('boxes', function (Blueprint $table) {
            //$table->bigIncrements('id');
            $table->string('box_barcode')->primary();
;      //want this to be my id that can increment
            $table->string('sort_description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('boxes');
    }
}

create_items_table.php (migration 2)

<?php

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

class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            //$table->bigIncrements('id');
            $table->string('item_barcode')->primary();
; //want this to be my id that can increment
            $table->string('its_box_barcode');
            $table->string('item_quality');
            $table->timestamps();


        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('items');
    }
}

boxesController.php (controller)

<?php

namespace App\Http\Controllers;

use App\Box;
use Illuminate\Http\Request;

class boxesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $boxes = Box::all();       
        return view('boxes.index', compact('boxes'));
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Box  $box
     * @return \Illuminate\Http\Response
     */
    public function show(Box $box)
    {
        return view('boxes.show', compact('box'));
    }


}

index.blade.php (view)

@extends('layout')


@section('title', 'Boxes')  


@section('content')


    <h1>Boxes</h1>

     <ul style="list-style-type: none;">

       @foreach($boxes as $box) 

         <li>
            <a href="/boxes/">
                  
            </a>
         </li>

       @endforeach

    </ul>           

 @endsection

show.blade.php (view)

@extends('layout')


@section('title', 'Show Box')  


@section('content')


@if ($box->items->count())
    <div>
        @foreach ($box->items as $item)

            <div>

                <form method="POST" action="/items/">
                    @method('PATCH')
                    @csrf

                    <!-- USE TO STRIKETHROUGH A CONPLETED TASK IN WEB PAGE -->
                    <label class="checkbox " for="in" >

                    <input type="checkbox" name="in" onChange="this.form.submit()" >
                            

                    </label>


                </form>



            </div>

        @endforeach

    </div>
@endif

@endsection


via Chebli Mohamed

Laravel 5.8 custom primary keys that allows hasMany belongsTo relationships

I am trying create two database tables (boxes and items) that will eventually be coded into 2 models with a hasMany belongsTo relationship in Laravel 5.8

These are the migrations I hope to make (below).

create_boxes_table.php

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

class CreateBoxesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('boxes', function (Blueprint $table) {
            //$table->bigIncrements('id');
            $table->string('box_barcode');      //**want this to be my id that can increment**
            $table->string('sort_description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('boxes');
    }
}

create_items_table.php

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

class CreateItemsTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            //$table->bigIncrements('id');
            $table->string('item_barcode');  //**want this to be my id that can increment**
            $table->string('its_box_barcode');
            $table->string('item_quality');
            $table->timestamps();


        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('items');
    }
}

How do I make Laravel recognize these as ids that I would want to make relationships on in my CRUD? For example:

  • show only the item_barcodes that belong to box_barcode TRB0001 when someone clicks on its box link
  • show only the item_barcodes that belong to box_barcode TRB0002 when someone clicks on its box link
  • etc etc

Unless there is a better way to structure these data tables for relationships

See example below:

enter image description here



via Chebli Mohamed

Laravel API returns file and client must show download dialog

I am developing an Laravel 5.3 API Brige to download some files to various systems. What I want to achieve:

  1. User clicks download button
  2. PHP web does a cURL post request to API
  3. Api response may be a file or a 404 HTTP Code
  4. Client browser shows file download dialog

APi method:

    $reportService = new ReportService($request->get('vRefGMS'));
    $reportData = $reportService->handle();
    if ($reportData) {
        $serverService = new NetServerService($reportData);
        $csvFile = $serverService->handle();
        if ($csvFile != null) {
            return response()->file($csvFile);
        } else {
            return abort(404);
        }
    } else {
        return abort(404);
    }

Now i will show you the code I had try.

PHP code in the web for the download:

    $uri = $this->getEndpointShow($this->reportCode, SELF::ENDPOINT_REPORT_DOWNLOAD);
    $file = $this->apiConnection->downloadReport($uri, $this->reportCode);
    if ($file) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        flush();
        readfile($file);
    } else {
        echo "alert('Can´t find a report file')";
    }

And the downloadReport method:

public function downloadReport($uri, $reportCode)
{
    if (!$reportCode) {
        throw new InvalidArgumentException("No report Code");
    }
    $cURLConnection = curl_init();
    curl_setopt($cURLConnection, CURLOPT_URL, self::BASE_API_URL . $uri);
    curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($cURLConnection, CURLOPT_POST, TRUE);
    curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, "vRefGMS=$reportCode");
    curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . self::API_ACCESS_TOKEN
    ]);

    $response = curl_exec($cURLConnection);

    if ($response === false) {
        throw new Exception(curl_error($cURLConnection), curl_errno($cURLConnection));
    }

    curl_close($cURLConnection);

    return $response;
}

As you can see in the PHP code for the download I have a $file var which always comes blank $file = ''. I did also try on the api with return response()->download($csvFile) with the same result.

Is possible that I am missunderstanding concepts, but I cannot achieve the file download. How can get this file?



via Chebli Mohamed

Why my Post api run in postman but doesn't run in react-native app

enter image description here I'm try to update 1 item to my server. It work in Post man

enter image description here But in react-native app, it do not work!



via Chebli Mohamed

dimanche 23 février 2020

Laravel: having trouble installing laravel-ffmpeg package

I'm a JS developer doing some Laravel and I'm having trouble using a package. I am trying to use a ffmpeg wrapper ( https://github.com/pascalbaljetmedia/laravel-ffmpeg ) and I went through the instructions to install it via composer and added it to config/app.php in the aliases and providers section as details.

At the top of my Users file, I have use Pbmedia\LaravelFFMpeg\FFMpegFacade; below the others.

I am then using it my code as follows in a function:

public function createThumb($url, $product) 
{
        $media = FFMpeg::open($url);
        $thumb = $media->getFrameFromString('00:00:05.00');
        $originalWidth = $thumb->width();
        $originalHeight =$thumb->height();
        $filename = "test";
}

I keep getting an error Error: Class 'App\UserProfile\FFMpeg not found referencing the line where I call it. I'm not sure what I am missing to use this.



via Chebli Mohamed

Have Laravel 5.8 count data in other fields not just unsignedInteger

Hi I am new to Laravel,

I have two database tables (boxes and items) aka a hasMany() relationship. I am trying to get laravel to display 4 results of the boxbarcode column not 5 of the box_id as you see in the screenshot. Basically, all items that are of box TRTB0001

enter image description here

enter image description here

The problem is it is looking at the box_id (1,1,1,1,1) not the boxbarcode (TRTB0001). How can I adjust my Model, Controller, View to display this? See code below.

Box.php (Model)

namespace App;

use Illuminate\Database\Eloquent\Model;

class Box extends Model
{

    protected $guarded = [];


    public function items(){

        return $this->hasMany(Item::class);
    }

}

Item.php (Model)

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{

    public function company(){

        return $this->belongsTo(Company::class);
    }

}

boxesController.php (Controller)


namespace App\Http\Controllers;

use App\Box;
use Illuminate\Http\Request;

class boxesController extends Controller
{

    /**
     * Display the specified resource.
     *
     * @param  \App\Box  $box
     * @return \Illuminate\Http\Response
     */
    public function show(Box $box)
    {        
        return view('boxes.show', compact('box'));
    }


}

show.blade.php

@extends('layout')


@section('title', 'Show Box')  


@section('content')

<h1 class="title"></h1>

<p> <a href="/projects//edit">Edit Box</a></p>

<h3 class="content">Status: </h3>

<hr>

<h5 class="content">List of Box Items:</h5>

<!-- ONLY SHOW TASK <DIV> IF A TASK EXISTS -->
@if ($box->items->count())
    <div>
        @foreach ($box->items as $item)

            <div>

                <form method="POST" action="/items/">
                    @method('PATCH')
                    @csrf

                    <label class="checkbox " for="in" >

                    <input type="checkbox" name="in" onChange="this.form.submit()" >
                            

                    </label>

                </form>         

            </div>

        @endforeach

    </div>
@endif

@endsection



via Chebli Mohamed

i move my laravel application but it always redirected

i have laravel apps owned by my friend in my server and point to hxxps://mydomain.com/ then i download it to local but it alwasy redirected.

My friend said that it only redirect the apps with .htaccess, and then i remove that files.

every time i open the app it always pointed to hxxps://localhost/ (localhost with http) and i have no idea what happenned,

every config in .env config/app have been checked and no item that describe about that domain, all database item have been checked also.

when debugging the line code i got

C:\wamp64\www\bikinmall\project\vendor\symfony\http-foundation\ResponseHeaderBag.php
$headers = $this->allPreserveCase();

and the header one of value is ['location'] = https://localhost/

how come this variable come? where to find it?



via Chebli Mohamed

Larvel's Passport error with frontend.....Everything works great till I have to run the command npm run dev and then I get the following error

dev /var/www/html/MyProject

npm run development

@ development /var/www/html/MyProject cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

98% after emitting SizeLimitsPlugin

ERROR Failed to compile with 6 errors 2:10:21 AM

error in ./resources/js/components/passport/Clients.vue

Module Error (from ./node_modules/vue-loader/lib/index.js): [vue-loader] vue-template-compiler must be installed as a peer dependency, or a compatible compiler implementation must be passed via options.

@ ./resources/js/app.js 16:34-78 @ multi ./resources/js/app.js ./resources/sass/app.scss

error in ./resources/js/components/passport/AuthorizedClients.vue

Module Error (from ./node_modules/vue-loader/lib/index.js): [vue-loader] vue-template-compiler must be installed as a peer dependency, or a compatible compiler implementation must be passed via options.

@ ./resources/js/app.js 17:45-99 @ multi ./resources/js/app.js ./resources/sass/app.scss

error in ./resources/js/components/passport/PersonalAccessTokens.vue

Module Error (from ./node_modules/vue-loader/lib/index.js): [vue-loader] vue-template-compiler must be installed as a peer dependency, or a compatible compiler implementation must be passed via options.

@ ./resources/js/app.js 18:49-106 @ multi ./resources/js/app.js ./resources/sass/app.scss

error in ./resources/js/components/passport/Clients.vue

Module build failed (from ./node_modules/vue-loader/lib/index.js): TypeError: Cannot read property 'parseComponent' of undefined at parse (/var/www/html/MyProject/node_modules/@vue/component-compiler-utils/dist/parse.js:14:23) at Object.module.exports (/var/www/html/MyProject/node_modules/vue-loader/lib/index.js:67:22)

@ ./resources/js/app.js 16:34-78 @ multi ./resources/js/app.js ./resources/sass/app.scss

error in ./resources/js/components/passport/AuthorizedClients.vue

Module build failed (from ./node_modules/vue-loader/lib/index.js): TypeError: Cannot read property 'parseComponent' of undefined at parse (/var/www/html/MyProject/node_modules/@vue/component-compiler-utils/dist/parse.js:14:23) at Object.module.exports (/var/www/html/MyProject/node_modules/vue-loader/lib/index.js:67:22)

@ ./resources/js/app.js 17:45-99 @ multi ./resources/js/app.js ./resources/sass/app.scss

error in ./resources/js/components/passport/PersonalAccessTokens.vue

Module build failed (from ./node_modules/vue-loader/lib/index.js): TypeError: Cannot read property 'parseComponent' of undefined at parse (/var/www/html/MyProject/node_modules/@vue/component-compiler-utils/dist/parse.js:14:23) at Object.module.exports (/var/www/html/MyProject/node_modules/vue-loader/lib/index.js:67:22)

@ ./resources/js/app.js 18:49-106 @ multi ./resources/js/app.js ./resources/sass/app.scss

   Asset      Size   Chunks             Chunk Names

/css/app.css 177 KiB /js/app [emitted] /js/app /js/app.js 2.11 MiB /js/app [emitted] /js/app

ERROR in ./resources/js/components/passport/Clients.vue Module Error (from ./node_modules/vue-loader/lib/index.js): [vue-loader] vue-template-compiler must be installed as a peer dependency, or a compatible compiler implementation must be passed via options. @ ./resources/js/app.js 16:34-78 @ multi ./resources/js/app.js ./resources/sass/app.scss

ERROR in ./resources/js/components/passport/AuthorizedClients.vue Module Error (from ./node_modules/vue-loader/lib/index.js): [vue-loader] vue-template-compiler must be installed as a peer dependency, or a compatible compiler implementation must be passed via options. @ ./resources/js/app.js 17:45-99 @ multi ./resources/js/app.js ./resources/sass/app.scss

ERROR in ./resources/js/components/passport/PersonalAccessTokens.vue Module Error (from ./node_modules/vue-loader/lib/index.js): [vue-loader] vue-template-compiler must be installed as a peer dependency, or a compatible compiler implementation must be passed via options. @ ./resources/js/app.js 18:49-106 @ multi ./resources/js/app.js ./resources/sass/app.scss

ERROR in ./resources/js/components/passport/Clients.vue Module build failed (from ./node_modules/vue-loader/lib/index.js): TypeError: Cannot read property 'parseComponent' of undefined at parse (/var/www/html/MyProject/node_modules/@vue/component-compiler-utils/dist/parse.js:14:23) at Object.module.exports (/var/www/html/MyProject/node_modules/vue-loader/lib/index.js:67:22) @ ./resources/js/app.js 16:34-78 @ multi ./resources/js/app.js ./resources/sass/app.scss

ERROR in ./resources/js/components/passport/AuthorizedClients.vue Module build failed (from ./node_modules/vue-loader/lib/index.js): TypeError: Cannot read property 'parseComponent' of undefined at parse (/var/www/html/MyProject/node_modules/@vue/component-compiler-utils/dist/parse.js:14:23) at Object.module.exports (/var/www/html/MyProject/node_modules/vue-loader/lib/index.js:67:22) @ ./resources/js/app.js 17:45-99 @ multi ./resources/js/app.js ./resources/sass/app.scss

ERROR in ./resources/js/components/passport/PersonalAccessTokens.vue Module build failed (from ./node_modules/vue-loader/lib/index.js): TypeError: Cannot read property 'parseComponent' of undefined at parse (/var/www/html/MyProject/node_modules/@vue/component-compiler-utils/dist/parse.js:14:23) at Object.module.exports (/var/www/html/MyProject/node_modules/vue-loader/lib/index.js:67:22) @ ./resources/js/app.js 18:49-106 @ multi ./resources/js/app.js ./resources/sass/app.scss npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! @ development: cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the @ development script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: npm ERR! /home/zeshan/.npm/_logs/2020-02-23T21_10_21_973Z-debug.log npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! @ dev: npm run development npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the @ dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: npm ERR! /home/zeshan/.npm/_logs/2020-02-23T21_10_22_036Z-debug.log



via Chebli Mohamed