
LARAVEL DOC

# Open Bits Developer Convention
1. Name model in singular form - Page
2. Controller in plural form - Pages, then table "pages" also plural, always, all tables.
3. If Page has additional info, first use prefix page_ in the table, then what it is page_categories, so Controller will be PageCategoriesController, model PageCategory. 
4. Name relationship in this format - page_category_id -> PageCategory. Don't do specific names for relationship fields.
5. If website has multiple languages, all PUBLIC links must start with /{language_code}/*
6. Put favicon for the project, otherwise Chrome can break sessions.
7. Name Controller Functions same as Routes!, for example, route: pageQuery, function: pageQuery. First use word of the model(page), then what it is. If routes and controller functions are chaotic, very hard to navigate thorught the project.


  


# Check Schedules:
$ php artisan schedule:list
$ php artisan schedule:clear-cache

php artisan schedule:list

This command displays a list of all the scheduled tasks in your application, along with their schedule and status.

php artisan schedule:run

This command runs all the due scheduled tasks in your application. This command should be run on a regular basis, typically using a cron job, to ensure that scheduled tasks are executed at their scheduled times.

php artisan schedule:work

This command starts a long-running process that continuously monitors the schedule and runs the due scheduled tasks as they become due. This command is useful for environments where you need to run scheduled tasks continuously, such as on a dedicated task runner server.

php artisan schedule:finish

This command is used to release any currently held mutex locks related to scheduled tasks. This command is useful if a scheduled task has become stuck or if you need to release a lock manually for some reason.

php artisan schedule:clear

This command clears all the scheduled tasks from the application's schedule. This command is useful if you need to start over with a fresh schedule.

php artisan event:cache

This command caches all the event listeners and subscribers in your application. This command is useful for optimizing the performance of event handling in your application.

php artisan event:clear

This command clears the cached event listeners and subscribers in your application. This command is useful if you need to clear the cache for some reason.

## SERVERIAI.LT CONFIGURATION > “public” => “public_html”
Change /public dir to /public_html for serveriai.lt:
Change in /app/Providers/AppServiceProvider.php:
    public function register()
    {
        $this->app->bind('path.public', function() {
          return base_path().'/public_html';
        });
    }

## Chmod on Shared Hosting
files: 644
Dirs: 755

## Turn off cache on local environment:
To turn off Laravel cache for a local environment, you can follow these steps:

Open the .env file in the root directory of your Laravel project.
Find the CACHE_DRIVER variable and set its value to array. This will disable caching in Laravel.
Save the .env file.
Alternatively, you can set the CACHE_DRIVER variable to null in your local environment to disable caching.

Note that disabling caching in a local environment may slow down the performance of your application, but it can be useful for development purposes, as it allows you to see changes immediately without having to clear the cache every time.

## MAX CONFIG RESET CACHE CLEAR!!!!
https://www.codegrepper.com/code-examples/php/laravel+commands+to+refresh+env+file

## CORS on NGINX:
https://docs.viblast.com/player/cors/cors-on-nginx
hack to rewrite POST headers:
https://stackoverflow.com/questions/24415376/post-request-not-allowed-405-not-allowed-nginx-even-with-headers-included


CRUD generator
https://github.com/appzcoder/crud-generator/blob/master/doc/usage.md

test?
php artisan crud:generate Categories --fields='name#string; oems#text; position#integer' --view-path=cms --route-group=cms --form-helper=html

php artisan crud:generate Texts --fields='name#string; slug#string; text#text; position#integer; active#integer' --view-path=cms --controller-namespace=Cms --route-group=cms --form-helper=html --model-namespace=Cms --model-name=Text

php artisan crud:generate Surcharges --fields='sum_from#integer; sum_to#integer; percents#integer' --view-path=cms --controller-namespace=Cms --route-group=cms --form-helper=html

php artisan crud:generate Materials --fields='fact_id#integer; user_id#integer; filename#string; type#string; size#integer; status#integer; position#integer; main#integer; comment#text; url#text' --view-path=cms --controller-namespace=Cms --route-group=cms --form-helper=html

php artisan crud:generate FactTypes --fields='name#integer; status#integer; position#integer;' --view-path=cms --controller-namespace=Cms --route-group=cms --form-helper=html

php artisan crud:generate Comments --fields='user_id#integer; comment_id#integer; fact_id#integer; comment#text; active#integer;' --view-path=cms --controller-namespace=Cms --route-group=cms --form-helper=html



Including this packages when starting fresh Laravel 7 Installation
composer require laravelcollective/html
composer require cviebrock/eloquent-sluggable
composer require barryvdh/laravel-dompdf
composer require intervention/image
composer require barryvdh/laravel-debugbar --dev

Remove standard Laravel 7 app.js for all projects and replace with bootstrap
This will make work drop-downs and logout if needed. I’m not using any more app.js functions…

Remove from app.blade.php, add this:
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
   <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>



Check Laravel Version
 -> Application.php
OR
php artisan --version
Laravel Framework 7.11.0

Chache not writtable:
php artisan cache:clear

On Errors

SQLSTATE[42000]: Syntax error or access violation: 1231 Variable 'sql_mode' can't be set to the value of 'NO_AUTO_CREATE_USER'
Adding mysql modes to config/database.php

Older


Creating CRUD
https://github.com/CrestApps/laravel-code-generator
php artisan create:scaffold [model-name]

Check menu is active
class="{{ Request::is('puslapis/kontaktai') ? 'active' : ''}}"

Redirect all www requests to non-www (used for shared hostings)
https://gist.github.com/reliq/7a5f506427eeaba6faa47ef3551f0bde
(Beautyfully works for romantic.lt)

Logout
https://stackoverflow.com/questions/43585416/how-to-logout-and-redirect-to-login-page-using-laravel-5-4


Redirect all HTTP requests to HTTPS:
https://stackoverflow.com/questions/28402726/laravel-5-redirect-to-https
(first big answer with middleware and integration to Kernel. Works good in romantic.lt)

Setup for production:
sudo chown -R www-data:www-data /var/www/AppName/
sudo chmod -R 755 /var/www/AppName/bootstrap/cache
sudo chmod -R 755 /var/www/AppName/storage

Generate migrations for existing table
https://github.com/Xethron/migrations-generator 
Generate for all tables:
$ php artisan help migrate:generate 

For one table:
$ php artisan migrate:generate table1,table2

Generate Seeder
$ php artisan make:seeder PhotosTableSeeder

Seed Seeder
$ php artisan db:seed --class=PhotosTableSeeder


Get table structure:
$s = \DB::connection('dm_hes')->getSchemaBuilder()->getColumnListing("credit");

Disable crfs cookie for some URLS:
Add to file Http/Middleware/VerifyCsrfToken.php
protected $except = [  'api/*' ];

On count issue, put on the route:
if (version_compare(PHP_VERSION, '7.2.0', '>=')) {
    // Ignores notices and reports all other kinds... and warnings
    error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
    // error_reporting(E_ALL ^ E_WARNING); // Maybe this is enough
}


Set all permissions, chmods for production, for laravel dir:
https://stackoverflow.com/questions/30639174/file-permissions-for-laravel-5-and-others 

To lock all actions access only with Auth, but except few:
    public function __construct()
    {
        $this->middleware('auth')->except('c', ‘another_action’);
    }


Write helper or CALL ANY OPTION FROM DATABASE TO CACHE
https://stackoverflow.com/questions/47728940/how-to-set-global-variables-from-database-in-laravel-5-4/47789365#47789365 
Create helper with simple php functions.
Add to composer.json, 
"autoload": {
"files": [
            "app/Http/helpers.php"
        ],

Set my local MAC to php 7.2:
export PATH=/usr/local/php5/bin:$PATH

Create new laravel 5.5 app:
$ php composer.phar create-project --prefer-dist laravel/laravel twitter
$ php artisan key:generate

Install Specific Laravel version
composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist




Protect actions in controller for unauntentificated users:
    public function __construct() {
        $this->middleware('auth', ['except' => ['index', 'show', 'megstamiausi', 'remember', 'unremember']]);
        parent::__construct();
    }


Select box from database with null value:
{{ Form::select('parent_id', [null=>''] + \App\CmsCategory::whereRaw('parent_id<1')->pluck('name', 'id')->toArray()) }}

If Eleoquent relations doesn’t work
public function files() {
return $this->hasMany('\App\PanUpload')->where('type', 'file');
}

If Laravel forces existing value in dabatase for field, do simple html:
<input name="street_id" type="hidden" value="0">

Model without table, write in ModelName.php:
public $useTable = false;

Select box from table:
<?php
$ad_types = \App\AdType::where('status', 1)->pluck('name', 'id')->toArray();
?>
{!! Form::select('ad_type_id', [0=>'Visi'] + $ad_types, Request::input('ad_type_id'), ['class' => 'form-control ntselect', 'style'=>'width:100%;']) !!}


Set timezone:
/config/app.php =>   'timezone' => 'Europe/Vilnius',

If error on “php artisan migrate”, searching for information.tables…
    Change DB_HOST=localhost > DB_HOST=127.0.0.1

Correct use of checkboxes:
    <div class="form-group">
      {!! Form::hidden('weight_field', 0) !!}
      {!! Form::checkbox('limit_field', 1) !!}
      {!! Form::label('limit_field', $t["Limit"]) !!}
    </div>
    CSS for bootstrapped design:
    input[type=checkbox] {
margin-right:5px;
float:left;
}
label {
clear: none;
}


Redirect with anchor:
return Redirect::to(URL::previous() . "#whatever");


And remember to import it at the top:
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;

Do in html:
<a name="whatever"></a>

Permanent redirect
    Route::get('/home', function(){ return Redirect::to('/mano_anketa', 301); });

Production
    Chmod
    /storage recursively 755 for folders
    
Check for local environment rails
    if (\App::environment('local')) {

Standart laravel helper for slug:
str_slug('Make a Slug') 

SESSION
Forget session key:
forget('key');

Set value for session array:
Session::put("items.{$key}.quantity",$new_quant);

COOKIES:
Check array value exist:
    @if (Cookie::get("isiminti") and !empty(Cookie::get("isiminti")[$ad->id]))
    
    Add value to an array:
    Cookie::queue('isiminti['.$id.']',1, 9999);

    Delete from an array:
     Cookie::queue(
               Cookie::forget('isiminti['.$id.']')
           );

    Get results from db:
    $ids = Cookie::get("isiminti");
        $id_keys = array();
        foreach ($ids as $key=>$value) {
            $id_keys[] = $key;
        }
        $ads = \App\Ad::whereIn('id', $id_keys)->paginate(15);

Slug:
use Cviebrock\EloquentSluggable\Sluggable;

class Ad extends Eloquent {
    use Sluggable;

    public function sluggable() {
        return [
            'url' => [
                'source' => 'public_comment',
                'maxLength' => 100,
                'onUpdate'=>true,
                'unique'          => true
            ]
        ];
    }

Methods after save, after update:
class BaseModel extends Model {
    public static function boot() {
        static::creating(function ($model) {
            // blah blah
        });
        static::updating(function ($model) {
            // bleh bleh
        });
        static::deleting(function ($model) {
            // bluh bluh
        });
        parent::boot();
    }
}

Create link in url for ordering:
@if (Input::get('sort')!='valid_to_asc')
    <a href="{{ Request::fullUrlWithQuery(['sort' => 'valid_to_asc']) }}">Galioja&uarr;</a>
@else 
    <a href="{{ Request::fullUrlWithQuery(['sort' => 'valid_to_desc']) }}">Galioja&darr;</a>
@endif

Ordering by relationship:
$ads->join('users as users', 'ads.user_id', '=', 'users.id')->orderBy('users.name', 'asc');

Delete item without form, when resources is ON:
<a href="{{url('/ads/'.$ad->id)}}" data-method="delete" data-token="{{csrf_token()}}" data-confirm="Are you sure?">Trint</a>

Zip:
Integrate: https://github.com/Chumper/Zipper
foreach ($photos as $photo) {
    $photo_a[] = public_path('nuotraukos/wide.'.$photo->filename);
}
var_dump(Zipper::make(public_path('zips/'.$id.'.zip'))->add($photo_a)->close());

Pagination:
->paginate(15); instead of ->get();
To pass get params: 
{!! $records->appends(Input::except('page'))->links() !!}
https://stackoverflow.com/questions/17159273/laravel-pagination-links-not-including-other-get-parameters
To include Input:
'Input' => Illuminate\Support\Facades\Input::class,
https://stackoverflow.com/questions/31696679/laravel-5-class-input-not-found 

Show only date from created_at:
{{$ad->valid_to->format('Y-m-d')}}

Save new record:
$item = new \App\Item;
$item->name = ‘labas’;
$item->save();

Model::find($id);
If no result: $id is empty
If result: $id is !empty

Add a lot of records to DB:
$i=1950;
while($i<=2017) {
    \App\PanelFieldField::firstOrCreate(array('field_group_id'=>28, 'name'=>$i));
    $i=$i+1;
}

ROUTES / URLS
    RECEIVE VARIABLE FROM URL GET, get METHOD:
    Input::get('var');
    Request::get(‘var’);

    
    FULL URL
    url()->full()

ACCESS ROUTES PARAMS IN VIEWS:
Request::url() - url without passed params
Request::getPathInfo() - gives url, without passed params, without domain and app path (gives: /skelbimai)

Get Action
explode('@', Route::getCurrentRoute()->getActionName())[1]

PASS ADDITIONAL PARAMS FROM ROUTE TO CONTROLLER:
Route: Route::get('/', ['uses'=>'CategoriesController@show', 'homepage'=>1]);
Receive variable: Request::route()->getAction()['homepage']
Blade condition: @if ( !empty(Request::route()->getAction()['homepage']) )
    
    
    PASS PARAM FROM URL
    Route::get('/dviraciai/{url}', 'BikesController@index');
    $request->url

    PASS ROUTE PARAMS
    Route::get('/show_bill/{hash_code}', 'BillsController@show_bill');
public function show_bill ($hash_code) {}

Blade comments:
{{-- of course, you can have single line comments too --}}


MYSQL raw where query:
whereRaw(‘`anything`=1’)

Check session exsist
if (Session::has('items')) {

Add value to a session
Session::push (ads new)
Session::put (updates)

Create a Form:
{!! Form::open(['url' => 'foo/bar', 'method' => 'put']) !!}
{!! Form::close() !!}

Session array
Session::put('items.'.$id, 2);
Session::get('items');

Order when empty fields goes to the end
orderByRaw('case when position is null then 1 else 0 end, position')->get();



GLOBAL VARIABLES WITH AUTH:
// app/Http/Controllers/Controller.php
// add `parent::__construct(); at the end of every __contruct function in other controllers
// add `use Auth;` after `namespace App\Http\Controllers;`
class Controller extends BaseController {
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    public function __construct(){
        $this->middleware(function ($request, $next) {
        Config::set('rights', \App\RightValue::all() );
        // to get use: Config::get('rights');
        
return $next($request);
        });
        }
}

Make function for views(helper):
https://laracasts.com/discuss/channels/laravel/calling-a-function-from-a-view

Select box:
echo Form::select('size', ['L' => 'Large', 'S' => 'Small'], 'S');

Checkbox:
echo Form::checkbox('name', 'value', true);


Order all things as numbers, raw OrderBy:
->orderByRaw('cast(name as unsigned) asc')

SET GLOBAL VARIABLES FOR ALL VIEWS AND CONTROLLERS (no Auth)
// add in your app/Providers/AppServiceProvider.php
class AppServiceProvider extends ServiceProvider { 
public function boot() { 
// Using view composer to set following variables globally 
view()->composer('*',function($view) { 
$view->with('user', Auth::user()); 
$view->with('social', Social::all()); 
}); 
} 
}
My answer on stackoverflow:
http://stackoverflow.com/questions/25189427/global-variable-for-all-controller-and-views/43222182#43222182


SETUP: CREATE LARAVEL APP

Install project with specific laravel version
$ composer create-project laravel/laravel ProjectName 5.0
$ cd ProjectName
$ composer install
$ composer update

NEW LARAVEL APP:
composer create-project --prefer-dist laravel/laravel blog
> https://laravel.com/docs/5.4/installation 

App name of Laravel:
It is best to leave App name in laravel configs, because you need less effort when copy/paste code from another controller. And I don’t know good sides of unique name yet.
$ php artisan app:name App

SERVER WRITABLE DIRS:
After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.

GET LARAVEL VERSION
$ php artisan --version

START INTEGRATED LARAVEL SERVER IF PHP IS INSTALLED
php artisan serve




SEARCH BY MULTIPLE IDS:
$ids = \App\Category::where('status’, 1)->pluck('id')->toArray();
$photos = \App\AdPhoto::whereIn('id', $ids)->get();
->whereNotIn('book_price', [100,200])->get();

By several where:
$items = \App\Item::whereIn('category_id', $sub_categories)->where('status', 1)->orderBy('position','DESC')->get();

Debugbar turn of for admin on production

In /config/app.php:
'debug' => env('APP_DEBUG', ($_SERVER['REMOTE_ADDR'] == '212.52.39.124' or $_SERVER['REMOTE_ADDR'] == '212.52.39.1111') ? true : false),

In /config/debugbar.php:
'enabled' => null,

In /.env:
Remove line “APP_DEBUG=false”

DEBUG

DEBUG TO LOG FILE:
# Add line in controller, before class: 
use Log;
# And debug:
Log::info('hi');


DEBUG IN MODEL TO ECHO:
1. Remove return line in controller action, 2. Use simply echo in model.

DEBUG LINE IN EXPLORER:
var_dump($sql);


GET VARIABLE FROM URL IN VIEW
Request::get('a')

ADD EMPTY VALUE TO SELECT INPUT:
{!! Form::select('user_id', [null=>'Nepasirinkta'] + $users, $ad->user_id, ['class' => 'form-control']) !!}

CALL MODEL METHOD IN CONTROLLER
Controller:
\App\Ad::saveMultiFields($input, $id);

For create in controller:
$ad = \App\Ad::create($input);
$id = $ad->id;
// Call model method for saving multiple fields
\App\Ad::saveMultiFields($input, $id);

Model:
use Illuminate\Database\Eloquent\Model as Eloquent;
class Ad extends Eloquent {
    public static function saveMultiFields($input, $id) {
        Debugbar::info('Saved Multiple Fields:');
        Debugbar::info($input);

        return true;
    }
}

SELECT INPUT WITH DATA FROM TABLE

    <div class="form-group">
        {!! Form::Label('city_id', 'Miestas') !!}
        <?php 
        $cities = DB::table('cities')->orderBy('name')->pluck('name', 'id')->all();
        ?>
        {!! Form::select('city_id', $cities, $ad->city_id, ['class' => 'form-control']) !!}
    </div>

FIRST OR CREATE
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

CSRF TOKEN AJAX
<metaname="csrf-token"content="{{csrf_token()}}">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

EMAIL

Email debuging:
https://github.com/laravelflare/mail-debug
.env: MAIL_DRIVER=debug

Pass multiple params to Mail function
Mail::send('emails.zinute_agentui', ['request' => $request], function ($m) use ($request, $agent) {

Comment pusher, because it gives error on lower than php7 version:
/config/pusher.php:
//declare(strict_types=1);

COMPOSER

How to install composer to development?
https://getcomposer.org/download/ download composer.phar
Put it in a /web folder for all project. When need to some project, just move it to some project and use in this way:
(use full path everytime)
/web/lnt.lt/composer.phar update

Installing new package:
/web/lnt.lt/composer.phar require "laravelflare/mail-debug"

Composer updates things by composer.json file:
    $ composer update

FILES MANAGEMENT

pathinfo($path):
array:4 [
  "dirname" => "uploads"
  "basename" => "a846679094c6dcb01cb1fd924f7e4b2d.jpeg"
  "extension" => "jpeg"
  "filename" => "a846679094c6dcb01cb1fd924f7e4b2d"
]

CHECK LARAVEL VERSION
php artisan --version

MIDDLEWARE
Midleware helps to identify user right before action:
“1 Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {
2     //
3 }]);”

SCAFFOLD

Scaffold Interface
http://amranidev.github.io/blog/site/scaffold-interface/

In controller:
$items = Items::pluck('name', 'id');
return view('your view', compact('items', $items));

In view:
{!! Form::select('items', $items, null, ) !!}


Create Table with command line
$ php artisan make:migration create_links_table --create=links

Example of some more fields in migration:
>> database/migrations/{{datetime}}_create_links_table.php
Schema::create('links', function (Blueprint $table) {
     $table->increments('id');
     $table->string('title');
     $table->string('url’)->unique();
     $table->text('description');
     $table->timestamps();
});

Create seeder file:
$ php artisan make:seeder LinksTableSeeder

Create Model:
$ php artisan make:model Link

Migrate:
$ php artisan migrate

CONTROLLER 

Create Plain Controller:
$ php artisan make:controller NameofController

Create Controller with Resources actions:
$ php artisan make:controller NameofController --resource


Laravel, MAMP/HOMESTEAD Installation

A) Install Mamp on MAC
https://www.mamp.info/en/downloads/

B) IF Install Laravel Homestead
It controls separated Ubuntu server on Vagrant in my Mac to configure everything as in separated Virtual Machine.
https://medium.com/@kunalnagar/install-laravel-5-on-os-x-23f3578386f1#.q65lp5twb 

Install Composer
https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx 

Use MAMP php version on my Mac local command line (before installing Laravel):
$ nano .bash_profile

Add on the first line:
export PATH=/Applications/MAMP/bin/php/php7.1.0/bin:$PATH

Save, exit and:
$ source .bash_profile or $ source ~/.bash_profile

Check which version is now:
$ which php

Remeber, that Laravel will quit working if installed on another, local PHP

Install Laravel correctly
https://medium.com/@kunalnagar/install-laravel-5-on-os-x-23f3578386f1#.5ohohu6ib 

PATH to “laravel command work”
http://stackoverflow.com/questions/32504748/installing-laravel-5-1-on-osx-with-mamp







