Alle Werkzeuge
Kostenlos

Eine durchsuchbare, druckbare Laravel-Referenz — Artisan, Routing, Eloquent, der Query-Builder, Migrationen, Blade, Validierung und Collections. Kostenlos.

Artisan CLI

14
php artisan serve
Start the local development server
php artisan make:model Post -mcr
Model with migration, controller and resource
php artisan make:controller PostController
Generate a new controller class
php artisan make:migration create_posts_table
Create a new migration file
php artisan migrate
Run pending database migrations
php artisan migrate:fresh --seed
Drop all tables, re-migrate and seed
php artisan db:seed
Run the database seeders
php artisan tinker
Open an interactive REPL shell
php artisan route:list
List all registered routes
php artisan optimize
Cache config, routes and views
php artisan queue:work
Process jobs on the queue
php artisan schedule:work
Run the scheduler in the foreground
php artisan storage:link
Symlink storage to the public path
php artisan key:generate
Generate the application key

Routing

13
Route::get('/users', [UserController::class, 'index'])
Define a GET route to a controller
Route::post('/users', [UserController::class, 'store'])
Define a POST route
Route::put('/users/{user}', [UserController::class, 'update'])
Define a PUT route
Route::patch('/users/{user}', [UserController::class, 'update'])
Define a PATCH route
Route::delete('/users/{user}', [UserController::class, 'destroy'])
Define a DELETE route
Route::get('/users/{id}', $fn)
Required route parameter
Route::get('/users/{id?}', $fn)
Optional route parameter
Route::get('/profile', $fn)->name('profile')
Name a route for URL generation
Route::get('/admin', $fn)->middleware('auth')
Attach middleware to a route
Route::resource('posts', PostController::class)
Register RESTful resource routes
Route::prefix('admin')->group(function () {})
Group routes under a URI prefix
Route::controller(PostController::class)->group($fn)
Group routes to one controller
Route::fallback($fn)
Handle unmatched routes (404)

Controllers

10
php artisan make:controller PostController --resource
Resource controller with CRUD methods
public function __invoke(Request $request)
Single-action invokable controller
public function index() {}
List resources (resource method)
public function store(Request $request) {}
Persist a new resource
public function show(Post $post) {}
Show one resource (route model binding)
public function __construct(PostService $svc) {}
Inject a dependency via the constructor
return view('posts.index', ['posts' => $posts])
Return a Blade view with data
return response()->json($data)
Return a JSON response
return redirect()->route('posts.index')
Redirect to a named route
return back()
Redirect to the previous page

Eloquent ORM

14
Post::all()
Get every record
Post::find($id)
Find a record by primary key
Post::where('active', true)->first()
First record matching a condition
Post::create(['title' => 'Hi'])
Mass-assign and persist a record
$post->update(['title' => 'Edited'])
Update an existing model
$post->delete()
Delete a model instance
Post::firstOrCreate(['slug' => $slug])
Find or create a matching record
Post::updateOrCreate($attrs, $values)
Update if found, otherwise create
Post::with('author')->get()
Eager load a relationship
public function comments() { return $this->hasMany(Comment::class); }
One-to-many relationship
public function author() { return $this->belongsTo(User::class); }
Inverse one-to-many relationship
protected $fillable = ['title', 'body'];
Mass-assignable attributes
protected function casts(): array { return ['published_at' => 'datetime']; }
Attribute casts (casts() method)
Post::onlyTrashed()->restore()
Restore soft-deleted records

Query builder

13
DB::table('users')->get()
Fetch all rows from a table
DB::table('users')->where('votes', '>', 100)->get()
Filter rows by a condition
DB::table('users')->join('posts', 'users.id', '=', 'posts.user_id')
Inner join two tables
DB::table('users')->orderBy('name')->get()
Order results by a column
DB::table('orders')->groupBy('status')->get()
Group rows by a column
DB::table('users')->select('name', 'email')->get()
Select specific columns
DB::table('users')->insert(['name' => 'Sam'])
Insert a new row
DB::table('users')->where('id', 1)->update(['votes' => 1])
Update matching rows
DB::table('users')->pluck('email')
Get a single column as a collection
DB::table('users')->count()
Count matching rows
DB::table('users')->where('id', 1)->exists()
Check whether rows exist
DB::table('users')->paginate(15)
Paginate the results
DB::table('users')->chunk(100, $fn)
Process results in chunks

