laravel documentation

 


Routing


Route::get('', [AuthController::class, 'index']);

Route::get('/', function () {
return view('welcome');
});

Route::get('/login', [AuthenticatedSessionController::class, 'create'])
->middleware('guest')
->name('login');

Route::resource('faq', 'ProductFaqController', [
'names' => [
'index' => 'faq',
'store' => 'faq.new',
// etc...
]
]);

Route::get('/verify-email/{id}/{hash}', [VerifyEmailController::class, '__invoke'])
->middleware(['auth', 'signed', 'throttle:6,1'])
->name('verification.verify');

Route::post('/count', function (Request $request) {
return response()->json([
'message' => $request->message,
]);
});

Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');






Controllers

  • define a route to this controller
use App\Http\Controllers\UserController;
 
Route::get('/user/{id}', [UserController::class, 'show']);
  • look at an example of a basic controller.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
class UserController extends Controller
{
/**
* Show the profile for a given user.
*
* @param int $id
* @return \Illuminate\View\View
*/
public function show($id)
{
return view('user.profile', [
'user' => User::findOrFail($id)
]);
}
}


If a controller action is particularly complex, you might find it convenient to dedicate an entire controller class to that single action. To accomplish this, you may define a single __invoke method within the controller:
          Route::get('profile', [UserController::class, 'show'])->middleware('auth');
  • controller
public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('log')->only('index');
        $this->middleware('subscribed')->except('store');
    }
VerbURIActionRoute Name
GET/photosindexphotos.index
GET/photos/createcreatephotos.create
POST/photosstorephotos.store
GET/photos/{photo}showphotos.show
GET/photos/{photo}/editeditphotos.edit
PUT/PATCH/photos/{photo}updatephotos.update
DELETE/photos/{photo}destroyphotos.destroy
php artisan make:controller PhotoController --model=Photo --resource
php artisan make:controller PhotoController --model=Photo --resource --requests



Middleware

         php artisan make:middleware EnsureTokenIsValid

                  Assigning Middleware To Routes

// Within App\Http\Kernel class...
 
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
];
  • assign middleware to a route:
            Route::get('/profile', function () {
    //
})->middleware('auth');
Route::get('/', function () {
    //
})->middleware(['first', 'second']);
use App\Http\Middleware\EnsureTokenIsValid;
 
Route::get('/profile', function () {
    //
})->middleware(EnsureTokenIsValid::class);
Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may accomplish this using the $middlewareGroups property of your HTTP kernel.
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
 
    'api' => [
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];
  • assign many middleware to a route at once
Route::get('/', function () {
    //
})->middleware('web');
 
Route::middleware(['web'])->group(function () {
    //
});



Migration



          php artisan make:migration create_users_table
#The --table and --create options may also be used to indicate the name of the table
php artisan make:migration create_users_table --create=users
 
php artisan make:migration add_votes_to_users_table --table=users
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFlightsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('airline');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('flights');
}
}
  • migrate
php artisan migrate --force
If you created more migrations and they are not migrated yet, to run only a specific migration use this:
php artisan migrate --path=/database/migrations/full_migration_file_name_migration.php

php artisan migrate:rollback
rollback the last five migrations
php artisan migrate:rollback --step=5
migrate:reset command will roll back all of your application's migrations
php artisan migrate:reset
CommandDescription
$table->bigIncrements('id');Auto-incrementing UNSIGNED BIGINT (primary key) equivalent column.
$table->bigInteger('votes');BIGINT equivalent column.
$table->binary('data');BLOB equivalent column.
$table->boolean('confirmed');BOOLEAN equivalent column.
$table->char('name', 100);CHAR equivalent column with an optional length.
$table->date('created_at');DATE equivalent column.
$table->dateTime('created_at');DATETIME equivalent column.
$table->dateTimeTz('created_at');DATETIME (with timezone) equivalent column.
$table->decimal('amount', 8, 2);DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
$table->double('amount', 8, 2);DOUBLE equivalent column with a precision (total digits) and scale (decimal digits).
$table->enum('level', ['easy', 'hard']);ENUM equivalent column.
$table->float('amount', 8, 2);FLOAT equivalent column with a precision (total digits) and scale (decimal digits).
$table->geometry('positions');GEOMETRY equivalent column.
$table->geometryCollection('positions');GEOMETRYCOLLECTION equivalent column.
$table->increments('id');Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column.
$table->integer('votes');INTEGER equivalent column.
$table->ipAddress('visitor');IP address equivalent column.
$table->json('options');JSON equivalent column.
$table->jsonb('options');JSONB equivalent column.
$table->lineString('positions');LINESTRING equivalent column.
$table->longText('description');LONGTEXT equivalent column.
$table->macAddress('device');MAC address equivalent column.
$table->mediumIncrements('id');Auto-incrementing UNSIGNED MEDIUMINT (primary key) equivalent column.
$table->mediumInteger('votes');MEDIUMINT equivalent column.
$table->mediumText('description');MEDIUMTEXT equivalent column.
$table->morphs('taggable');Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR equivalent columns.
$table->multiLineString('positions');MULTILINESTRING equivalent column.
$table->multiPoint('positions');MULTIPOINT equivalent column.
$table->multiPolygon('positions');MULTIPOLYGON equivalent column.
$table->nullableMorphs('taggable');Adds nullable versions of morphs() columns.
$table->nullableTimestamps();Alias of timestamps() method.
$table->point('position');POINT equivalent column.
$table->polygon('positions');POLYGON equivalent column.
$table->rememberToken();Adds a nullable remember_token VARCHAR(100) equivalent column.
$table->smallIncrements('id');Auto-incrementing UNSIGNED SMALLINT (primary key) equivalent column.
$table->smallInteger('votes');SMALLINT equivalent column.
$table->softDeletes();Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes.
$table->softDeletesTz();Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes.
$table->string('name', 100);VARCHAR equivalent column with a optional length.
$table->text('description');TEXT equivalent column.
$table->time('sunrise');TIME equivalent column.
$table->timeTz('sunrise');TIME (with timezone) equivalent column.
$table->timestamp('added_on');TIMESTAMP equivalent column.
$table->timestampTz('added_on');TIMESTAMP (with timezone) equivalent column.
$table->timestamps();Adds nullable created_at and updated_at TIMESTAMP equivalent columns.
$table->timestampsTz();Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns.
$table->tinyIncrements('id');Auto-incrementing UNSIGNED TINYINT (primary key) equivalent column.
$table->tinyInteger('votes');TINYINT equivalent column.
$table->unsignedBigInteger('votes');UNSIGNED BIGINT equivalent column.
$table->unsignedDecimal('amount', 8, 2);UNSIGNED DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
$table->unsignedInteger('votes');UNSIGNED INTEGER equivalent column.
$table->unsignedMediumInteger('votes');UNSIGNED MEDIUMINT equivalent column.
$table->unsignedSmallInteger('votes');UNSIGNED SMALLINT equivalent column.
$table->unsignedTinyInteger('votes');UNSIGNED TINYINT equivalent column.
$table->uuid('id');UUID equivalent column.
$table->year('birth_year');YEAR equivalent column.
Below is a list of all the available column modifiers
ModifierDescription
->after('column')Place the column "after" another column (MySQL)
->autoIncrement()Set INTEGER columns as auto-increment (primary key)
->charset('utf8')Specify a character set for the column (MySQL)
->collation('utf8_unicode_ci')Specify a collation for the column (MySQL/SQL Server)
->comment('my comment')Add a comment to a column (MySQL)
->default($value)Specify a "default" value for the column
->first()Place the column "first" in the table (MySQL)
->nullable($value = true)Allows (by default) NULL values to be inserted into the column
->storedAs($expression)Create a stored generated column (MySQL)
->unsigned()Set INTEGER columns as UNSIGNED (MySQL)
->useCurrent()Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value
->virtualAs($expression)Create a virtual generated column (MySQL)

#change method allows you to modify some existing column
#let's increase the size of the name column from 25 to 50

