search
HomeBackend DevelopmentPHP TutorialFunctionality for Laravel framework template loading and assigning variables and simple routing

This article mainly introduces the Laravel framework template loading, variable allocation and simple routing functions. It analyzes the related principles, operating skills and precautions of the Laravel framework template loading, variable allocation and simple routing functions in the form of examples. Friends who need it can Refer to the examples below

This article describes the Laravel framework template loading, variable allocation and simple routing functions. Share it with everyone for your reference, the details are as follows:

As the world's number one PHP framework, it is imperative to learn Laraver. Although ThinkPHP is popular in China, it is always good for you to know one more framework.

Through the previous article's method of quickly installing the Laravel framework on a local virtual machine, we have been able to successfully install Laravel

After installation, there is a routes.php in the directory laravel\app\Http File, the point is, this is the routing file that controls the entire site.

Route::get('/', function () {
 return view('welcome');
});

The above is a simple route, if you bind the route and enable it For the pseudo-static of apche and nginx, you can access it through the domain name http:xxx.com/

Then a beautiful Laraver interface will appear.

So what does return refer to? It is to return a View files, Laraver's view files are under laravel\resources\views. Laraver stipulates that the view file name ends with .blade.php. Usually we need a lot of views when doing projects, so we can under views It is possible to define many directories and then place them in

return view('index.index');

. It represents the view file in the directory below the view. Many frameworks are like this, but the file name is The naming will be different.

The above is just a simple route that calls an anonymous function, so how to use it in conjunction with control.

Laraver’s controller directory is in laravel\app\Http \Controllers Below, you can create a controller through the

php artisen make:controller UseController

command that comes with Laraver, and the commonly used method, if we output the content under the index method of the control

If you need a controller without any definition, please add the --plain parameter after it

But how to access it? Please look at the code

Route::get('/','UseController@index');

This example binds the current directory '/' to the index method under the controller UseController

Route::get('/about','UseController@about');

Another example is this, we can use http:xxx.com/about to access the specified control method

There are many get here, such as needing to use post, etc. , I will contact you one after another in the future.

Then there is another problem, is it very troublesome to define a route every time, so Laraver allows us to use implicit controllers

Route::controller('User','UserController');

This is to access any method under User without specifying a route, but in this case remember to follow the following format in the method

Specify delivery methods such as get or post Index, the first method name should be capitalized. If passing parameters, it should be in function ($a), and write .

in the function. Classify the variable to the blade template. Note here that it is different from the thinkphp framework. We commonly use it. The following methods:

1:

If

$name = 'php artisen';

you can

return view('index')=>with('name',$name);

Then use {{ $name }} in the template to parse the assigned variables.

The above method is equivalent In

return view('index',['a'=>'b']);

However, when parsing in the template, you still need to use {{ $a }} to allocate variables

2:

If

$articles = DB::table('user')->get();

the result of using database query

is also I saw someone recommending this way of writing

return view('user.dashboard.index', compact('articles'));

But this is all personal operating habits.

When using the compact function In this case, we can directly traverse

$data = ['a','b','c'];

in the case of using

@foreach($data as $v)

Next, you can directly use {{ $v }} to traverse

3:

Of course we usually allocate arrays or objects Come over. So generally use the following method

You can

return view('index',$data);

It should be noted that the default is PDO in database.php under config 'fetch' => PDO::FETCH_ASSOC, the default is FETCH_CLASS as the object format

So when traversing, if the default settings are not modified, the traversal will be {{ $a-> ;v }}This kind, if it is an array, it is {{ $a['v'] }}

About escaping and not escaping during loading Meaning, for example:

$a = &#39;<span style="color:red">this Laravel</span>&#39;;

##{{ $a }} Output

<span style="color:red">this Laravel</span>

{{!! $aa !!}} Output the

&#39;this Laravel&#39;

knowledge points in red font, if loaded The variable is a one-dimensional array, which is output as {{ $key name}} in the template. For example:

$data[&#39;a&#39;] = &#39;this&#39;;
$data[&#39;n&#39;] = &#39;that&#39;;
return view(&#39;sites.my&#39;,$data);

is

## in the template.

#
<p>我是$data分配过来的变量{{ $a }}</p>

This works, you can’t use it

$data[&#39;a&#39;]

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于Laravel中重写资源路由自定义URL的实现方法

Laravel5框架中向视图传送array的学习

The above is the detailed content of Functionality for Laravel framework template loading and assigning variables and simple routing. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

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

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor