-
-
Save gausoft/615d1060b3207d5ea7105befe9212953 to your computer and use it in GitHub Desktop.
Laravel base workflow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE AN APP | |
1.a | |
laravel new APPNAME | |
1.b: or: | |
composer create-project laravel/laravel APPNAME | |
cmd: | |
cd name-of-your-project | |
php artisan -v | |
(it gives you laravel version) | |
node -v | |
npm -v | |
php -v | |
laravel -v | |
(they give version infos) | |
How do I know which laravel version I use? | |
https://stackoverflow.com/questions/44637811/how-to-know-laravel-version-and-where-is-it-defined | |
Start GIT: | |
git init | |
// | |
git add . | |
or | |
git add -A | |
or | |
git add --all | |
git commit -m ("make a commit") | |
Go to github.com AND make a repo there. Important. | |
(Don't do a readme yet) | |
…or push an existing repository from the command line: | |
cmd: | |
git remote add origin https://github.com/user/repo.git | |
or if you want to share/upload a gist: | |
git remote add origin https://gist.github.com/Bazsmagister/manynumbers | |
git push -u origin master | |
(if git error - Fatal: remote origin already exists:) | |
git remote remove origin | |
live example: | |
a: | |
git remote add origin https://github.com/Bazsmagister/Kindergarten.git | |
git push -u origin master | |
b: | |
git remote add origin https://github.com/Bazsmagister/5.7_with_telescope.git | |
git push -u origin master | |
(The -u tells Git to remember the parameters, so that next time we can simply run git push and Git will know what to do.) | |
Backwards : git pull origin master | |
USING GIT IN DAILY WORKFLOW | |
git add * | |
or if you are in your app directory | |
git add . | |
git commit -m "Commit message" | |
git push | |
NICE gitlog | |
git log --graph --oneline --decorate --all | |
Laravel uses the utf8mb4 character set by default, which includes support for storing "emojis" in the database. | |
If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. | |
You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider: | |
Copy into App/Providers/AppServiceProvider: | |
use Illuminate\Support\Facades\Schema; | |
public function boot() | |
{ | |
Schema::defaultStringLength(191); | |
} | |
MYSQL | |
CREATE DATABAE databasename; | |
USE databasename; | |
show tables; (empty yet) | |
In .env file set up DB name and password . Save it! | |
Not so important | |
app/conf database.php overwrite. | |
//'charset' => 'utf8mb4', | |
//'collation' => 'utf8mb4_unicode_ci', | |
'charset' => 'utf8', | |
'collation' => 'utf8_unicode_ci', | |
2. Laravel telescope: | |
https://laravel.com/docs/5.7/telescope | |
If you plan to only use Telescope to assist your local development. You may install Telescope using the --dev flag: | |
composer require laravel/telescope --dev | |
or this one: | |
composer require laravel/telescope | |
php artisan telescope:install | |
//it creates a TelescopeServiceProvider and | |
//it puts App\Providers\TelescopeServiceProvider::class, in app.php | |
php artisan migrate | |
php artisan serve | |
CLick on the URL and add /telescope | |
When updating Telescope, you should re-publish Telescope's assets: | |
php artisan telescope:publish | |
Done. | |
5. Make model : | |
php artisan help make:model | |
php artisan make:model -a Product | |
(It makes: factory, migration és resource too. -a means all.) | |
(Model created successfully. | |
Factory created successfully. | |
Created Migration: 2020_03_01_100234_create_students_table | |
Seeder created successfully. | |
Controller created successfully.) | |
php artisan make:model -a Destination | |
(Model created successfully. | |
Factory created successfully. | |
Created Migration: 2018_02_17_120444_create_destinations_table | |
Controller created successfully.) | |
(vagy: | |
php artisan make:model --factory Model (it makes factory) | |
pl: | |
php artisan make:model --factory Link | |
php artisan make:model -m SingularCapitalized | |
(it creates Model and Migration). | |
php artisan make:model -cfm Destination (it makes controller, factory, migration)) | |
--all -a Generate a migration, factory, and resource controller for the model. | |
--controller -c Create a new controller for the model. | |
--factory -f Create a new factory for the model. | |
--force Create the class even if the model already exists. | |
--migration -m Create a new migration file for the model. | |
--pivot -p Indicates if the generated model should be a custom intermediate table model. | |
--resource -r Indicates if the generated controller should be a resource controller. | |
//doc | |
php artisan make:controller PhotoController --resource | |
Next, you may register a resourceful route to the controller: | |
in web.php | |
Route::resource('photos', 'PhotoController'); | |
## Partial Resource Routes | |
When declaring a resource route, you may specify a subset of actions the controller should handle instead of the full set of default actions | |
Route::resource('photos', 'PhotoController')->only([ | |
'index', 'show' | |
]); | |
Route::resource('photos', 'PhotoController')->except([ | |
'create', 'store', 'update', 'destroy' | |
]); | |
Migration file: | |
/database/migrations there will be the plural lowercase tablename | |
Moidify it as your own needsn | |
php artisan migrate; | |
(Important, that the database need to be empty.) | |
(Before it you should repair AppServiceProvider if needed) | |
Table is created in database. | |
In Models if you don't want to use timestamps: | |
public $timestamps = false; | |
Make Controller: | |
this works not well: | |
//php artisan make:controller -mr Modellname ModellnameController | |
it makes Model and Controller also. | |
it is better: | |
php artisan make:controller -rm Destination DestinationController | |
(ez megcsinálja az összes crud metódust is. és hozzáadja a model classt a Controllerhez. | |
It makes all the CRUD methods and gives the Model class and the Controlller class also. | |
php artisan make:controller -m Address AddressController | |
kontroller mögé -r adva megcsinálja a restful metódusokat is. | |
Adding -r after the Controller it makes the resful methods also. | |
Route::resource('students', 'StudentsController'); | |
Route::resource('addresses', 'AddressController'); | |
Making factory: | |
php artisan make:factory AddressFactory | |
php artisan make:factory StudentFactory | |
FAKER MAKING: | |
https://github.com/fzaninotto/Faker/blob/master/src/Faker/Provider/hu_HU/Address.php | |
USING faker in other language f.e (hungarian) : | |
In Config/app.php Faker Locale | |
'faker_locale' => 'hu_HU', | |
Faker timestamps: | |
https://github.com/fzaninotto/Faker#fakerproviderdatetime | |
'created_at'=> $faker->dateTimeBetween($startDate = '-5 years', $endDate = '-3 years', $timezone = null), | |
'updated_at'=> $faker->dateTimeBetween($startDate = '-2 years', $endDate = 'now', $timezone = null), | |
'customer_id' => $faker->unique()->randomElement($array = array ('1','2','3','4','5','6','7','8','9','10'), $count = 1), | |
THEN IN | |
Database/Factories/ UserFactory : | |
$factory->define(App\Wordchain::class, function (Faker $faker) { | |
return [ | |
'words' => $faker->name, | |
'wordsstringben' => str_random(10), | |
'updated_at'=> $faker->NOW(), | |
]; | |
SEEDER MAKING | |
php artisan make:seeder StudentTableSeeder | |
php artisan make:seeder ProductTableSeeder | |
php artisan make:seeder Destination_ProductTableSeeder | |
php artisan make:seeder UsersTableSeeder | |
INTO THE run method or | |
in | |
php artisan tinker: | |
factory(App\Student::class, 10)->create(); | |
factory(App\User::class, 20)->create(); | |
\App\User::create(["name" =>"admin", "email" => "[email protected]", "password" => bcrypt("password")]); | |
\App\User::create(["name" =>"admin2", "email" => "[email protected]", "password" => bcrypt("password2")]); | |
in tinker also: | |
//this way we don't have to use App\User::create(....) | |
namespace = App; | |
$user3 = User::create(['name' => 'user3', 'email' => '[email protected]', 'password' => bcrypt('password3')]); | |
php artisan make:seeder AddressTableSeeder | |
ebbe a run metódusba: | |
factory(App\Address::class, 10)->create(); | |
IMPORTANT: | |
use App\Product; | |
use App\ANYModel | |
Database\seed\Databaseseeder run method : | |
$this->call([ | |
UsersTableSeeder::class, | |
AddressTableSeeder::class, | |
StudentTableSeeder::class, | |
]); | |
Once you have written your seeder, you may need to regenerate Composer's autoloader using the dump-autoload command: | |
composer dump-autoload | |
Make pivot to many to many | |
This is how I create pivot tables in Laravel 5 with foreign key constraints: | |
//php artisan make:migration create_player_team_table --table=player_team | |
//php artisan make:migration create_destination_product_table --table=destination_product | |
//php artisan make:migration create_destination_product_pivot_table --table=destination_product | |
good ones: | |
php artisan make:migration create_destination_product_pivot_table --create=destination_product | |
php artisan make:migration create_hero_spell_pivot_table --create=hero_spell | |
So it will be good the migration file inside. | |
Pivot table making: | |
php artisan make:migration --create address_student create_address_student_pivot_table | |
php artisan make:migration --create destination_product create_destination_product_pivot_table | |
php artisan make:migration --create bicycle_user create_bicycle_user_pivot_table | |
Note: in case you have timestamps on the pivot table you must set withTimestamps on the relationship of both ends like this: | |
return $this->belongsToMany(\Mega\Modules\Account\Models\Tag::class)->withTimestamps(); | |
return $this->belongsToMany(\Mega\Modules\Account\Models\Account::class)->withTimestamps(); | |
php artisan migrate:refresh; | |
php artisan db:seed; | |
or: | |
php artisan db:seed --class=UsersTableSeeder | |
best : | |
php artisan migrate:fresh --seed | |
You may also seed your database using the migrate:refresh command, which will also rollback and re-run all of your migrations. This command is useful for completely re-building your database: | |
php artisan migrate:refresh --seed (erase database, but doesn't drop tables.) | |
php artisan migrate:fresh --seed (a fresh new migration. it drops tables too. (From 5.5). | |
OR: | |
7. php artisan tinker | |
factory('App\Wordchain', 50)->create(); | |
It creates 50 fake, and it will be in the database. | |
8. | |
in routes/web | |
Route::resource('Wordchain', 'WordchainConroller'); | |
php artisan route:list | |
/it gives all the routes list | |
9. Then in WordchainController: | |
public function index() | |
{ | |
$wordchain = Wordchain::all(); | |
return view('wordchain.index', ['wordchains' => $wordchain]);} | |
10.resources\views\wordchains(én készítettem)\index.blade.php make and edit. | |
11. php artisan serve | |
12.in a brower http://localhost:8000/Wordchain | |
13.comment out in blade: | |
{{-- and end with --}} | |
14. PAGINATION | |
in the Controller : ->simplePaginate(5); | |
don't use get:get() | |
if there is orberBy then it will not work. | |
in View : <?php echo $products->render(); ?> | |
or | |
<div class=" d-flex justify-content-center pt-2"> | |
{{ $products->links() }} | |
</div> | |
Second way : | |
php artisan make:controller LearnController --resource; | |
$users = DB::table('sizes') | |
->crossJoin('colours') | |
->get(); | |
Teszt: | |
run: | |
in cli : | |
.vendor/bin/phpunit | |
or | |
./vendor/bin/phpunit | |
vscodeban phpunit setup: | |
C:\Users\User\AppData\Roaming\Composer\vendor\bin\phpunit.bat | |
"./phpunit.xml.dist" | |
], | |
protected $guarded = []; | |
vs protected $fillable | |
<link href="{{ asset('css/album.css') }}" rel="stylesheet"> | |
//For n:m Relationships, where I need to attach random entries, I use this simple but efficient Seeder code, that only uses real ids: | |
// $faker = Faker\Factory::create(); | |
// $limit = 100; | |
// for ($i = 0; $i < $limit; $i++) { | |
// $newrow = *Yourmodel*::create ([ | |
// 'email' => $faker->word . rand(0, 9999) . '@test.com' , | |
// ... | |
// ]); | |
// $ids = $faker->randomElements( \App\YourOtherModel::select('id')->get()->toArray(), rand(1,*3*) ); | |
// foreach($ids as $id) { | |
// $newrow->*your_relationship*()->attach( $id ); | |
// } | |
'customer_id' => $faker->unique()->randomElement($array = array ('1','2','3','4','5','6','7','8','9','10')), | |
'customer_id' => App\Customer::inRandomOrder()->first()->id, | |
'customer_id' => $faker->unique()->numberBetween(1,10), | |
<div class="alert alert-danger {{(count($errors)) ? 'show' : 'hide'}}"> | |
resorces lang en pagination: | |
'previous' => '« Előző', | |
'next' => 'Következő »', | |
CARBON | |
<?php | |
use Carbon\Carbon; | |
Carbon::setLocale('hu'); | |
?> | |
sqlite :(in env file): | |
DB_CONNECTION=sqlite | |
DB_DATABASE=database/database.sqlite | |
What happens if you remove the DB_DATABASE from your .env file and use the default in config/database.php which is | |
'database' => env('DB_DATABASE', database_path('database.sqlite')), | |
Restart server!!! | |
Pagination: | |
php artisan vendor:publish | |
USEFUL COMMANDS: | |
php artisan cache:clear | |
php artisan view:clear | |
php artisan config:clear | |
php artisan route:clear | |
in .zshrc or/and in .bashrc: | |
alias paclear='php artisan view:clear && php artisan cache:clear && php artisan config:clear && php artisan route:clear' | |
answer: | |
Compiled views cleared! | |
Application cache cleared! | |
Configuration cache cleared! | |
Route cache cleared! | |
Clear the config cache php artisan config:clear or rebuild it php artisan config:cache. | |
AUTH and Frontend scaffolding: | |
in laravel 6: | |
php artisan make:auth; => it makes a login page. i | |
in laravel 7 : | |
composer require laravel/ui | |
Front end scaffolding: | |
//in Laravel 7 | |
composer require laravel/ui | |
//before laravel 8 it worked. | |
In 2020 12 there was a failure: | |
Your requirements could not be resolved to an installable set of packages. | |
Problem 1 | |
- laravel/ui[v3.1.0, ..., 3.x-dev] require illuminate/console ^8.0 -> found illuminate/console[v8.0.0, ..., 8.x-dev] but it conflicts with another require. | |
- Root composer.json requires laravel/ui ^3.1 -> satisfiable by laravel/ui[v3.1.0, 3.x-dev]. | |
solution: | |
composer require laravel/ui "^2.0" | |
//in Laravel 6 | |
composer require laravel/ui:^1.0 --dev | |
php artisan ui bootstrap --auth | |
npm install && npm run dev | |
then: | |
php artisan ui vue --auth | |
or | |
php artisan ui react --auth | |
or | |
php artisan ui bootstrap --auth | |
--auth is not necessary, just in case you need authentication | |
npm install && npm run dev | |
npm install | |
npm run dev | |
npm run watch | |
You may find that in certain environments Webpack isn't updating when your files change. If this is the case on your system, consider using the watch-poll command: | |
npm run watch-poll | |
Creating Applications Including Authentication | |
If you are starting a brand new application and would like to include the authentication scaffolding, you may use the --auth directive when creating your application. This command will create a new application with all of the authentication scaffolding compiled and installed: | |
laravel new blog --auth | |
How to downgrade Laravel? | |
The best way to do this is by changing the value of the Laravel version inside the composer.json file to the laravel 5.5. | |
delete vendor folder and run composer install | |
or: | |
composer create-project --prefer-dist laravel/laravel PROJECTNAME "6.*" | |
>composer create-project --prefer-dist laravel/laravel Projectname "7.*" | |
prefer-dist : | |
--prefer-dist: Reverse of --prefer-source, Composer will install from dist if possible. This can speed up installs substantially on build servers and other use cases where you typically do not run updates of the vendors. It is also a way to circumvent problems with git if you do not have a proper setup. | |
prefer-source: | |
--prefer-source: There are two ways of downloading a package: source and dist. For stable versions Composer will use the dist by default. The source is a version control repository. If --prefer-source is enabled, Composer will install from source if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. | |
Using sqlite | |
in .env file | |
DB_CONNECTION=sqlite | |
?? DB_DATABASE=database/database.sqlite | |
and make an sqlite database | |
touch database/database.sqlite | |
php artisan migrate:fresh | |
error: | |
What happens if you remove the DB_DATABASE from your .env file and use the default in config/database.php which is | |
'database' => env('DB_DATABASE', database_path('database.sqlite')), | |
Restart server!!! | |
In vscode : ctrl+shift+p (commands) | |
sqlite extension | |
open sqlite database (and it is not working :) ) | |
TINKER | |
factory('App\User', 10)->create(); | |
App\User::all() | |
App\User::first() | |
php artisan make:seeder UserSeeder | |
//Many to many | |
User::first()->roles()->attach(3); | |
return User::first(); | |
return User::with('roles')->first(); | |
return User::first()->roles; | |
return User::first()->roles->first(); | |
return User::first()->roles->first()->name; | |
Before and Role using | |
Route::get(/reporting, function(){ | |
return 'secret financial data'; | |
})->before(role:admin); | |
after that we should make a filter...Route::filter where csrf filter is. | |
https://github.com/laracasts/Users-and-Roles-in-Laravel/blob/master/app/filters.php | |
Route::filter('role', function($route, $request, $role) | |
{ | |
if (Auth::guest() or ! Auth::user()->hasRole($role)) | |
{ | |
App::abort(403); | |
} | |
}); 4years ago... | |
Route::get('/reports', function () { | |
return 'the secret reports'; | |
})->middleware('can:view_reports'); | |
Auth::loginUsingId(1); | |
auth()->loginUsingId(11); | |
Dependency / dependecies: | |
if you're not a Windows user you can drop cross-env. | |
Note: if you drop the cross-env dependency, you also have to remove the string "cross-env " from the beginning of each of the scripts lines (e.g. cross-env NODE_ENV=... becomes NODE_ENV=...). | |
it shows the sql command for the query: | |
DB::listen(function($query) {var_dump($query->sql, $query->bindings); }); | |
In User Model. It makes the query in Laracasts Laravel 6 from scratch ep.60. It makes the query not by id but by 'name'. | |
public function getRouteKeyName{ | |
return 'name'; | |
} | |
<p> Joined {{$user->created_at->diffForHumans() }} </p> | |
in blade: | |
@component('master') | |
//if you have a componentS dir in wievs. Laravel 7. | |
In laravel 7 also you can use: | |
<x-master> </x-master> | |
from Laravel docs: | |
Often, you will need to pass additional content to your component via "slots". Let's imagine that an alert component we created has the following markup: | |
<!-- /resources/views/components/alert.blade.php --> | |
<div class="alert alert-danger"> | |
{{ $slot }} | |
</div> | |
We may pass content to the slot by injecting content into the component: | |
<x-alert> | |
<strong>Whoops!</strong> Something went wrong! | |
</x-alert> | |
The major difference is that Laravel's users table migration out the box changed from $table->increments('id'); to $table->bigIncrements('id'); in Laravel 5.8. | |
php artisan vendor:publish --tag=anypackage | |
fe. | |
php artisan vendor:publish --provider="Encore\Admin\AdminServiceProvider" | |
//https://laravel-admin.org/docs/#/ | |
Stub Customization | |
php artisan stub:publish | |
The Artisan console's make commands are used to create a variety of classes, such as controllers, jobs, migrations, and tests. These classes are generated using "stub" files that are populated with values based on your input. However, you may sometimes wish to make small changes to files generated by Artisan. To accomplish this, you may use the stub:publish command to publish the most common stubs for customization: | |
The published stubs will be located within a stubs directory in the root of your application. Any changes you make to these stubs will be reflected when you generate their corresponding classes using Artisan make commands. | |
## php artisan storage:link | |
The [/home/bazs/code/bicycle_7.7.1/public/storage] link has been connected to [/home/bazs/code/bicycle_7.7.1/storage/app/public]. | |
The links have been created. | |
<p> | |
You are logged in (1) : {{ Auth::user()->name }} | |
<br> | |
You are logged in (2): {{ auth()->user()->name }} | |
</p> | |
Middleware auth | |
or method chaining in .web file ->auth() | |
or in Controller in the __construct method: | |
public function __construct() | |
{ | |
$this->middleware('auth'); | |
} | |
in blade file | |
@if (Auth::user()){ | |
Hi {{Auth::user()->name}} | |
} | |
@else { | |
default | |
} | |
@endif | |
or (both is the same) | |
@if (Auth::check()){ | |
Hi {{Auth::user()->name}} | |
} | |
@else{ | |
default | |
} | |
@endif | |
Same: | |
@auth { | |
Hi {{Auth::user()->name}} | |
} | |
@else { | |
default | |
} | |
@endauth | |
The opposite of @auth is @guest | |
@guest { | |
} | |
@else { | |
} | |
@endguest | |
Carbon: | |
use Carbon\Carbon | |
Add the following line to the aliases array in the config/app.php: | |
'Carbon' => 'Carbon\Carbon' | |
And you need to add use Carbon; every class where you want to use it. | |
You can declare some fields in your models using the following structure: | |
protected $dates = ['created_at', 'updated_at', 'disabled_at','mydate']; | |
All of those fields will automatically be Carbon instances and you will be able to use them in your views like: | |
{{ $article->mydate->diffForHumans() }} | |
Single Action Controllers: | |
php artisan make:controller ShowProfile --invokable | |
Error: | |
undefined variable id laravel | |
answe from SO: | |
just pass the $id to your Update method: | |
public function update(Request $request, $id) | |
but you have to make sure your route has {id} segment in your routes file | |
IF, Unless | |
@if (! in_array($currentVersion, [DEFAULT_VERSION, 'master'])) | |
@unless (in_array($currentVersion, [DEFAULT_VERSION, 'master'])) | |
DAVE-CRAP-BREAD | |
DAVE (Delete-Add-View-Edit) | |
CRAP (Create-Retrieve-Alter-Purge) | |
BREAD (Browse-Read-Edit-Add-Delete) | |
Voyager admin package: | |
https://github.com/the-control-group/voyager | |
https://voyager.devdojo.com/academy/routing/ | |
Route Group Rout gruping example: | |
Route::group(['prefix' => 'admin'], function () { | |
Voyager::routes(); | |
}); | |
You have to change in config also the prefix. fe : voyager.php | |
$table->integer('parent_id')->unsigned()->nullable()->default(null); | |
$table->integer('order')->default(1); | |
doctrine/dbal | |
dbal = database absraction layer. | |
doctrine : The Doctrine Project is the home to several PHP libraries primarily focused on database storage and object mapping. | |
Laravel 5 now supports changing a column; here's an example from the offical documentation: | |
$table->text('excerpt')->nullable()->change(); ??? | |
Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the required adjustments: | |
Laravel 7 doc | |
$table->nullableTimestamps(0); Alias of timestamps() method. | |
$table->softDeletes('deleted_at', 0); Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes with precision (total digits). | |
$table->softDeletesTz('deleted_at', 0); Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes with precision (total digits). | |
Psalm | |
Psalm is an open-source static analysis tool for PHP that helps you identify both obvious and hard-to-spot bugs in your code. | |
https://psalm.dev/schema/config | |
psalm.xml in vendor files. | |
Soft Deletes: | |
in migration table: | |
$table->softDeletes(); | |
$table->timestamps(); | |
In model: | |
use SoftDeletes; | |
protected $dates = ['deleted_at']; | |
protected $table = 'estados'; | |
protected $casts = ['id' => 'string', 'pais_id' => 'string']; | |
protected $primaryKey = ['id', 'pais_id']; // | |
protected $fillable=[ | |
'id', 'pais_id', 'estado', | |
]; | |
https://laravel.com/docs/7.x/eloquent-mutators | |
Route::get('/clear-cache', function() { | |
$configCache = Artisan::call('config:cache'); | |
$clearCache = Artisan::call('cache:clear'); | |
// return what you want | |
}); | |
# Timezone: | |
in config\app.php | |
'timezone' => env('APP_TIMEZONE', 'UTC'), | |
in .env | |
APP_TIMEZONE=Europe/Budapest | |
In order to use users timezone, first that timezone needs to be stored somewhere | |
for example in DB table users under column timezone | |
and then if you need the current time in users timezone you just call this method: | |
$usersCurrentTime = now($user->timezone)->format('Y-m-d H:i:s'); | |
That will give you the current time in users timezone. | |
# session | |
HomeController@index | |
dd(request()->session()->all()); | |
https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php | |
# json_encode vs json_decode | |
$name = json_encode(['name' => 'Abigail', 'state' => 'CA']); | |
//dd($name); // "{"name":"Abigail","state":"CA"}" | |
$nameback = json_decode($name); | |
//dd($nameback); //{#247 ▼ +"name": "Abigail" +"state": "CA"} | |
# serialize vs unserialize | |
$myarray = array('Guitar' => 'Johnny', 'Vocals'=> 'Stephen', 'Bass' => 'Andy', 'Drums' => 'Mike'); | |
$mySerial = serialize($myarray); | |
dd($mySerial); // "a:4:{s:6:"Guitar";s:6:"Johnny";s:6:"Vocals";s:7:"Stephen";s:4:"Bass";s:4:"Andy";s:5:"Drums";s:4:"Mike";}" | |
$deserialised = unserialize($mySerial); | |
// dd($deserialised); | |
// array:4 [▼ "Guitar" => "Johnny" "Vocals" => "Stephen" "Bass" => "Andy" "Drums" => "Mike"] | |
# Variable handling Functions | |
drop the dd() and use print_r() instead due to the Laravel lifecycle | |
print_r() displays information about a variable in a way that's readable by humans. | |
print_r ( mixed $expression [, bool $return = FALSE ] ) : mixed | |
# Middleware | |
# Auth | |
If you want to add that extra middleware in the route. Just use the group and you'll be fine. | |
Route::group(['middleware' => 'auth'], function () { | |
// User needs to be authenticated to enter here. | |
Route::get('/', function () { | |
// Uses Auth Middleware | |
}); | |
Route::get('user/profile', function () { | |
// Uses Auth Middleware | |
}); | |
}); | |
# Truncate | |
If you wish to truncate the entire table, which will remove all rows and reset the auto-incrementing ID to zero, you may use the truncate method: | |
DB::table('users')->truncate(); | |
Visitor::query()->truncate(); | |
Visitor::truncate(); | |
# manyToMany | |
// $admin->role()->attach($adminRole); | |
// $author->role()->attach($authorRole); | |
// $user->role()->attach($userRole); | |
# DB::listen | |
DB::listen(function($query) {var_dump($query->sql, $query->bindings); }); | |
# Carbon | |
# class | |
<tr class="@if($ldate->diffindays($rx->rxdate)>="90") table-danger @elseif($ldate->diffindays($rx->rxdate)>="60") table-warning @endif" >> | |
# AUTH | |
Auth::logout(); | |
# clear all | |
php artisan optimize:clear | |
/* | |
Compiled views cleared! | |
Application cache cleared! | |
Route cache cleared! | |
Configuration cache cleared! | |
Compiled services and packages files removed! | |
Caches cleared successfully! | |
*/ | |
my paclear = php artisan clear: ..... does lesser. | |
/* | |
Compiled views cleared! | |
Application cache cleared! | |
Configuration cache cleared! | |
Route cache cleared! | |
*/ | |
# uuid | |
A universally unique identifier (UUID) is a 128-bit number used to identify information in computer systems. The term globally unique identifier (GUID) is also used, typically in software created by Microsoft. | |
123e4567-e89b-12d3-a456-426614174000 | |
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx | |
You may want to set | |
protected $keyType = 'string'; | |
so Laravel handles joins as strings and doesn’t cast to integer. | |
OPTIONAL: If you changed the field name in your migrations, you must set | |
protected $primaryKey = 'uuid'; | |
to match. | |
Usually for UUID you will also set | |
public $incrementing = false; | |
.Remove it if it causes problems for you. | |
# unindent indent | |
tab shift+tab | |
# sqlite | |
touch database/database.sqlite | |
# MustVerifyEmail | |
in app\User.php | |
class User extends Authenticatable implements MustVerifyEmail | |
in: | |
app/routes/web.php | |
Auth::routes(['verify' => true]); | |
and simple in your method just call this: | |
$user->sendEmailVerificationNotification(); | |
# MYSQL Varchar and text | |
The string() method creates a VARCHAR equivalent column while text() creates a TEXTequivalent. With that done, let’s go ahead and migrate: | |
HTTP codes: | |
200: OK. The standard success code and default option. | |
201: Object created. Useful for the store actions. | |
204: No content. When an action was executed successfully, but there is no content to return. | |
206: Partial content. Useful when you have to return a paginated list of resources. | |
400: Bad request. The standard option for requests that fail to pass validation. | |
401: Unauthorized. The user needs to be authenticated. | |
403: Forbidden. The user is authenticated, but does not have the permissions to perform an action. | |
404: Not found. This will be returned automatically by Laravel when the resource is not found. | |
500: Internal server error. Ideally you're not going to be explicitly returning this, but if something unexpected breaks, this is what your user is going to receive. | |
503: Service unavailable. Pretty self explanatory, but also another code that is not going to be returned explicitly by the application. | |
# NEXT LINE / end of line | |
echo "<p>".$thisyearjanfirst. "<p/>\n"; | |
echo "<p>".$lastyearjanlast. "<p/>" . PHP_EOL; | |
# git nah : | |
alias nah="git reset --hard && git clean -df" | |
logger('Debug message'); //App/Storage/logs/laravel.log | |
logger(); | |
logger()->error('You are not allowed here.'); | |
# Variable | |
dump($array); | |
var_dump($array); | |
echo "<br>"; | |
print_r($array); | |
echo $array; //Array to string conversion | |
PHP to JS | |
Object to array | |
//Assign php generated json to JavaScript variable | |
let tempArray = <?php echo json_encode($mergecombinedorigplusdates); ?>; | |
//You will be able to access the properties as | |
//alert(tempArray); //object Object | |
//console.log(tempArray); | |
var datesGood = Object.keys(tempArray); | |
console.log(datesGood); //array | |
var countsGood = Object.values(tempArray); | |
console.log(countsGood); //array | |
php --ini | |
cd etc/php/7.4/cli/php.ini | |
cat php.ini | |
nano /etc/php/7.4/cli/php.ini | |
# Store method example: | |
$post = [ | |
'title'=>$data['title'], | |
'body'=>$data['body'], | |
'created_by'=>$request->created_by, | |
'user_id'=>Auth::user()->id, | |
'filled_by'=>Auth::user()->uuid | |
] | |
if ($id && $id->friends_id == auth()->id()) { | |
$post['name'] = $id->name; | |
} | |
Post::create($post); | |
#Test Jquery | |
//write in text and hit enter | |
<input id="ddtype" type="text" placeholder="enter here with mouse"> | |
<script> | |
$(document).ready(function(){ | |
jQuery( "#ddtype" ).mouseenter(function() { | |
alert( "Handler for .change() called." ); | |
}); | |
}); | |
</script> | |
#Error errorfinding | |
$data= $request->all(); | |
echo "<pre>"; | |
print_r($data); | |
die; | |
Check remote: | |
git remote -v | |
Github change remote dir. | |
git remote set-url origin https://github.com/Bazsmagister/bicycle_7_7_1.git | |
Cookie: | |
Session::put('check', "data"); | |
$cookie= Session::get('check'); | |
dump($cookie); | |
var_dump($cookie); | |
************************* | |
// $request->session()->put('key', 'myvalue'); | |
// $answer= $request->session()->get('key', 'default'); | |
// dump($answer); | |
TABLE: | |
<table id="table_devices" class="table table-striped table-bordered"> | |
<thead class="thead-dark"> | |
<tr> | |
<th scope="col">#</th> | |
<th scope="col">Name</th> | |
<th scope="col">Description</th> | |
<th scope="col">Serial</th> | |
<th scope="col">IP</th> | |
<th scope="col">x</th> | |
<th scope="col">y</th> | |
<th scope="col">Level</th> | |
<th scope="col">Map</th> | |
<th scope="col">Status</th> | |
</tr> | |
</thead> | |
<tbody> | |
@foreach ($devices as $device) | |
<tr> | |
<td>{{ $device->id }}</td> | |
<td>{{ $device->name }}</td> | |
<td>{{ $statu->description ? $statu->description : '--' }}</td> | |
<td>{{ $device->serial }}</td> | |
<td>{{ $device->ip }}</td> | |
<td>{{ $device->x }}</td> | |
<td>{{ $device->y }}</td> | |
<td>{{ $device->level }}</td> | |
<td>{{ $device->map->name }}</td> | |
<td>{{ $device->statu->name }}</td> | |
</tr> | |
@endforeach | |
</tbody> | |
</table> | |
.env | |
FILESYSTEM_DRIVER=public | |
form validation( with tailwind) | |
@error('name') | |
<p class = "text-red-500">{{$message}}</p> | |
@enderror | |
An alternate solution is adding this to the links key in your config/filesystems.php file. | |
public_path('avatars') => storage_path('app/public/avatars'), | |
After adding that, then you can run the artisan command again, and it should work. | |
For the avatar validation, you can use the image rule instead of just file. The dimensions rule maybe be useful as well. Example: | |
'avatar' => [ | |
'image', | |
'dimensions:min_width=100,min_height=200', | |
], | |
<div class="mb-6"> | |
<label class="block mb-2 uppercase font-bold text-xs text-grey-700" for="name"> | |
Name | |
</label> | |
<input class="border border-grey-400 p-2 w-full" type="text" name="name" id="name" required> | |
@error('name') | |
<p class="text-red-500 text-xs mt-2">{{ $message }}</p> | |
@enderror | |
</div> | |
Seeder | |
return [ | |
type' => 'image', | |
'url' => $faker->imageUrl(666, 461, 'cats'), | |
'is_primary' => $faker->randomElements([true, false]) | |
'name' => $faker->sentence(20, true), | |
'slug' => $faker->slug(), | |
'description' => $faker->realText(420), | |
'booking_details' => $faker->realText(120), | |
'cost' => $faker->randomFloat(2, 10, 250) | |
]; 'type' => $faker->randomElement(['user', 'performer', 'admin']) | |
Sometimes we may not want to save the data created to the database. For that we use the make method on the factory object instead of create. | |
$user = factory(App\User::class)->make(); | |
Laravel Echo REDIS Pusher Channel: | |
1. app\config\app.php | |
uncomment : | |
// App\Providers\BroadcastServiceProvider::class, | |
test: | |
php artisan route:list | |
GET|POST|HEAD broadcasting/auth Illuminate\Broadcasting\BroadcastController@authenticate | |
2. app\config\broadcasting.php | |
'default' => env('BROADCAST_DRIVER', 'null'), | |
to log or redis or pusher: | |
'default' => env('BROADCAST_DRIVER', 'log'), | |
3. | |
php artisan make:event BicycleUpdated | |
4. in | |
app\events\Bicycleupdated | |
implements ShouldBroadcast contract(interface) | |
public function broadcastOn() | |
{ | |
// return new PrivateChannel('channel-name'); | |
return new Channel('orders'); | |
} | |
5. web.php | |
use App\Events\BicycleUpdated; | |
Route::get('/', function () { | |
BicycleUpdated::dispatch(); | |
//same as | |
// event(new BicycleUpdated); | |
return view('welcome'); | |
}); | |
6. pas (php artisan serve) | |
hit the route: | |
php artisan event:list | |
check app\storage\logs\laravel.log | |
[2020-06-12 10:22:30] local.INFO: Broadcasting [App\Events\BicycleUpdated] on channels [orders] with payload: | |
{ | |
"socket": null | |
} | |
7. in BicycleUpdated.php | |
if you define a public property than it will load in the broadcast. | |
API: | |
question: | |
hi i want to update one of my tables with the new data i post to my controller is there a way to do some thing like | |
Platform::update($request->all()); | |
my post request is like this | |
axios.post(`http://www.crown.mehi/admin/platforms`, { data }) | |
.then(res => { | |
console.log(res); | |
console.log(res.data); | |
}) | |
i changed the data inside of json request and i want to update my table in database with it | |
public function store(Request $request) | |
{ | |
dd($request->all); | |
Platform::update($request->all()); | |
} | |
answer | |
So the solution for the problem was this: | |
public function updateOrder(Request $request) | |
{ | |
foreach ($request['data'] as $entry) { | |
Platform::where('id', $entry['id'])->update(['order' => $entry['order']]); | |
} | |
} | |
You have to go through all of the sent items and update them. | |
'bicycle_id' => \App\Bicycle::all()->random()->id, | |
'user_id' => \App\User::all()->random()->id, | |
$maxValue = App\User::max('id'); | |
dd($maxValue); | |
Public function search(){ | |
$pageName = 'your page name'; | |
$error = 'something went wrong'; | |
return view('yourview')->with([ | |
'page_title'=> $pageName, | |
'error'=> $errorMesssage | |
]); | |
} | |
Now you can access those variable in your blade file as | |
{{$page_title}} | |
{{$error}} | |
Try to use {!! $data->render() !!} instead of {!! $data->links() !!} | |
# strtotime | |
$dateStart = date('Y-m-d', strtotime('-5 year')); | |
$dateEnd = date('Y-m-d'); | |
#php ini | |
echo php_ini_loaded_file(); | |
# bash function | |
function acp(){ | |
git add --all; | |
git commit -m "$1"; | |
git push; | |
} | |
# Collection vs 1 object: | |
When you're using get() you get a collection. In this case you need to iterate over it to get properties: | |
@foreach ($collection as $object) | |
{{ $object->title }} | |
@endforeach | |
Or you could just get one of objects by it's index: | |
{{ $collection[0]->title }} | |
Or get first object from collection: | |
{{ $collection->first() }} | |
When you're using find() or first() you get an object, so you can get properties with simple: | |
{{ $object->title }} | |
# File Storage example: | |
public function store(Request $request) { | |
$blob = $request->file('record_audio'); | |
$filename = $blob->getClientOriginalName() . date("now") . ".ogg"; | |
$localization = 'files/' . $filename; | |
Storage::put($localization, file_get_contents($blob)); | |
} | |
# migartion tipps | |
$table->string('PASSWORD', 500); | |
$table->string('profileImage', 500)->default(null); | |
$table->boolean('admin')->default('0'); | |
$table->time('created_At')->nullable()->useCurrent(); | |
# form dropdown languages: | |
<div class="p-4 pt-5"> | |
<div class="btn-group dropright"> | |
<form action="home-screen" method="get"> | |
@csrf | |
<select name="lang" onchange="submit()" class="custom-select custom-select-sm text-light bg-dark border-0" > | |
<option disabled selected hidden>Languages</option> | |
<option value="1">Dutch</option> | |
<option value="2">English</option> | |
<option value="3">Francais</option> | |
<option value="4">Deutch</option> | |
</select> | |
</form> | |
</div> | |
</div> | |
# session flash success | |
In your Controller : | |
return redirect(route('post.index'))->withSuccess('Post Edited Successfully'); | |
In your blade : | |
@if(Session::has('success') ) | |
<h4 class="alert alert-info" >{{ session()->get('success')}}</h4> | |
@endif | |
# cron schedule | |
$logfilename = 'cron_'. now()->format('Y_m_d') . '.txt'; | |
//Push Notification check - RUNS EVERY FIVE MINUTES | |
$schedule->exec('env -i /usr/local/bin/php72 -f /www/xxxx-xxxx.com/artisan command:pushmessages')->everyFiveMinutes()->appendOutputTo(public_path().'/logs/'.$logfilename); | |
php artisan stub:publish | |
The published stubs will be located within a stubs directory in the root of your application. Any changes you make to these stubs will be reflected when you generate their corresponding classes using Artisan make commands. | |
Auth::check(); | |
https://laravel.com/docs/7.x/authentication | |
Illuminate\Support\Facades\Auth; | |
if (Auth::check()) { | |
// Your code | |
} | |
# In the shell, what does “ 2>&1 ” mean? | |
File descriptor 1 is the standard output (stdout). | |
File descriptor 2 is the standard error (stderr). | |
Here is one way to remember this construct (although it is not entirely accurate): at first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1". & indicates that what follows is a file descriptor and not a filename. So the construct becomes: 2>&1. | |
Directory Separator: | |
Because in different OS there is different directory separator. In Windows it's \ in Linux it's /. DIRECTORY_SEPARATOR is constant with that OS directory separator. Use it every time in paths. | |
# sqlite: | |
touch database/database.sqlite | |
.env: | |
DB_CONNECTION=sqlite | |
DB_DATABASE=/absolute/path/to/database.sqlite | |
php artisan migrate | |
# API token json | |
Route::group(['namespace' => 'Api', 'middleware' => ['auth:sanctum']], function(){ | |
Route::post('logout/all', 'Auth\LoginController@logoutAll'); | |
Route::post('logout', 'Auth\LoginController@logout'); | |
Route::put('profile/{profile}', 'ProfileController@update'); | |
}); | |
public function logout(Request $request) | |
{ | |
Auth::user()->tokens()->where('id', Auth::user()->currentAccessToken()->id)->delete(); | |
return response()->json(['data' => 'User logged out.'], 200); | |
} | |
# | |
$client = new Client(); | |
$res = $client->request('POST', 'http://127.0.0.1:5000', [ 'form_params' => $data ]); | |
if ($res->getStatusCode() == 200) | |
{ $response_data = $res->getBody()->getContents(); | |
//return $response_data;; | |
dd($response_data); | |
// $data = gettype($response_data); | |
// dd($data); | |
//View | |
return view('front.flight-list', compact('response_data')); | |
} | |
to convert your JSON string response to a JSON object you can work with. You an also do something like $response_data = collect(json_decode($res->getBody(), true)); to make it into a laravel collection as well | |
# Login Modal, Sign in | |
@guest | |
<li class="list-inline-item"> | |
<button type="button" class="btn btn-primary btn-outline-light" data-toggle="modal" data-target="#signIn" href="{{ route('login') }}">{{ __('Login') }}</button> | |
</li> | |
@if (Route::has('register')) | |
<li class="list-inline-item"> | |
<button type="button" class="btn btn-primary btn-outline-light" data-toggle="modal" data-target="#signUp" href="{{ route('register') }}">{{ __('Register') }} </button> | |
</li> | |
@endif | |
@endguest | |
bootstrap modal SignIn: | |
<div class="modal" id="signIn"> | |
<div class="modal-dialog"> | |
<div class="modal-content"> | |
<!-- Modal Header --> | |
<div class="modal-header"> | |
<h4 class="modal-title">SignIn</h4> | |
<button type="button" class="close" data-dismiss="modal"> | |
× | |
</button> | |
</div> | |
<!-- Modal body --> | |
<div class="modal-body"> | |
<form method="POST" action="{{ route('login') }}"> | |
@csrf | |
<div class="form-group"> | |
<label for="email" class="">{{ __('E-Mail Address') }}</label> | |
<input id="email" type="email" class="form-control" @error('email') is-invalid @enderror" | |
name="email" value="{{ old('email') }}" required autocomplete="email" autofocus /> | |
@error('email') | |
<span class="invalid-feedback" role="alert"> | |
<strong>{{ $message }}</strong> | |
</span> | |
@enderror | |
</div> | |
<div class="form-group"> | |
<label for="password" class="">{{ __('Password') }}</label> | |
<input id="password" type="password" | |
class="form-control @error('password') is-invalid @enderror" name="password" required | |
autocomplete="current-password"> | |
@error('password') | |
<span class="invalid-feedback" role="alert"> | |
<strong>{{ $message }}</strong> | |
</span> | |
@enderror | |
</div> | |
<div class="form-group"> | |
<button type="submit" class="btn btn-primary btn-block"> | |
Sign In | |
</button> | |
</div> | |
</form> | |
</div> | |
</div> | |
</div> | |
</div> | |
* * * * * /path/to/php /home/path/to/project/php artisan storage:link | |
# SO | |
# If you have no ssh/terminal access, then create symbolic link with Route, run it once & delete it. | |
route/web.php : | |
Route::get('/sym', function () { | |
Artisan::call('storage:link'); | |
}); | |
# abort | |
abort(404, 'sorry the page is not found'); | |
# firstOrFail(); | |
if (!$post){abort(404);} | |
$post = Post::where(slug , $slug)->first(); | |
$post = Post::where(slug , $slug)->firstOrFail(); | |
# Get specific columns in json | |
You can use select for certain field display : | |
Model::select('title', 'price', 'description')->get(); | |
Or, in get() method : | |
Model::get(['title', 'price', 'description']); | |
As you would like to make some typically visible attributes hidden on a given model instance, you may use the makeHidden method : | |
$data = Model::all(); | |
$data->makeHidden('price'); | |
Now price will be hidden from your query. | |
# | |
# Multiple file uploads: | |
<div class="form-group"> | |
<label >Product Image</label> | |
<input type="file" class="form-control btn btn-primary" name="image[]" multiple="multiple"> | |
</div> | |
$productSubImages = $request->file('sub_image'); | |
foreach($productSubImages as $productSubImage){ | |
$subImageName =$productSubImage->getClientOriginalName(); | |
$subImageDirectory = 'product-sub-images/'; | |
$productSubImage->move($subImageDirectory,$subImageName); | |
$subImageUrl =$subImageDirectory.$subImageName; | |
$subImage = new SubImage(); | |
$subImage->product_id = $productId; | |
$subImage->sub_image = $subImageUrl; | |
$subImage->save(); | |
} | |
<li class="{{Request::path()==='/' ? 'page_item active' : ''}}"><a href="{{ url('/') }}">Home</a></li> | |
# python in laravel | |
$result = shell_exec("python " . storage_path() . "/python/python.py 2>&1"); //this works | |
echo($result); | |
$result2 = shell_exec("python " . public_path() . "/storage/python/python.py 2>&1"); //this works too | |
echo($result2); | |
$command ="python ".public_path() . "/storage/python/python.py"; | |
// $command =public_path() . "/storage/python/python.py"; //need python | |
$proc = Process::fromShellCommandline($command, null, [])->mustRun()-> | |
getOutput(); | |
//getErrorOutput(); | |
echo $proc; | |
win10 | |
echo %PATH% | |
Old setuptools failure: | |
pip install --upgrade setuptools | |
pip3 install --upgrade setuptools | |
sudo pip3 uninstall numpy | |
sudo pip3 uninstall scipy | |
Then | |
sudo apt-get install python3.5-dev libmysqlclient-dev | |
sudo apt-get install python3-numpy | |
Linux ppa add : | |
sudo add-apt-repository ppa:communitheme/ppa | |
sudo apt update | |
sudo apt install ubuntu-communitheme-session | |
# Date date strtotime | |
{{date('Y F d', strtotime($user->created_at))}} at | |
at | |
{{date('g : ia', strtotime($user->created_at))}} | |
/* | |
\r = CR (Carriage Return) → Used as a new line character in Mac OS before X | |
\n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X | |
\r\n = CR + LF → Used as a new line character in Windows | |
*/ | |
# | |
https://laravel.com/docs/7.x/collections#method-mapwithkeys | |
Route::get('key', function () { | |
$userCollections = User::all(); | |
//dd($userCollections); | |
$userCollectionskey = $userCollections ->mapWithKeys(function ($user) { | |
return [$user['name'] => $user['created_at']]; | |
}); | |
$userCollectionsmap = $userCollectionskey->all(); | |
//dd($userCollectionsmap); | |
//print_r($userCollections); | |
//echo $userCollections; | |
//dd($userCollections); | |
return view('welcome', compact('userCollectionsmap')); | |
}); | |
<div> | |
<ul> | |
@foreach ( $userCollectionsmap as $name => $date) | |
<li> | |
{{ $name }} | Joined at: {{ $date }} | |
</li> | |
@endforeach | |
</ul> | |
</div> | |
# | |
# TABLE | |
<table class="table table-bordered table-striped"> | |
<thead> | |
<tr> | |
<th>Name</th> | |
<th>Email</th> | |
<th>Date/Time Added</th> | |
<th>User Roles</th> | |
<th>Operations</th> | |
</tr> | |
</thead> | |
<tbody> | |
@foreach ($users as $user) | |
@foreach($user->getAttributes() as $key => $value) | |
<p> | |
{{$key, $value}} {{-- it shows only one of them. --}} | |
{{ $value}} | |
{{$key}} | |
</p> | |
@endforeach | |
<tr> | |
<td>{{ $user->name }}</td> | |
<td>{{ $user->email }}</td> | |
<td>{{ $user->created_at->format('F d, Y h:ia') }}</td> | |
<td>{{ $user->roles()->pluck('name')->implode(' ') }}</td>{{-- Retrieve array of roles associated to a user and convert to string --}} | |
<td> | |
<a href="{{ route('users.edit', $user->id) }}" class="btn btn-info pull-left" style="margin-right: 3px;">Edit</a> | |
{!! Form::open(['method' => 'DELETE', 'route' => ['users.destroy', $user->id] ]) !!} | |
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} | |
{!! Form::close() !!} | |
</td> | |
</tr> | |
@endforeach | |
</tbody> | |
</table> | |
# Request | |
# Request helper request() | |
#request parameter : $request->id | |
you can fetch item inside json by request function or request prameter | |
this is by request helper function | |
public function save(){ | |
$id = request("id"); | |
. | |
} | |
by request parameter | |
public function save(Request $request){ | |
$id = $request->id; | |
withTimestamps(); is used in Many to Many relationships where you want to declare that there are created_at and updated_at columns in the join table. | |
$withTimestamps Indicates if timestamps are available on the pivot table. | |
As the exception rightly points out, Illuminate\Database\Eloquent\Relations\HasMany does not have a withTimestamps() method. | |
## Important !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! | |
https://laracasts.com/discuss/channels/laravel/undefined-property-stdclassuser: | |
If you want to get the User through the defined relationship, then you will need to use the Eloquent model to fetch the $history; using the DB class bypasses Eloquent, and therefore, the relationship. Try this instead: | |
$history = Adjustments::with('user') | |
->where('remark_id', $operation->id) | |
->get(); | |
**************** | |
AJAX | |
If you are getting an error after calling the AJAX then you need to add a header like below. In your head tag | |
<meta name="csrf-token" content="{{ csrf_token() }}"> | |
In Your Script tag | |
$.ajaxSetup({ | |
headers: { | |
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') | |
} | |
}); | |
*/-**************** | |
When anytime you want to redirect to any page you must either used "url" or "route" (if you have specified name to route). | |
**** | |
php artisan event:generate | |
or: | |
php artisan make:event and php artisan make:listener | |
The event:generate command is simply a convenient wrapper around the make:listener and make:event commands. | |
The classes generated in the previous example can be manually generated like so: | |
# Generate the BookWasPurchasedEvent event class. | |
php artisan make:event BookWasPurchasedEvent | |
# Generate the EmailPurchaseConfirmation listener class. | |
php artisan EmailPurchaseConfirmation --event=BookWasPurchasedEvent | |
php artisan make:event aRentHasBeenEnded | |
php artisan make:listener EmailToRentUser --event=aRentHasBeenEnded | |
Pusher | |
composer require pusher/pusher-php-server "~4.0" | |
npm install --save laravel-echo pusher-js | |
with public function shouldDiscoverEvents() | |
{ | |
return true; | |
} | |
: it works | |
| App\Events\BicycleUpdated | App\Listeners\EmailToOwner@handle | | |
| App\Events\BicycleUpdated | App\Listeners\EmailToOwner | | |
| App\Events\NewUser | App\Listeners\NewUserAdminNotification@handle | | |
| App\Events\aRentHasBeenEnded | App\Listeners\EmailToRentUser@handle | | |
| App\Events\aRentHasBeenEnded | App\Listeners\EmailToRentUser | | |
| App\Events\aRentHasBeenMade | App\Listeners\RentListener@handle | | |
| App\Providers\NewUser | App\Providers\NewUserAdminNotification | | |
| App\Providers\aRentHasBeenMade | App\Providers\RentListener | |
without it: it doesn't work | |
App\Events\BicycleUpdated | App\Listeners\EmailToOwner | | |
| App\Events\aRentHasBeenEnded | App\Listeners\EmailToRentUser | | |
| App\Providers\NewUser | App\Providers\NewUserAdminNotification | | |
| App\Providers\aRentHasBeenMade | App\Providers\RentListener | |
?php artisan queue:listen | |
t_paamayim_nekudotayim It’s the double colon operator :: done. | |
bootstrap tooltip and collapse: | |
<button type="button" class="btn btn-danger" data-toggle="tooltip" title="Lorem ipsum dolor sit amet, consectetur adipisicing elit, | |
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, | |
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."> | |
Simple tooltip. Hover over me!</button> | |
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#demo">Simple | |
collapsible</button> | |
<div id="demo" class="collapse"> | |
Lorem ipsum dolor sit amet, consectetur adipisicing elit, | |
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, | |
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. | |
</div> | |
symlink: | |
<?php | |
$target = '/home/public_html/xyz/storage/app/public'; | |
$link = '/home/public_html/xyz/storage'; | |
symlink($target, $link); | |
echo 'Symlink done!'; | |
You can create a symlink.php file inside public_html/xyz/public and then go to the link. | |
Example: http://www.xyx.com/symlink.php | |
** Don't forget to delete this file after you finish from linking the storage folder. | |
php artisan storage:link | |
ajax in jquery: | |
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead. | |
$.post("ajax/comment_insert.php", { | |
task : "comment_insert", | |
userId : _userId, | |
comment : _comment, | |
}).done(function(data) { | |
console.log("ResponseText:" + data); | |
}); | |
Laravel File Image upload store: | |
in .env add: | |
FILESYSTEM_DRIVER=public | |
in config/filesystem.php: | |
'links' => [ | |
public_path('storage') => storage_path('app/public'), | |
//add | |
// public_path('images') => storage_path('app/public/images'), | |
//then | |
//php artisan storage:link | |
], | |
import class in controller | |
Illuminate\Http\UploadedFile | |
in controller store method: | |
$imageName = 'hero'.time().'.'.request()->image->getClientOriginalExtension(); | |
$path = $request->file('image')->storeAs('images', $imageName); | |
$hero->image = $path; | |
$hero->save(); | |
<div> | |
<img src="{{ asset("storage/$hero->image") }}" alt="image should be here" width="" height=""> | |
</div> | |
<img src="/storage/{{$hero->image}}" alt="no image yet" height="100" width="120"> | |
<img src="/storage/{{$hero->image}}" alt="no image yet"> | |
## Scout | |
composer require laravel/scout | |
8.2 | |
laravel/scout suggests installing algolia/algoliasearch-client-php (Required to use the Algolia engine (^2.2).) | |
composer require algolia/algoliasearch-client-php | |
2.7 | |
Finally, add the Laravel\Scout\Searchable trait to the model you would like to make searchable. This trait will register a model observer to keep the model in sync with your search driver: | |
use Illuminate\Database\Eloquent\Model; | |
use Laravel\Scout\Searchable; | |
class Post extends Model | |
{ | |
use Searchable; | |
} | |
algolia need id... | |
i try an other engine: | |
https://github.com/yabhq/laravel-scout-mysql-driver | |
composer require yab/laravel-scout-mysql-driver | |
3.0 | |
Next add the ServiceProvider to the Package Service Providers in config/app.php | |
/* | |
* Package Service Providers... | |
*/ | |
Yab\MySQLScout\Providers\MySQLScoutServiceProvider::class, | |
Append the default configuration to config/scout.php | |
'mysql' => [ | |
'mode' => 'NATURAL_LANGUAGE', | |
'model_directories' => [app_path()], | |
'min_search_length' => 0, | |
'min_fulltext_search_length' => 4, | |
'min_fulltext_search_fallback' => 'LIKE', | |
'query_expansion' => false | |
] | |
Set SCOUT_DRIVER=mysql in your .env file | |
<!-- php artisan scout:import --> | |
php artisan scout:mysql-index App\\Hero | |
php artisan scout:import App\\Spell | |
Imported [App\Spell] models up to ID: 5 | |
All [App\Spell] records have been imported. | |
php artisan scout:mysql-index App\\Post --drop | |
in config/scout.php | |
'mysql' => [ | |
'mode' => 'NATURAL_LANGUAGE', | |
I changed it to LIKE | |
I think it is better | |
-------- | |
Blade if else directive on Request::path() | |
@if(Request::path() === 'map') | |
<audio autoplay controls loop> | |
<source src="/storage/grasslandtheme.mp3" type="audio/mpeg"> | |
</audio> | |
@else | |
<audio autoplay controls loop> | |
<source src="/storage/s.mp3" type="audio/mpeg"> | |
</audio> | |
@endif | |
------- | |
spatielaravel-permissions 3.16 | |
composer require spatie/laravel-permission | |
https://spatie.be/docs/laravel-permission/v3/installation-laravel | |
In the Installation instructions you'll see that the HasRoles trait must be added to the User model to enable this package's features. | |
use Illuminate\Foundation\Auth\User as Authenticatable; | |
use Spatie\Permission\Traits\HasRoles; | |
class User extends Authenticatable | |
{ | |
use HasRoles; | |
// ... | |
} | |
in config/app.php add: | |
Spatie\Permission\PermissionServiceProvider::class, | |
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" | |
php artisan optimize:clear | |
php artisan migrate | |
php artisan make:seeder RolesAndPermissionsSeeder | |
in that seeder class: | |
$role = Role::create(['name' => 'admin']); | |
$role->givePermissionTo(Permission::all()); | |
$admin = factory(\App\User::class)->create([ | |
'id' => '1', | |
'name' => 'Admin Adam', | |
'email' => '[email protected]', | |
'password' => bcrypt('adminadmin'), | |
'phone' => '0623232565321', | |
]); | |
$admin ->assignRole('admin'); | |
$authuser = factory(\App\User::class)->create([ | |
'id' => '2', | |
'name' => 'Authenticated User', | |
'email' => '[email protected]', | |
'password' => bcrypt('authuser'), | |
'phone' => '0623232565322', | |
]); | |
$authuser ->assignRole('authuser'); | |
-------lar8 | |
ls database/migrations | wc -l | |
(wordcount -line) | |
There is no factory method anymore. | |
App\Models\User::factory()->make(); | |
//dont persist in the database | |
App\Models\User::factory()->count(3)->make(); | |
persist in the database. | |
App\Models\User::factory()->count(3)->create(); | |
--- | |
App\Models\User::factory()->has(Post::factory->count(5)->create(); | |
This one needs the User model has posts(). | |
posts(){ | |
return \$this->hasMany(Post::class); | |
} | |
--- | |
a lesser verbose with magic method: | |
App\Models\User::factory()->hasPosts(5)->create(); | |
-- | |
reverse of it: | |
Post::factory()->for(User::factory)->count(3)->create(); | |
This one still needs a relationship. | |
public functon user(){ | |
return \$this->belongsTo(User::class); | |
} | |
a lesser verbose: | |
Post::factory()->forUser()->count(3)->create(); | |
--- | |
php artisan down --secret=asecretword | |
so localhost/asecretword will work. It put a cookie on the machine. | |
published: php artisa publish 12 | |
php artisan down --render="errors.illustrated-layout" | |
php artisan down --render="errors::503" | |
--- | |
When you generate your factory with php artisan make:factory in Laravel 8, you need to update: | |
use App\Models\Model; | |
class ModelFactory | |
protected $model = Model::class; | |
In your case, you would have to replace Model with Article: | |
use App\Models\Article; | |
class ArticleFactory | |
protected $model = Article::class; | |
An easier option would have been to run php artisan make:factory --model=Article from the start. Everything would have been properly filled to be used for an Article model. Then, only the definition method would have needed to be edited. | |
---- | |
Spatie\Permission\Exceptions\GuardDoesNotMatch | |
The given role or permission should use guard `` instead of `web`. | |
solution: //in User.php | |
protected $guard_name = 'web'; | |
--- | |
class App\User not found whn i want to login. | |
solution: config/auth.php 'model' => App\Models\User::class, | |
--- | |
$attributes contains the current version of model's attributes. $original is supposed to contain, well, the original values of given object, so here you'll find the values that object was created with or the values it was loaded with from the database. | |
--- | |
php artisan make:controller UserController -m User | |
---jet | |
composer require laravel/jetstream | |
// Install Jetstream with the Livewire stack... | |
php artisan jetstream:install livewire | |
// Install Jetstream with the Inertia stack... | |
php artisan jetstream:install inertia | |
--- csv to mysql | |
//This one works well | |
LOAD DATA LOCAL INFILE '/home/bazs/Desktop/tk_lista.csv' | |
INTO TABLE medicines | |
FIELDS TERMINATED BY ';' | |
ENCLOSED BY '"' | |
LINES TERMINATED BY '\n' | |
IGNORE 1 ROWS | |
(TK_szam,Nev,Kiszereles,INN,ATC,Forg_Eng_Jog,Kiadhatosag,Kiad_alcsop,Biztonsagi_elemek,TK_datum,veglegminta,alaki_hiba,termekhiannyal_erintett); | |
//works well also | |
LOAD DATA LOCAL INFILE '/home/bazs/Desktop/tk_lista.csv' | |
INTO TABLE medicines | |
FIELDS TERMINATED BY ';' | |
ENCLOSED BY '"' | |
LINES TERMINATED BY '\n' | |
IGNORE 1 ROWS; | |
--- | |
Route::get('/phpinfo', function () { | |
phpinfo(); | |
}); | |
//phpinfo(); | |
//echo php_ini_loaded_file(); | |
--- | |
Xdebug | |
php debug felix becker | |
phpinfo() > copy the output | |
paste in the xdebug wizard website | |
Download xdebug-2.9.8.tgz | |
Install the pre-requisites for compiling PHP extensions. | |
On your Ubuntu system, install them with: | |
sudo apt install php-dev autoconf automake | |
Unpack the downloaded file with tar -xvzf xdebug-2.9.8.tgz | |
Run: cd xdebug-2.9.8 | |
Run: phpize (See the FAQ if you don't have phpize). | |
The phpize command is used to prepare the build environment for a PHP extension. | |
As part of its output it should show: | |
Configuring for: | |
... | |
Zend Module Api No: 20190902 | |
Zend Extension Api No: 320190902 | |
If it does not, you are using the wrong phpize. Please follow this FAQ entry and skip the next step. | |
Run: ./configure | |
Run: make | |
Run: cp modules/xdebug.so /usr/lib/php/20190902 | |
Edit /etc/php/7.4/cli/php.ini and add the line | |
zend_extension = /usr/lib/php/20190902/xdebug.so | |
Make sure that zend_extension = /usr/lib/php/20190902/xdebug.so is below the line for OPcache. | |
Please also update php.ini files in adjacent directories, as your system seems to be configured with a separate php.ini file for the web server and command line. | |
Restart the webserver | |
in php ini: | |
[XDEBUG] | |
xdebug.remote_enable=1 | |
xdebug.remote_autostart=1 | |
zend_extension = /usr/lib/php/20190902/xdebug.so | |
--- | |
text, longtext | |
It's based on what type of content you're expecting from the user Text has the capacity to hold 65,535 characters which is about 64 KiB of size while LONG TEXT has the capacity to hold 4,294,967,295 characters which is about 4GB of size. | |
For me I use TEXT. | |
Hope it's helpful. | |
Source [http://stackoverflow.com/questions/13932750/tinytext-text-mediumtext-and-longtext-maximum-storage-sizes] | |
Type | Maximum length | |
-----------+------------------------------------- | |
TINYTEXT | 255 (2 8−1) bytes | |
TEXT | 65,535 (216−1) bytes = 64 KiB | |
MEDIUMTEXT | 16,777,215 (224−1) bytes = 16 MiB | |
LONGTEXT | 4,294,967,295 (232−1) bytes = 4 GiB | |
--- | |
// It cannot be declared with a ‘protected’ access modifier. So, to solve it, try to change it into a ‘public’ access modifier as shown below : | |
//protected $timestamps = false; wrong | |
public $timestamps = false; | |
--- | |
declare(strict_types=1); | |
typed properties: | |
They are available as of PHP 7.4, which is scheduled to be released in November of 2019 | |
They are only available in classes and require an access modifier: public, protected or private; or var | |
All types are allowed, except void and callable | |
--- | |
php artisan make:controller --model=Video VideoController | |
php artisan make:controller --invokable CreateVideoController | |
Resource: | |
php artisan make:controller --model=Video --resource VideoController | |
API: | |
php artisan make:controller --model=Video --api VideoController | |
Route::apiResource() only creates routes for index, store, show, update and destroy while | |
Route::resource() also adds a create and edit route which don't make sense in an API context. | |
--- | |
Interesting. Route::get /anything here gives back a view. | |
Route::get('/{any}', function () { | |
return view('vueapp'); | |
})->where('any', '.*'); | |
--- | |
resource: if I don't want to be wrapped. | |
public function boot() | |
{ | |
JsonResource::withoutWrapping(); | |
} | |
--- | |
debugbar : | |
composer require barryvdh/laravel-debugbar --dev | |
--- | |
Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel: | |
solution: | |
Change the group permission for the folder | |
sudo chown -R w3cert /home/w3cert/.composer/cache/repo/https---packagist.org | |
and the Files folder too | |
sudo chown -R w3cert /home/w3cert/.composer/cache/files/ | |
I'm assuming w3cert is your username, if not change the 4th parameter to your username. | |
If the problem still persists try | |
sudo chown -R w3cert /home/w3cert/.composer | |
I've encountered this a couple of times, but just realised that this may be a consequence of running self-update as root: $ sudo composer self-update , which may have been the cause of why the ~/.composer folder and all its contents change owner. Just chown -R your ~/.composer back to yourself | |
--- | |
after pluck which gives back an array we shopuld use ->first(); | |
$county = DB::table('wsh_co_county')->where('cty_code', $city->cit_cty_code)->get()->pluck('cty_name')->first(); | |
--- | |
failure during install a lumen 5 app. | |
(doing :composer update, and npm install & npm run dev) | |
Downloading binary from https://github.com/sass/node-sass/releases/download/v4.9.0/linux-x64-83_binding.node | |
Cannot download "https://github.com/sass/node-sass/releases/download/v4.9.0/linux-x64-83_binding.node": | |
HTTP error 404 Not Found | |
solution: | |
npm uninstall node-sass | |
npm install node-sass | |
then npm install & npm run dev | |
--- | |
failure: | |
on install a lumen 5 app on php 7.4 | |
Trying to access array offset on value of type null | |
solution: | |
in /vendor/illuminate/support/ServiceProvider.php | |
84 protected function loadViewsFrom($path, $namespace) | |
85 { | |
86 -- if (is_array($this->app->config['view']['paths'])) { | |
87 ++ if (isset($this->app->config['view']) && is_array($this->app->config['view']['paths'])) { | |
after this change it worked. | |
https://github.com/laravel/framework/issues/30737#issuecomment-571122633 | |
--- | |
// Let's grab a random User | |
$user = User::inRandomOrder()->first(); | |
----- | |
npm, js, vue, laravel-mix | |
failure: | |
[webpack-cli] Error: Unknown option '--hide-modules' | |
[webpack-cli] Run 'webpack --help' to see available commands and options | |
https://github.com/JeffreyWay/laravel-mix/issues/2523 | |
solution: | |
JeffreyWay's answer: | |
Remove those two options from your build script in package.json. Webpack 5 no longer supports them. | |
Or use the new Mix executable: | |
npx mix -p | |
https://github.com/JeffreyWay/laravel-mix/blob/master/docs/cli.md | |
(When it comes time to build your assets for a production environment, Mix will set the appropriate webpack options, minify your source code, and optionally version your assets based on your Mix configuration file (webpack.mix.js). To build assets for production, include the --production flag - or the alias -p - to the Mix CLI. Mix will take care of the rest! | |
npx mix --production) | |
(laravel-mix 6.doc: | |
-Support for webpack 5 | |
-New `npx mix` executable for triggering your build | |
https://github.com/JeffreyWay/laravel-mix/blob/master/docs/installation.md | |
) | |
What is difference between NPM and NPX? | |
Npm is a tool that use to install packages. Npx is a tool that use to execute packages. Packages used by npm are installed globally you have to care about pollution for the long term. Packages used by npx are not installed globally so you have to carefree for the pollution for the long term. | |
https://www.freecodecamp.org/news/npm-vs-npx-whats-the-difference/ | |
npx https://gist.github.com/Tynael/0861d31ea17796c9a5b4a0162eb3c1e8 | |
https://gist.github.com/Tynael/0861d31ea17796c9a5b4a0162eb3c1e8 | |
index.js | |
#!/usr/bin/env node | |
console.log("I was executed from a gist inside the terminal with npx!"); | |
man env -> env - run a program in a modified environment | |
--- | |
This means your vue and vue-template-compiler dependencies are out of sync. Per Vue 2's instructions, the version number for both of these dependencies must be identical. Update as needed to fix the problem: | |
solution: | |
npm update vue | |
// or | |
npm install [email protected] (both need to be identical) | |
--- | |
I'm having trouble updating/installing Mix. | |
Unfortunately, there are countless reasons why your dependencies may not be installing properly. A common root relates to an ancient version of Node (node -v) and npm (npm -v) installed. As a first step, visit http://nodejs.org and update those. | |
Otherwise, often, it's related to a faulty lock file that needs to be deleted. Give this series of commands a try to install everything from scratch: | |
rm -rf node_modules | |
rm package-lock.json yarn.lock | |
npm cache clear --force //npm cache clean no longer works because npm is self healing. | |
npm install | |
try23 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment