This article brings you relevant knowledge about laravel, which mainly introduces some basic knowledge, including how to install Laravel, routing, validators, views, etc., the following is Let's take a look, hope it helps everyone.
[Related recommendations: laravel video tutorial]
1. Install laravle
1. Install composer
2. Execute the command:
##composer create-project laravel/laravel project folder name-- prefer-dist
app
: The core code of the application
bootstrap
: An app.php file that guides the framework, a cache directory (including routing and cache files), and the framework startup file. Generally, it does not move.
config
: All configuration files
database
: The migrations directory can generate data tables .
public
: Entry file storage location, and static resources (similar to tp)
resources
:
routes
: All route definitions applied
tests
: Available for Unit test
vendor
: All composer dependency packages
3. First introduction to routing
1. Several common requests
- Route::get( u r l , , url, url,callback);
- Route::post( u r l , , url, url,callback);
- Route::put( u r l , , url, url,callback);
- Route::delete( u r l , , url, url,callback);
2. Match the specified request method
Route::match(['get','post'],'/',function(){});
3. Configure any request method
Route::any('/home', function () { });
4. Add must to the route Fill in the parameters
Route::get('/home/{id}', function ($id) { echo 'id为:'.$id;});
5. Add optional parameters to the route
Route::get('/home/{id?}', function ($id = '') { echo 'id为:'.$id;});
6. Pass the get parameter in the form of ?
Route::get('/home', function () { echo 'id为:'.$_GET['id'];});
7. Add an alias to the route
Route::any('/home/index', function () { echo '测试';})->name('hh');
8. Set routing group
For example, the following route:
- /admin/login
- /admin/index
- /admin /logout
- /admin/add
If adding them one by one is more troublesome, they have a common difference, they all have the /admin/ prefix, and you can set up a routing group Add the group:
Route::group(['prefix'=>'admin'], function () { Route::get('test1', function () { echo 'test1'; }); Route::get('test2', function () { echo 'test2'; });});
You can now access it through /admin/test1.
9. Routing configuration controller
The controller can build a front desk and a back desk:
命令行创建路由:
php artisan make:controller Admin/IndexController
基本路由建立:
Route::get('test/index','TestController@index');
分目录路由建立:
Route::get('/admin/index/index','Admin\IndexController@index');
四、laravel验证器
引入:use Illuminate\Support\Facades\Validator
$param = $request->all();$rule = [ 'name'=>'required|max:2',];$message = [ 'required' => ':attribute不能为空', 'max' => ':attribute长度最大为2'];$replace = [ 'name' => '姓名',];$validator = Validator::make($param, $rule, $message,$replace);if ($validator->fails()){ return response()->json(['status'=>0,'msg'=>$validator->errors()->first()]);}
五、控制器获取用户输入的值
在控制器中如果要使用一个类,例如use Illuminate\Http\Request
,就可以简写为use Request
。
但是需要在config目录下的app.php配置文件中加入:
'aliases' => [ 'App' => Illuminate\Support\Facades\App::class, 'Arr' => Illuminate\Support\Arr::class, 'Artisan' => Illuminate\Support\Facades\Artisan::class, 'Auth' => Illuminate\Support\Facades\Auth::class, 'Blade' => Illuminate\Support\Facades\Blade::class, 'Request' => Illuminate\Support\Facades\Request::class, ],
1、获取用户单个输入值:
Input::get('id')
2、获取用户输入的所有值:
Input::all()
打印出来的是数组
关于dd(dump+die)
3、获取用户输入指定的值:
Input::only(['id','name'] //只接收id,其余不接受
4、获取用户输入指定值之外的值:
Input::except(['name'] //不接收name,其余都接收
5、判断某个值是否存在
Input::has('name') //存在返回true 不存在返回false 其中0返回true
六、视图的创建与使用
1、视图的创建
视图也可分目录管理:
控制器语法:
return view('home/test');
也可写为:
return view('home.test');
2、变量映射
控制器中:
return view('home/test',['day'=>time()]);
视图中:
{{$day}}
其中控制器中变量映射有三种:
- view(模板文件,数组)
- view(模板文件)->with(数组)
- view(模板文件)->with(数组)->with(数组)
了解一下compact数组。
3、视图渲染
3.1 foreach的使用
控制器中:
public function index(){ $arr = [ 0 => [ 'name' => 'tom', 'age' => '12', ], 1 => [ 'name' => 'bby', 'age' => '13', ] ]; return view('home/test',['data'=>$arr]); }
视图中:
@foreach($data as $k=>$v) 键:{{$k}} 值:{{$v['name']}} <br>@endforeach
3.2 if的使用
@if(1==2) 是的 @else 不是的 @endif
4、视图之间的引用
@include('welcome')
七、模型的创建与使用
1、创建模型的命令
php artisan make:model Model/Admin/Member
此时,就会在app目录内创建:
2、模型基本设置
<?phpnamespace App\Model\Admin;use Illuminate\Database\Eloquent\Model;class Member extends Model{ //定义表名 protected $table = 'student'; //定义主键 protected $primaryKey = 'id'; //定义禁止操作时间 public $timestamps = false; //设置允许写入的字段 protected $fillable = ['id','sname'];}
3、模型数据添加
方式一:
$model = new Member(); $model->sname = '勒布朗'; $res = $model->save(); dd($res);
方式二:
$model = new Member(); $res = $model->create($request->all()); dd($res);
4、模型的表连接
//查询客户与销售顾问的客资列表$data = Custinfo::select(['custinfo.*', 'customers.name']) ->join('customers', 'customers.id', '=', 'custinfo.cust_id') ->where($where) ->get() ->toArray();
5、简单模型关联一对一
<?phpnamespace App\Model\Admin;use Illuminate\Database\Eloquent\Model;class Phone extends Model{ //定义表名 protected $table = 'phone'; //定义主键 protected $primaryKey = 'id'; //定义禁止操作时间 public $timestamps = false; //设置允许写入的字段 protected $fillable = ['id','uid','phone'];}
<?phpnamespace App\Model\Admin;use Illuminate\Database\Eloquent\Model;class Member extends Model{ //定义表名 protected $table = 'student'; //定义主键 protected $primaryKey = 'id'; //定义禁止操作时间 public $timestamps = false; //设置允许写入的字段 protected $fillable = ['id','sname']; /** * 获取与用户关联的电话号码记录。 */ public function getPhone() { return $this->hasOne('App\Model\Admin\Phone', 'uid', 'id'); }}
//对象转数组 public function Arr($obj) { return json_decode(json_encode($obj), true); } public function index(){ $infoObj = Member::with('getPhone')->get(); $infoArr = $this->Arr($infoObj); print_r($infoArr); }
八、日志
1、自定义日志目录
在config
目录下的logging.php
中的channels
配置:
'custom' => [ 'driver' => 'single', 'path' => storage_path('logs/1laravel.log'), 'level' => 'debug', ]
控制器中:
$message = ['joytom','rocker'];Log::channel('custom')->info($message);
九、迁移文件
建立一个迁移文件:php artisan make:migration create_shcool_table
会在database\migrations
下创建一个文件:
在up方法中增加如下代码:
<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;class CreateShcoolTable extends Migration{ /** * Run the migrations. * * @return void */ public function up() { Schema::create('shcool', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('school_name','20')->notNull()->unique(); $table->tinyInteger('status')->default(1); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('shcool'); }}
更详细的生成SQL方法请参考:数据迁移文件常用方法速查表
写好SQL文件以后,执行:php artisan migrate
将会生成数据表,其中操作日志将记录在这个表中:
php artisan migrate:rollback
:回滚最后一次的迁移操作, 删除(回滚)之后会删除迁移记录,并且数据表也会删除,但是迁移文件依旧存在,方便后期继续迁移(创建数据表)。
【相关推荐:laravel视频教程】
The above is the detailed content of Summarize and organize the basic knowledge of Laravel. For more information, please follow other related articles on the PHP Chinese website!

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment