1. Database Update
composer require doctrine/dbal

php artisan make:migration add_paid_to_users

1
2
3
4

public function up()
{
    Schema::table('users', function($table) {
        $table->integer('paid');
    });
}

public function down()
{
    Schema::table('users', function($table) {
        $table->dropColumn('paid');
    });
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

use $table->integer('paid')->after('whichever_column'); to add this field after specific column.

  1. Laravel can set database engine

You have to set engine to InnoDB if there is anything other you can change in database.php

  1. Laravel Passport Token Generation
POST http://127.0.0.1:8000/oauth/token
Cache-Control: no-cache
Content-Type: application/json
X-Requested-With: XMLHttpRequest

{  "grant_type": "password",
   "client_id": 2,
   "client_secret": "NJqnjOkFr6NUqQ0sBoHYWWxoPZ1S2tOdAgv7CU1p",
   "scope": "",
   "username": "[email protected]",
   "password": "password"
   }

1
2
3
4
5
6
7
8
9
10
11
12
13
  1. Use of isset()

always use if(isset($variable)) instead if($variable) of checking if variable have value or not

  1. Select Row with Column Unique values
$lottery_entry = Lottery::where('event_id', $event_id)->get();
$unique = $lottery_entry->unique('user_id');
dd($unique->values()->all());
1
2
3
  1. Configuring vuetify for standalone use in laravel

A) Install necessary package

npm install
1

B) Component Creation

Create Component inside resource>assets>js>components with extension .vue

Basic code for component is :

<template>
<div><p>{{ greeting }} World!</p></div>
</template>

<script>
    // import OtherComponent from './OtherComponent.vue'

    export default {
        components: {
            // OtherComponent
        },
        data () {
            return {
                greeting: 'Hello'
            }
        }
    }
</script>

<style  scoped>
    
</style>


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

d) Register Component

add component in resource>assets>js>app.js as follows

Vue.component('report',require('./components/report/FullReport.vue'))
1

e) add #app id and js in the page where you want to use vue

<script src="{{ asset('js/app.js') }}"></script>
1

f) Call component

<componentname></componentname>
1
  1. referring data from axios call

In option functions like data and created, vue binds this to the view-model instance for us, so we can use this.contas, but in the function inside then, this is not bound.

So you need to preserve the view-model like (created means the component's data structure is assembled, which is enough here, mounted will delay the operation more):

created() {
    var self = this;
    axios.get('http://127.0.0.1/api/bills')
        .then(function (response) {
                self.contas = response.data;
                });
}

1
2
3
4
5
6
7
8

Or you can use arrow function in ES6 standard if you only aim to support modern browsers(or using a transpiler like babel), like:

created() {
    axios.get('http://127.0.0.1/api/bills')
        .then((response) => {
                this.contas = response.data;
                });
}
1
2
3
4
5
6

this inside arrow functions are bound according to lexical context, which means the this in the above snippet is the same as the one in created, which is what we want.

  1. Passing data to component through props
<template>
  <p>{{ name }}</p>
</template>

<script>
export default {
  props: {
  firstName: {
    type: String,
    required: true
  }
}
}
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<ComponentName firstName="white" />
1
  1. From an array of objects, extract value of a property as array
let result = objArray.map(a => a.foo);
1
  1. Display length of varaible in tempalte vue
 {{ smsMessage && smsMessage.length ? smsMessage.length : 0 }}
1
  1. Concate Array in js
 [].concat.apply([], array);

 //for js
 data.join()
1
2
3
4
  1. Find object by id in an array of JavaScript objects
myArray.find(x => x.id === '45').foo;
1
  1. How can I make Laravel return a custom error for a JSON REST API

I'm developing some kind of RESTful API. When some error occurs, I throw an App::abort($code, $message) error.

go to your app/start/global.php

This will convert all errors for 401 and 404 to a custom json error instead of the Whoops stacktrace. Add this:

App::error(function(Exception $exception, $code)
{
    Log::error($exception);

    $message = $exception->getMessage();

    // switch statements provided in case you need to add
    // additional logic for specific error code.
    switch ($code) {
        case 401:
            return Response::json(array(
                    'code'      =>  401,
                    'message'   =>  $message
                ), 401);
        case 404:
            $message            = (!$message ? $message = 'the requested resource was not found' : $message);
            return Response::json(array(
                    'code'      =>  404,
                    'message'   =>  $message
                ), 404);        
    }

});

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

This is one of many options to handle this errors.

Making an API it is best to create your own helper like Responser::error(400, 'damn') that extends the Response class.

Somewhat like:

public static function error($code = 400, $message = null)
{
    // check if $message is object and transforms it into an array
    if (is_object($message)) { $message = $message->toArray(); }

    switch ($code) {
        default:
            $code_message = 'error_occured';
            break;
    }

    $data = array(
            'code'      => $code,
            'message'   => $code_message,
            'data'      => $message
        );

    // return an error
    return Response::json($data, $code);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  1. Error log in console
        error_log($event);
1
  1. Fetch array of value from collection
            $value = $collection->pluck('user_id');
1
  1. Difference between array and collection

The Collection provides a convenient wrapper for working with arrays.

Collection is the class for php array , they are what PHP arrays should be, but better.

They provide feature like :

  1. ArrayAccess - Interface to provide accessing objects as arrays.

  2. IteratorAggregate - Interface to create an external Iterator.

  3. JsonSerializable

  4. Fetch Multiple row with array

 $collaborator_list = collect([1,2])
 $total_user = User::whereId($collaborator_list)->get();
 error_log($total_user);

1
2
3
4
  1. Creating Resource for api response
php artisan make:resource UserResource
1
 public function toArray($request)
    {
      return [
        'id' => $this->id,
      ];
    }
1
2
3
4
5
6
  1. how can i access my laravel app from another pc?
php artisan serve --host 0.0.0.0 

1
2
  1. array_keys() Function

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys.

  1. laravel migration Data types :

do't forget to set default 0 for boolean value - Boolen : you can use tinyInteger or boolean . tinyInteger store 0 or 1 while boolen store true or false - Auto increment : you can use bigIncrements - Number with large value : bigInteger - title : text or string - date and time : timestamp - latitude and longitude : float - name : string with length 100 - email : string with length 100 - Number with small value : integer - description : string with length 200 - image path : string - password : string - message : string - payload , expection : longText - money : float

  1. Establishing Foreign relationship
$table->bigInteger('option_id')->unsigned();
$table->foreign('option_id')->references('id')->on('options')->onDelete('cascade');
1
2
  1. General API call format
GET http://127.0.0.1:8000/api/events/24/questions
Cache-Control: no-cache
Content-Type: application/json
X-Requested-With: XMLHttpRequest
Authorization: Bearer eyJ0eXAiOiJKV1Qi

1
2
3
4
5
6
  1. How to implement a self referencing (parent_id) model in Eloquent Orm
class User extends Eloquent {

    protected $table = 'users';
    public $timestamps = false;

    public function parent()
    {
        return $this->belongsTo('User', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('User', 'parent_id');
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16