Migrations & schema

12
Schema::create('posts', function (Blueprint $table) {})
Create a new table
$table->id()
Auto-incrementing primary key
$table->string('title')
VARCHAR column
$table->integer('votes')
Integer column
$table->boolean('active')
Boolean column
$table->timestamps()
created_at and updated_at columns
$table->foreignId('user_id')->constrained()
Foreign key with a constraint
$table->string('note')->nullable()
Allow NULL values
$table->boolean('active')->default(true)
Set a default value
$table->index('slug')
Add an index to a column
$table->unique('email')
Add a unique constraint
$table->dropColumn('votes')
Drop a column

Blade templates

14
@if ($ok) ... @elseif ($x) ... @else ... @endif
Conditional rendering
@foreach ($posts as $post) ... @endforeach
Loop over a collection
@forelse ($posts as $post) ... @empty ... @endforelse
Loop with an empty fallback
{{ $variable }}
Echo escaped output
{!! $html !!}
Echo unescaped raw HTML
@extends('layouts.app')
Inherit from a layout
@section('content') ... @endsection
Define a layout section
@yield('content')
Output a section in a layout
@include('partials.nav')
Include another view
<x-alert type="error" />
Render a Blade component
@csrf
CSRF token field for forms
@auth ... @endauth
Show content to authenticated users
@can('update', $post) ... @endcan
Authorization gate check
{{ $loop->index }}
Loop variable inside @foreach

Validation

12
$request->validate(['title' => 'required'])
Validate request data inline
'email' => 'required|email'
Required and valid email rule
'name' => 'required|max:255'
Required with a max length
'email' => 'unique:users,email'
Must be unique in a table
'age' => 'nullable|integer|min:18'
Optional integer with a minimum
'role' => ['required', Rule::in(['admin', 'user'])]
Constrain to allowed values
php artisan make:request StorePostRequest
Generate a Form Request class
public function rules(): array { return [...]; }
Form Request validation rules
public function authorize(): bool { return true; }
Form Request authorization
public function messages(): array { return [...]; }
Custom validation messages
$validator = Validator::make($data, $rules)
Create a validator manually
$request->validated()
Get only validated input

Requests & responses

10
request()->input('name')
Retrieve an input value
request()->query('page')
Retrieve a query string value
request()->all()
Get all input as an array
request()->only(['name', 'email'])
Get a subset of input
request()->has('name')
Check if input is present
response()->json(['ok' => true])
Return a JSON response
redirect()->route('home')->with('status', 'Saved')
Redirect with a flash message
back()->withInput()
Redirect back keeping old input
abort(404)
Throw an HTTP exception
abort_if($user->banned, 403)
Conditionally abort the request

Collections

13
$collection->map(fn ($x) => $x * 2)
Transform each item
$collection->filter(fn ($x) => $x > 0)
Keep matching items
$collection->each(fn ($x) => $x->save())
Run a callback per item
$collection->pluck('name')
Extract one column
$collection->reduce(fn ($c, $x) => $c + $x, 0)
Reduce to a single value
$collection->sortBy('created_at')
Sort by a key
$collection->groupBy('status')
Group items by a key
$collection->where('active', true)
Filter by a key/value pair
$collection->first()
Get the first item
$collection->contains('name', 'Sam')
Check for a matching item
$collection->sum('price')
Sum a column
$collection->flatten()
Flatten nested collections
$collection->toArray()
Convert to a plain array

Auth & middleware

11
Auth::user()
Get the authenticated user
Auth::check()
Check if a user is logged in
Auth::id()
Get the authenticated user ID
Auth::login($user)
Log a user in
Auth::logout()
Log the current user out
auth()->user()
Helper for the current user
Route::get('/home', $fn)->middleware('auth')
Protect a route with auth
Gate::allows('update', $post)
Check an authorization gate
$user->can('update', $post)
Check ability against a policy
php artisan make:policy PostPolicy --model=Post
Generate an authorization policy
php artisan make:middleware EnsureTokenIsValid
Generate a middleware class

Helpers & misc

12
config('app.name')
Read a config value
env('APP_DEBUG', false)
Read an environment variable
route('posts.show', $post)
Generate a URL to a named route
url('/dashboard')
Generate a fully qualified URL
asset('css/app.css')
URL for a public asset
old('email')
Retrieve old flashed input
now()->addDays(7)
Current Carbon timestamp
Str::slug('My Title')
String helper (slugify)
collect([1, 2, 3])->sum()
Create a collection from an array
cache()->remember('key', 60, $fn)
Cache a value for a duration
dd($value)
Dump a value and die
Storage::put('file.txt', $contents)
Write a file to storage

Kein Eintrag passt zu „:q“.


Über Laravel-Spickzettel

Dieser Laravel-Spickzettel verdichtet die Framework-Oberfläche, mit der Sie täglich arbeiten: Artisan-CLI, Routing, Controller, Eloquent-ORM, den Query Builder, Migrationen und Schema, Blade-Templates, Validierung, Requests und Responses, Collections, Auth und Middleware sowie Hilfsfunktionen.

Laravel hat eine ausdrucksstarke, aber breite API — die exakte Eloquent-Beziehungssignatur, ein Migrations-Spaltenmodifikator, ein Validierungsregelname, eine Collection-Methode —, und jede Zeile hier zeigt den echten Aufruf mit einer knappen Beschreibung, sodass sich der Spickzettel wie das Framework in Kurzform liest.

Er ist kostenlos und läuft vollständig im Browser. Filtern Sie jedes Snippet live mit dem Suchfeld, springen Sie über das fixierte Inhaltsverzeichnis zwischen Abschnitten, kopieren Sie Code mit einem Klick und drucken Sie den Spickzettel für eine Framework-Referenz beim Programmieren aus.

So verwenden Sie Laravel-Spickzettel

  1. Überfliegen Sie die zwölf Abschnitte, von Artisan-CLI und Routing über Eloquent-ORM bis Hilfsfunktionen & Sonstiges.
  2. Suchen Sie nach einem Begriff wie migration, hasMany oder validate, um den Spickzettel live zu filtern.
  3. Springen Sie über die fixierte Seitenleiste zu einem Abschnitt wie Blade-Templates oder Collections.
  4. Klicken Sie auf ein Snippet oder sein Kopiersymbol, um das PHP in Ihr Projekt zu kopieren.
  5. Drucken Sie den Spickzettel für eine Offline-Laravel-Referenz.

Häufig gestellte Fragen

Zwölf Abschnitte: Artisan-Befehle, Routing, Controller, Eloquent, den Query Builder, Migrationen und Schema, Blade, Validierung, Requests und Responses, Collections, Auth und Middleware sowie allgemeine Hilfsfunktionen.

Ja. Der Artisan-Abschnitt listet die Generator-, Migrations-, Cache- und Wartungsbefehle auf, die Sie ständig ausführen, jeweils mit einer knappen Beschreibung, was sie erzeugen oder tun.

Ja. Der Eloquent-Abschnitt zeigt Modelldefinition, Beziehungen und Abfragemuster, und ein separater Query-Builder-Abschnitt behandelt die tiefer liegende fluent API, wenn Sie sie brauchen.

Ja. Klicken Sie auf den Code oder das beim Hover erscheinende Kopiersymbol in einer Zeile, und er wird sofort in Ihre Zwischenablage kopiert.

Ja, sie ist kostenlos, durchsuchbar, druckbar und ohne Konto verfügbar.


Beliebte Suchen
laravel cheat sheet artisan commands list eloquent query methods laravel routing syntax laravel validation rules blade directives list laravel migration schema methods laravel collections methods
Brauchen Sie Hilfe?
Ein Problem mit diesem Tool gefunden? Sagen Sie es unserem Team.
Problem melden

Füge dieses kostenlose Tool zu deiner eigenen Website hinzu — kopiere den Code unten und füge ihn ein.