Schema::table('users', function (Blueprint $table) {
$table->string('name', 50)->change();
});
#modify a column to be nullable
Schema::table('users', function (Blueprint $table) {
$table->string('name', 50)->nullable()->change();
});
#Renaming Columns
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');
});
#Dropping Columns
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('votes');
});
#drop multiple columns from a table
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['votes', 'avatar', 'location']);
});



#create new migration to change existing table column(s).
php artisan make:migration update_products_table
Then you should do this inside up() method in your new migration:

#update
Schema::table('products', function (Blueprint $table) {
$table->string('color', 10)->change();
});


#add
Schema::table('blogs', function (Blueprint $table) {
$table->string('details');
});


Available Command Aliases

CommandDescription
$table->dropRememberToken();Drop the remember_token column.
$table->dropSoftDeletes();Drop the deleted_at column.
$table->dropSoftDeletesTz();Alias of dropSoftDeletes() method.
$table->dropTimestamps();Drop the created_at and updated_at columns.
$table->dropTimestampsTz();Alias of dropTimestamps() method.


CommandDescription
$table->primary('id');Adds a primary key.
$table->primary(['id', 'parent_id']);Adds composite keys.
$table->unique('email');Adds a unique index.
$table->index('state');Adds a plain index.
$table->spatialIndex('location');Adds a spatial index. (except SQLite)
To rename an index
$table->renameIndex('from', 'to')

Dropping Indexes

CommandDescription
$table->dropPrimary('users_id_primary');Drop a primary key from the "users" table.
$table->dropUnique('users_email_unique');Drop a unique index from the "users" table.
$table->dropIndex('geo_state_index');Drop a basic index from the "geo" table.
$table->dropSpatialIndex('geo_location_spatialindex');Drop a spatial index from the "geo" table (except SQLite).





Eloquent ORM

         
           
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
//
}


<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'my_flights';
}

protected $primaryKey = 'flight_id';
use App\Models\Flight;
foreach (Flight::all() as $flight) {
echo $flight->name;
}

$flights = Flight::where('active', 1)
->orderBy('name')
->take(10)
->get();

$flights = Flight::where('destination', 'Paris')->get();

use App\Models\Flight;
// Retrieve a model by its primary key...
$flight = Flight::find(1);
// Retrieve the first model matching the query constraints...
$flight = Flight::where('active', 1)->first();
// Alternative to retrieving the first model matching the query constraints...
$flight = Flight::firstWhere('active', 1);


use App\Models\Flight;
$flight = Flight::find(1);
$flight->name = 'Paris to London';
$flight->save();

Mass Updates
Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);


$deleted = Flight::where('active', 0)->delete();



  • retrieve the data from the database
$posts=Post::all();  
$posts=Post::find(2); 
$posts=Post::where('id',2)->first();  
$posts=Post::where('id',1)->value('title');  
$post=new Post;  
$post->title='Nishka';  
$post->body='QA Analyst';  
$post->save();  
$post=Post::find(2);  
$post->title='Haseena';  
$post->body='Graphic Designer';  
$post->save(); 
Post::create(['title'=>'Harshita','body'=>'Technical Content Writer']);  
Post::where('id',1)->update(['title'=>'Charu','body'=>'technical Content Writer']);  
$post=Post::find(1);  
$post->delete();  
Post::destroy(2);  
Post::destroy([3,4]);   //destroy more than one row
Post::where('id',5)->delete(); 
Post::find(1)->delete();  
Post::withTrashed()->where('id',1)->get();  //retrieve the deleted data, we use the withTrashed() method
Post::withTrashed()->where('id',1)->restore();  //Restoring deleted/trashed data
Post::onlyTrashed()->forceDelete();  //Deleting records permanently




Setup frondend,admin,api

  • boot route set in App\Providers\RouteServiceProvider

public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
Route::middleware('web')
->namespace('App\Http\Controllers\Admin')
->prefix('admin')
->group(base_path('routes/admin.php'));
Route::middleware('web')
->namespace($this->namespace)
->prefix('webapp')
->group(base_path('routes/webapp.php'));
});
}

  • create api.php,web.php,webapp.php,admin.php in app\routes
  • you can separate  controller,middleware,resource/view