Skip to content

Instantly share code, notes, and snippets.

@shotaK
Last active September 10, 2015 12:11
Show Gist options
  • Save shotaK/bf6605edad30e67f6285 to your computer and use it in GitHub Desktop.
Save shotaK/bf6605edad30e67f6285 to your computer and use it in GitHub Desktop.
Laravel 5
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ghostblog
DB_USERNAME=admin
DB_PASSWORD=pass
// show artisan commands
php artisan
// run local web server for phpstorm
php artisan serve
// -------- CONTROLLERS -------- \\
// show options for specific commands
php artisan help make:controller
// create new controller called NameMeController
php artisan make:controller NameMeController
// create new plain/empty controller called NameMePlainController
php artisan make:controller NameMePlainController --plain
// -------- MIGRATIONS -------- \\
// migrate all migrations
php artisan migrate
// Rollback/remove all migrations
php artisan migrate:rollback
// show options for creating migrations
php artisan help make:migration
// create migration called create_articles_table, DB table name will be articles
php artisan make:migration create_articles_table --create="articles"
// -------- MODELS -------- \\
// Create a model called Article
php artisan make:model Article
// -------- Form Request Validation -------- \\
// Create new Form Request Validation
php artisan make:request StoreBlogPostRequest
// Install Laravel via Composer
composer create-project laravel/laravel --prefer-dist
//composer dump-autoload won’t download a thing. It just regenerates the list of all classes that need to be included in the
//project (autoload_classmap.php). Ideal for when you have a new class inside your project.
//Ideally, you execute composer dump-autoload -o , for a faster load of your webpages. The only reason it is not default, is //because it takes a bit longer to generate (but is only slightly noticable)
composer dump-autoload
// Expose model DB data to view
$articles = Article::all();
return view('pages.articles') ->with('articles', $articles);
// get variable parameter from route and expose data
public function showSingle($id) {
$article = Article::findOrFail($id);
return view('articles.showOne') -> with('article', $article);
}
//getting input data and save it to database
Article::create($request->all());
return redirect('articles');
// extended form of getting input data and save it to database
$title = $request->input('title');
$body = $request->input('body');
$published_at = $request->input('published_at');
$article = new Article();
$article->title = $title;
$article->body = $body;
$article->published_at = $published_at;
Article::create($article->toArray());
return redirect('articles');
// Inject Form Request Validator into controller method
public function store(StoreBlogPostRequest $request) {
}
// Validate input data into controller
$this->validate($request, [
'title' => 'required|min:3',
'body' => 'required',
'published_at' => 'required|date'
]);
// Update Article
public function update($id, StoreBlogPostRequest $request) {
$article = Article::findOrFail($id);
$article->update($request->all());
return redirect('articles');
}
'mysql' => [
'unix_socket' => '/opt/lampp/var/mysql/mysql.sock',
]
// Start tinker CLI
php artisan tinker
// Insert Article into database
$article = new App/Article;
$article -> title = 'Article title';
$article -> body = 'Article body';
$article -> save();
// Show all rows of Article from DB
App\Article::all()
// Find article row in DB with id equals 1
App\Article::find(1);
// select * from articles where body = 'something'
$article = App\Article::where('body', 'something')->get();
// Insert Article into database
$article = App\Article::create(['title' => 'New Article', 'body' => 'New body', 'published_at' => Carbon\Carbon::now()]);
// Migration table schema which keeps integrity between different tables
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->longText('body');
$table->timestamp('published_at');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
// Create flash message in controller method
Session::flash('flash_message', 'Article has been created successfully');
// echod out the flash message from view
@if(Session::has('flash_message'))
<div class="alert alert-success">{{Session::get('flash_message')}}</div>
@endif
// Apply middleware to controller
function __construct()
{
$this->middleware('auth', ['only' => 'create']);
}
// Define table for Model
protected $table = 'articles';
// Define fillable fields in Model
protected $fillable = [
'title',
'body',
'published_at'
];
// Define guarded fields in Model
protected $guarded = [
'id',
'other_column'
];
// parent toMany relationship
public function articles() {
return $this->hasMany('App/Article');
}
// Child relationship
public function user() {
return $this->belongsTo('App/User');
}
// IMPORTANT: when getting relational data eager loading should br used:
// http://laravel.com/docs/5.0/eloquent#eager-loading
$time = TimeEntry::with('user')->get();
// validation data
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required',
'published_at' => 'required|date'
];
}
Make front-end available from views folder.
Route::get('/', function () {
return view('index');
});
// A route group allows us to have a prefix, in this case api
Route::group(array('prefix' => 'api'), function () {
Route::resource('tour', 'TourController', ['only' => ['index', 'show']]);
Route::group(array('prefix' => 'admin'), function () {
Route::resource('tour', 'TourController');
});;
});
// Route with variable option
Route::get('/articles/{id}', 'pages\ArticlesController@showSingle');
// Resource route
Route::resource('articles', 'pages\ArticlesController');
// A route group allows us to have a prefix, in this case api
Route::group(array('prefix' => 'api'), function()
{
Route::resource('time', 'TimeEntriesController');
Route::resource('users', 'UsersController');
});
// Create seeder file
php artisan make:seeder UsersTableSeeder
// Load seed classes
composer dump-autoload
// send records to database
php artisan db:seed
// Add records to the specific table
public function run()
{
// We want to delete the table if it exists before running the seed
DB::table('users')->delete();
$seederData = array(
['email' => '[email protected]', 'password' => Hash::make('secret')],
['email' => '[email protected]', 'password' => Hash::make('secret')],
['email' => '[email protected]', 'password' => Hash::make('secret')],
['email' => '[email protected]', 'password' => Hash::make('secret')],
);
foreach($seederData as $item) {
User::create($item);
}
}
// add seeder file to seeding starter file.
public function run()
{
Model::unguard();
$this->call('CommentTableSeeder');
}
// make url with variable id
<a href="{{ url('/article', $article->id) }}">
// get all errors in views
@if(count($errors)>0)
<ul class="alert alert-danger">
@foreach($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
@endif
// Form with put action
{!! Form::open(array('method' => 'put', 'action' => array('pages\ArticlesController@update', $article->id))) !!}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment