


Laravel5.1 database connection, database creation, model creation and controller methods, laravel5.1model_PHP tutorial
Jul 12, 2016 am 08:55 AMLaravel5.1 database connection, create database, create model and create controller method, laravel5.1model
This article describes the Laravel5.1 database connection, create database, create model and methods to create controllers. Share it with everyone for your reference, the details are as follows:
Foreword: Laravel creates a database, which can actually be created manually, such as the ancient phpmyadmin.
1. Database connection:
In the root directory (there is a .env file under laravel5.1, if not, there will be a .env.example and then modify this file into a .env file)
Open file:
Found:
DB_HOST=127.0.0.1 //連接地址不使用localhost DB_DATABASE=homestead //數(shù)據(jù)庫名稱(需要預先創(chuàng)建) DB_USERNAME=root //登錄名 DB_PASSWORD= //密碼
I have modified this to match my local environment.
2. Data table creation
cmd created:
Cut to the storage directory of laravel 5.1 (project directory)
Then run:
php artisan make:migration create_articles_table --create=articles
You will get the created file: D:laravel-v5.1.11databasemigrations
If there is an error about the database at this time, please check whether the database connection is correct. I was stuck here all morning (my phpmyadmin was modified by me, and the password was entered casually, but it turned out to be empty, so it was difficult to connect to the database. I can’t get in if I just enter the password, but phpmyadmin can)
Open the newly created file and add fields:
public function up() { Schema::create('articles', function (Blueprint $table) { $table->increments('id');// 主鍵 自增 $table->string('title'); $table->text('intro'); $table->text('content'); $table->timestamp('published_at'); $table->timestamps(); // 自動創(chuàng)建的兩個字段:created_at 和 updated_at }); }
Then execute:
php artisan migrate
The table will be automatically created
3. Create modal
Execution:
php artisan make:model Article
The Article.php file will be created under the app directory. I don’t know exactly how to use this model, I will update it later
4. Controller
I created it manually here. (It feels very nonsense. I personally feel that phpmyadmin or navicat can create a database). I created the ArtilcesController.php controller under D:laravel-v5.1.11appHttpControllersArticles (I use the controller method under the sub-file. See the previous article for specific operations. ).
Code:
namespace App\Http\Controllers\Articles; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Article;//這個必須有,引入model,不然無法獲取數(shù)據(jù)庫數(shù)據(jù) class ArticlesController extends Controller{ public function index(){ // $articles = Article::with('category')->latest()->paginate(15); $articles = Article::all();//獲取所有數(shù)據(jù) //print_r($articles); $name = array( 0=>array( "name"=>"123" ), ); return view('articles.index', compact('articles'));//映射 } }
Readers who are interested in more information about Laravel can check out the special topics on this site: "Introduction and Advanced Tutorial on Laravel Framework", "Summary of PHP Excellent Development Framework", "Basic Tutorial on Getting Started with Smarty Templates", "php Date and Time" Usage Summary", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php mysql database operation introductory tutorial" and "php common database operation skills summary"
I hope this article will be helpful to everyone’s PHP program design based on the Laravel framework.
Articles you may be interested in:
- Introduction to Laravel 5 framework learning routes, controllers and views
- ThinkPHP, ZF2, Yaf, Laravel framework routing competition
- Laravel 4 Basic Tutorial: Views, Namespaces, and Routing
- Learn the road to Laravel with me
- Laravel framework routing configuration summary and setup tips
- Laravel Detailed explanation of usage examples of Trait
- Laravel’s method of implementing automatic dependency injection of constructors
- Making APP interface (API) based on laravel
- Experience of learning PHP framework Laravel
- Get the previous and next data in Laravel
- Laravel routing setting and sub-routing setting example analysis

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

InLaravel,policiesorganizeauthorizationlogicformodelactions.1.Policiesareclasseswithmethodslikeview,create,update,anddeletethatreturntrueorfalsebasedonuserpermissions.2.Toregisterapolicy,mapthemodeltoitspolicyinthe$policiesarrayofAuthServiceProvider.

Defining a method (also known as an action) in a controller is to tell the application what to do when someone visits a specific URL. These methods usually process requests, process data, and return responses such as HTML pages or JSON. Understanding the basic structure: Most web frameworks (such as RubyonRails, Laravel, or SpringMVC) use controllers to group related operations. Methods within each controller usually correspond to a route, i.e. the URL path that someone can access. For example, there may be the following methods in PostsController: 1.index() – display post list; 2.show() – display individual posts; 3.create() – handle creating new posts; 4.u

The main role of the controller in Laravel is to process HTTP requests and return responses to keep the code neat and maintainable. By concentrating the relevant request logic into a class, the controller makes the routing file simpler, such as putting user profile display, editing and deletion operations in different methods of UserController. The creation of a controller can be implemented through the Artisan command phpartisanmake:controllerUserController, while the resource controller is generated using the --resource option, covering methods for standard CRUD operations. Then you need to bind the controller in the route, such as Route::get('/user/{id

Laravelprovidesrobusttoolsforvalidatingformdata.1.Basicvalidationcanbedoneusingthevalidate()methodincontrollers,ensuringfieldsmeetcriterialikerequired,maxlength,oruniquevalues.2.Forcomplexscenarios,formrequestsencapsulatevalidationlogicintodedicatedc

CachinginLaravelsignificantlyimprovesapplicationperformancebyreducingdatabasequeriesandminimizingredundantprocessing.Tousecachingeffectively,followthesesteps:1.Useroutecachingforstaticrouteswithphpartisanroute:cache,idealforpublicpageslike/aboutbutno

The .env file is a configuration file used in the Laravel project to store environment variables. It separates sensitive information from code and supports multi-environment switching. Its core functions include: 1. Centrally manage database connections, API keys and other configurations; 2. Call variables through env() or config() functions; 3. After modification, the configuration needs to be refreshed before it takes effect; 4. It should not be submitted to version control to prevent leakage; 5. Multiple .env files can be created for different environments. When using it, you should first define variables and then call them in conjunction with configuration file to avoid direct hard coding.

In Laravel tests, the assert method is used to verify that the application is running as expected. Common assert methods include assertTrue(), assertFalse(), assertEquals(), and assertNull(), which are used to verify that the values ??in the logic meet expectations. For HTTP responses, you can use assertStatus(), assertRedirect(), assertSee(), and assertJson() to verify the response status and content. Database verification can be used through assertDatabaseHas() and assertDatabaseMissing

EloquentORMisLaravel’sbuilt-inobject-relationalmapperthatsimplifiesdatabaseinteractionsusingPHPclassesandobjects.1.Itmapsdatabasetablestomodels,enablingexpressivesyntaxforqueries.2.Modelscorrespondtotablesbypluralizingthemodelname,butcustomtablenames
