Laravel 5 Series Tutorial Three: View variable passing and blade

Source: Internet
Author: User
Tags compact

Originally from: Https://jellybool.com/post/programming-with-laravel-5-blade-views-with-var

Article series: Http://segmentfault.com/blog/jellybool

In the previous article we simply said Router,views and controllers workflow, this time I will follow the previous plan, to say the following content:

  • Passing variables to the view

  • Usage of blade templates

  • Laravel database configuration and the use of migration

  • Passing variables to the view

    When we're developing Web applications, it's not usually about writing static pages, we need to deal with data, and then the question is, how do you pass data to a view in an MVC framework? For example, we want to output a $title variable in the view of the Articlecontroller index method, in Laravel, there are several common methods:

    Using the WITH () method

    Public Function Index ()    {        $title = ' article title 1 ';        Return view (' Articles.lists ')->with (' title ', $title);    }

    With this with (' title ', $title), the first ' title ' is key, the second $title is the value, so we can output this variable in our articles/lists.blade.php:

    Refresh our Blog.dev and you'll see a page like this:

    In the blade engine, we can output variables like this:

    {{$title}}

    In fact, in the blade engine, {{$title}} will be parsed like this output , but here the {{}} symbol will output the data as is, such as you will $title written as:

    Public Function Index ()    {        $title = ' article title 1 ';        Return view (' Articles.lists ')->with (' title ', $title);    }

    This time you use {{$title}} output, you will see something like this:

    If you want to render the $title as a page element, you need to write this:

    {!! $title!}

    The {{}} and {!!!!} Here are the most basic uses of blade, which we'll use very much, and I'll talk about Blade's usage in detail later.

    Directly to the view () pass parameter

    When you use this method, you can write:

    Public Function Index ()    {        $title = ' article title 1 ';        Return view (' articles.lists ', [' title ' = + $title]);    

    Refresh the page and you'll still see the same output. Here's what you need to say if you pass multiple variables, such as:

    Public Function Index ()    {        $title = ' article title 1 ';        $intro = ' Introduction to Article I ';        Return view (' articles.lists ', [                                        ' title ' = = $title,                                        ' introduction ' = ' $intro                                        ]);    }

    In the passed array:

    [' title ' = $title, ' introduction ' + $intro]

    Each key is used as a variable in a view, and value is used as a variable. So in the view we need this output:

    {!! $title!}

    {{$introduction}}

    This should be written as {{$introduction}} instead of {{$intro}}.

    Using the Compact

    This is written using the compact:

    Public Function Index ()    {        $title = ' article title 1 ';        $intro = ' Introduction to Article I ';        Return view (' Articles.lists ', Compact (' title ', ' intro '));    }

    The compact () string can be the name of a variable, and multiple variable names are separated by commas. At this point, pay attention to changing the view's variable output.

    These are the methods commonly used in laravel to transfer variables to the view, choose a way you like and stick to this kind of writing, I am using the third kind.

    Basic usage of Blade

    The above content introduces a little bit of blade syntax, here we introduce blade, say the following a few more commonly used:

    @yield () @extends () @if () and @unless () @foreach ()

    @yield () and @extends () are usually used by the layouts to achieve what we usually call the layout: in the process of web development, we put some common parts such as headers, footer, etc. directly in a view file, and then use the use of direct inheritance ( Using @extends) is possible, for example, we create a app.blade.php under the resources/views/folder:

        
     
          
     
          
     
          Laravel 5 Tutorials    
     
              @yield (' content ')    
     
                          
      
       
      
    • Laravel 5 Blog

    Write so some content, CSS this href= "/css/all.css", need us to manually under Public/folder to create css/folder, and create all.css this file, for JS src= "/js/all.js" is also the same, These two files are prepared in advance for the beautification of the subsequent pages.

    Notice the syntax of @yield (' content '), which means that there is a content area where a page inherits the app.blade.php, and then the page dynamically changes the contents of the @yield (' content '). For example we are in articles/lists.blade.php, we inherit the app.blade.php:

    @extends (' app ') @section (' content ')

    {!! $title!}

    {{$intro}}

    Here the first line of @extends (' app ') is to declare that this page inherits from App.blade.php, that is, our articles/lists.blade.php can use the all.css and all.js files, and then @section (' Content ') is the @yield (' content ') for app.blade.php, which indicates that @yield (' content ') when rendering loading articles/lists.blade.php This section will be replaced by the following content:

    {!! $title!}

    {{$intro}}

    @if () is typically used to determine whether something is displayed in the view based on certain conditions, such as we can "be bored" to try this:

    Public Function Index ()    {        $first = ' jelly ';        $last = ' bool ';        Return view (' Articles.lists ', compact (' first ', ' last '));    

    In the views file, we use the @if ():

    {{$first}}

    {{$last }}

    @endif @endsection

    Refresh to see the output of the page, the value of $last.

    The above @if (), there is a label that can be used is @unless (), @unless () can be understood as if (!), that is, if not this understanding is OK.

    @foreach () is used for cyclic output variables, such as:

    Public Function Index ()    {        $first = [' Jelly ', ' bool '];        Return view (' Articles.lists ', compact (' first '));    

    We pass an array to the view, and then we can use the @foreach () loop to output:

    @extends (' app ') @section (' content ') @foreach ($first as $name)    

    {{$name}}

    @endforeach @endsection

    Refresh the page and you'll see the results of the loop:

    For more information on blade, you can refer to the documentation:

    Http://laravel.com/docs/5.1/blade

    Database configuration for Laravel

    This section prepares you for the next section.

    Laravel configuration files are in the project directory under the config/folder, here is the Blog/config folder, you can open this folder to see that you have a lot of configuration files: such as mail.php (Configure the mail delivery service) and database.php (configuration database), here we are to see this database.php configuration file:

    ' Connections ' = [        ' mysql ' + ['            driver '    = ' mysql ',            ' host '      = ' env ' (' db_host ', ' localhost '),            ' database '  = env (' db_database ', ' Forge '),            ' username '  = env (' Db_username ', ' Forge '),            ' password '  = env (' Db_password ', '),            ' charset ' = '   utf8 ',            ' collation ' = > ' utf8_unicode_ci ',            ' prefix '    = = ', ' strict ' and    false,        ]        //...        ]

    Open the file, you can see inside just return simply PHP array just, we are only concerned about connections this array at present. The above code does not give all the database configuration, you can see for yourself, because bloggers are using MySQL, so here will give the configuration of MySQL, other databases you can refer to, the subsequent textbook blogger will still use MySQL.

    The configuration mentioned here is basically the configuration of the following four variables:

    ' Host '      = env (' db_host ', ' localhost '),///if the. env file does not have a db_host configuration, then take localhost, followed by ' database '  = env (' Db_database ', ' Forge '), ' username '  = env (' db_username ', ' Forge '), ' password '  = env (' Db_password ', ' '),

    The env () method here is to read the config entry in the. env (located in blog/.env) file.

    Open this file, you can see some common configuration, including debug mode and development environment, you can also see the following several of us need to operate the options:

    Db_host=localhostdb_database=homesteaddb_username=homesteaddb_password=secret

    Since I am using the Homestead development environment here, I have the above configuration (homestead Default username and password for homestead and secret), if you are directly using PHP artisan serve this way to open the service to develop, Modify your configuration accordingly.

    Why should laravel take such a configuration? A big reason might be to consider the security and convenience of the file, so that when we need to push the code to coding or github, we can directly ignore the. env file without worrying about our core information being leaked. When deploying the application, we can create an. env file directly on the server, and write the corresponding configuration item on the OK.

    So, as soon as we properly configure the information, we connect to the database, of course, you have to create a homestead database first.

    Using migration

    After the database is connected, we need to create the corresponding data table, you may have to manually create the data table before using Laravel, such as our blog project, you will go to the database manually create a articles data table, but in Laravel project, I highly recommend you to use migration, so what is the benefit? In fact, you can think of migration as a database version management tool, like Git for our project file version management, you can rollback, you can reset, etc., it gives you a code implementation and command line combination way to manage your database, if you are in blog/ Directory, command line execution PHP artisan, you can see a lot of command line, below these are the rollback and reset we talked about here:

    Red box These basic is more commonly used, if I have not persuaded to use migration here, then we will go through this process:

    First, we create a migration file that defines the schema of a table, and the command line executes:

    PHP artisan make:migration create_articles_table--create= ' articles '

    After smooth execution, we will get a migration file, this file is located under database/migrations/, open this folder, you can see Laravel originally have two migration files, Users table and Password-reset table, we do not currently have these two files in this project. So you can simply delete and open the migration file we just generated: create_articles_table this file

    Public function up ()    {        schema::create (' articles ', function (Blueprint $table) {            $table->increments (' Id ');            $table->timestamps ();        });    }    /**     * Reverse the migrations.     *     * @return void     *    /Public Function down ()    {        Schema::d rop (' articles ');    }

    There are two methods: up () and down (). The Up () method is called when executing PHP artisan migrate, which creates a articles data table, while the down () method is executed in PHP artisan migrate:rollback usage, This data table will be deleted directly from articles.

    However, it is not urgent to implement PHP artisan migrate here, we also need to add several fields for articles:

    Public function up ()    {        schema::create (' articles ', function (Blueprint $table) {            $table->increments (' ID ');//primary key self            -increment $table->string (' title ');            $table->text (' intro ');            $table->text (' content ');            $table->timestamp (' published_at ');            $table->timestamps (); Automatically created two fields: Created_at and Updated_at        });    }

    Here our intro field is an introduction to the article, the Published_at field is the publication date of the article, so it is very good for us to write a blog, you can control the publication date of the blog, because there are some I have written but not yet published date, Do not want to let users see the article I can use Published_at to control. After that, let's take a look at PHP artisan migrate:

    Then, articles this table is created successfully.

    This time you may not realize the benefits of migration, imagine the following two scenarios:

    1. How can we get the same database table design when team members pull down our code when team development? Should we export the table and import it once for each member? This is obviously not wise enough, if you use the migration, just a line of command, Direct ' PHP artisan migrate ', you can get the same database table. 2. If this time we find articles this table has a field is wrong, such as our intro field is wrong, it should be named introduction, this time, what do we do? Directly manually change the database table? So back to the first scenario, your team members also need to change manually? This is obviously not the way we like it, and this time, migration's advantage comes

    For example, here's a demonstration of how to solve the second scenario:

    We only need command line execution:

    PHP Artisan Migrate:rollback

    Then modify the intro field of the Up () method:

    $table->text (' Introduction ');

    Then execute PHP artisan migrate:

    Gaocheng, see the documentation for more features:

    Http://laravel.com/docs/5.1/migrations

    Next section

    It seems that the above configuration database link has not been used, do not worry, my next article will be specific to the use of eloquent, this is a very representative part of the Laravel, I hope you can learn a little something.

    Happy Hacking

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.