search
HomePHP FrameworkLaravelHow to learn laravel framework in php (novice beginner)

How to learn laravel framework in php (novice beginner)

关于laravel的介绍就不讲了,总之laravel是款比较强大的框架,它是国外框架所以在安装的上面可能比较麻烦。

laravel的安装

首先安装laravel之前要安装composer,如果是linux系统即可直接下载安装,下载完后不能安装记得修改下文件权限用命令chmod,这边主要讲下window下如何使用composer这个工具。 

首先百度搜索中国composer镜像,就可以找到composer config -g repositories.packagist composer http://packagist.phpcomposer.com这条命令,运行cmd在命令行运行上面的命令,就可以下载composer工具,

下载成功后可以看到composer文件底下有个composer.json文件这是一个配置文件,打开配置文件写明php版本信息和要下载的laravel信息,格式如下:

  {
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "repositories": [
        {"type": "composer", "url": "http://packagist.phpcomposer.com"},
        {"packagist": false}
    ]
}```

配置好之后输入composer install  进行安装laravel,这边要比较注意的是安装目录的路径问题,如果你想安装在d盘底下就在把命令行切到d目录底下进行安装(在此操作之前要配置好环境变量)。 

laravel的目录结构介绍 

   安装完的第一次肯定是要想怎么去运行它,很简单,直接进入public文件就可以打开一个开始页面,如果在本地的话那就是localhost/laravelproject/public,就可以运行。

接下来介绍下laravel目录结构,首先介绍下public的index.php文件 里面主要是加载了开始文件然后才能成功运行laravel,具体的两个文件你可以在根目录下bootstrap文件夹中找到。现在看下app中的结构: 

How to learn laravel framework in php (novice beginner)
view中主要放的是视图文件(创建文件时要用到blade模板,比如创建test.blade.php,laravel中是结合blade模板引擎来调用视图模板)

controller放的是控制器(手动创建时记得要用composer 命令进行更新)

config中主要是配置文件(比如配置数据库时要用到database.php文件)

models主要是放模型(也就是数据库的表)

routes则是路由配置,

filters则是过滤器。 

laravel是怎么运行的 

刚学习时肯定是要先尝试下如何运行这个laravel,首先手动创建一个controller,文件命名为TestController.php,然打开命令行进入项目的根目录下 执行 composer dumpautoload,里面内容可以模仿homeController.php。

然后编辑routes.php文件,将原来的Route::GET(‘/’,function()…);修改为Route::Get(‘/’,’TestController@showWelcome’); 然后运行也会跳到laravel欢迎界面。

如果Route::Get(‘test’,’TestController@showWelcome’);则在网站根目录下后面直接增加test就可以访问了,到了这里应该明白了怎么到Controller,Controller怎么到View了。  

laravel数据库配置

这边用到的是mysql,进行了简单的配置

'mysql' => array(
'driver'    => 'mysql',
'host'      => 'localhost',
'database'  => 'oss',
'username'  => 'root',
'password'  => '',
'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix'    => '',
)

laravel的数据库使用

数据表比较多时且数据表的前缀不一样,则可以先配置模型model,在models文件夹中建立一个文件要与表名一样的php文件,内容如下:
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
    use UserTrait, RemindableTrait;
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = &#39;users&#39;;
    /**
     * The attributes excluded from the model&#39;s JSON form.
     *
     * @var array
     */
    protected $hidden = array(&#39;password&#39;, &#39;remember_token&#39;);
}

即可以直接使用 User ::all() 查询所有结果  ,User::find(2)查询一个,Post::findOrFail(2)  

如果没找到就会返回错误,Post::save()、Post::where()->find()、Post::add()、Post::delete()

数据库的简便操作:  

DB::table(‘tablename’)->insert([
        插入多个时要再加一个数组
        [&#39;title&#39;=>&#39;title&#39;,&#39;name&#39;=>&#39;name&#39;]
        [&#39;title&#39;=>&#39;title&#39;]
        [&#39;title&#39;=>&#39;title&#39;]
        ])
        插入时要想得到ID
        DB::table(&#39;tablename&#39;)->insertGetId([&#39;title&#39;=>&#39;titles&#39;])
        更新数据要有ID
        DB::table(&#39;tablename&#39;)->where(&#39;id&#39;,1)->update([&#39;title&#39;=>&#39;titles&#39;])
        删除数据
        DB::table(&#39;tablename&#39;)->where(&#39;id&#39;,1)->delete();
        查询数据
        DB::table(&#39;tablename&#39;)->get();  得到全部的值
        DB::table(&#39;tablename&#39;)->get([&#39;title&#39;]); 只查询title的值
        DB::table(&#39;tablename&#39;)->first();  只拿第一个
        DB::table(&#39;tablename&#39;)->orderBy(&#39;id&#39;,&#39;desc&#39;)->first(); 根据id排序
        DB::table(&#39;tablename&#39;)->where(&#39;id&#39;,&#39;!=&#39;,2)->get(); 不等于2
        DB::table(&#39;tablename&#39;)->where(&#39;id&#39;,&#39;!=&#39;,2)->where(&#39;id&#39;,&#39;>&#39;,5)->get(); 可以使用多个where
        DB::table(&#39;tablename&#39;)->where(&#39;id&#39;,&#39;!=&#39;,2)->OrWhere(&#39;id&#39;,&#39;>&#39;,5)->get(); 或者
        DB::table(&#39;tablename&#39;)->whereBetween(&#39;id&#39;,[2,5])->get();  闭包之间
        DB::table(&#39;tablename&#39;)->whereIn(&#39;id&#39;,[2,5,9])->get();
        DB::table(&#39;tablename&#39;)->whereNotIn(&#39;id&#39;,[2,5,9])->get();
        DB::table(&#39;tablename&#39;)->whereNull(&#39;id&#39;)->get();  为空的话就可以查询出来
        DB::table(&#39;tablename&#39;)->take(3)->get();  只查询3个
        DB::table(&#39;tablename&#39;)->limit(3)->get();  只查询3个
        DB::table(&#39;tablename&#39;)->skip(2)->take(3)->get();  只查询3个跳过第二个
        DB::table(&#39;tablename&#39;)->where(&#39;id&#39;,&#39;!=&#39;,2)->pluck(&#39;title&#39;); 只返回它的title
        DB::table(&#39;tablename&#39;)->count();  有多少条记录
        DB::table(&#39;tablename&#39;)->max(&#39;id&#39;);
        DB::table(&#39;tablename&#39;)->min(&#39;id&#39;);
        DB::table(&#39;tablename&#39;)->avg(&#39;id&#39;);
        DB::table(&#39;tablename&#39;)->sum(&#39;id&#39;);

多表关联 

在Post中定义 

public function comment(){ return $this->hasMany(&#39;Comment&#39;,&#39;post_id&#39;) }
 正向关联   一对多   一对一是hasOne

在Comment中定义

public function post(){ return $this->belongsTo(&#39;Post&#39;,&#39;post_id&#39;) }
  反向关联

取得关联值

    Post::find(2)->comment  就可以得到Comment这张表的内容   //这样查询一个是可以的  查询多个就要设置预载入
            查询多个
                Post::with(&#39;comment&#39;)->get();
                Post::with([&#39;comment&#39;=>function($query){$query->where(&#39;id&#39;,&#39;>&#39;,2)}])->get();  加条件

感谢大家的阅读,希望大家有所收益。

本文转自:https://blog.csdn.net/Happy_CSDN/article/details/49363219

推荐教程:《php教程

The above is the detailed content of How to learn laravel framework in php (novice beginner). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Using Laravel: Streamlining Web Development with PHPUsing Laravel: Streamlining Web Development with PHPApr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Laravel: An Introduction to the PHP Web FrameworkLaravel: An Introduction to the PHP Web FrameworkApr 19, 2025 am 12:15 AM

Laravel is a modern PHP framework that provides a powerful tool set, simplifies development processes and improves maintainability and scalability of code. 1) EloquentORM simplifies database operations; 2) Blade template engine makes front-end development intuitive; 3) Artisan command line tools improve development efficiency; 4) Performance optimization includes using EagerLoading, caching mechanism, following MVC architecture, queue processing and writing test cases.

Laravel: MVC Architecture and Best PracticesLaravel: MVC Architecture and Best PracticesApr 19, 2025 am 12:13 AM

Laravel's MVC architecture improves the structure and maintainability of the code through models, views, and controllers for separation of data logic, presentation and business processing. 1) The model processes data, 2) The view is responsible for display, 3) The controller processes user input and business logic. This architecture allows developers to focus on business logic and avoid falling into the quagmire of code.

Laravel: Key Features and Advantages ExplainedLaravel: Key Features and Advantages ExplainedApr 19, 2025 am 12:12 AM

Laravel is a PHP framework based on MVC architecture, with concise syntax, powerful command line tools, convenient data operation and flexible template engine. 1. Elegant syntax and easy-to-use API make development quick and easy to use. 2. Artisan command line tool simplifies code generation and database management. 3.EloquentORM makes data operation intuitive and simple. 4. The Blade template engine supports advanced view logic.

Building Backend with Laravel: A GuideBuilding Backend with Laravel: A GuideApr 19, 2025 am 12:02 AM

Laravel is suitable for building backend services because it provides elegant syntax, rich functionality and strong community support. 1) Laravel is based on the MVC architecture, simplifying the development process. 2) It contains EloquentORM, optimizes database operations. 3) Laravel's ecosystem provides tools such as Artisan, Blade and routing systems to improve development efficiency.

Laravel framework skills sharingLaravel framework skills sharingApr 18, 2025 pm 01:12 PM

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

The difference between laravel and thinkphpThe difference between laravel and thinkphpApr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Laravel user login function listLaravel user login function listApr 18, 2025 pm 01:06 PM

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

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),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.