0% found this document useful (0 votes)
338 views

Laravel Beginners Full Course

Uploaded by

busrazcvik
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
338 views

Laravel Beginners Full Course

Uploaded by

busrazcvik
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

Create Laravel Project

There are several ways to create Laravel project locally.

Install using composer


composer create-project laravel/laravel D:/LaravelProje/cars_ecommerce

Install with Laravel Installer


Install Laravel installer and create new project with Laravel installer (which
internally still uses composer). Bu şekilde yapmıyorum.

# Install Laravel Installer globally


composer global require laravel/installer

# Create new project with Laravel Installer


laravel new [YOUR_PROJECT_NAME]

Install with Sail


Laravel Sail is a tool that streamlines Laravel development by providing a
Docker-based local development environment with just a few simple
commands.

💡 You need to have docker installed to be able to use this method.


curl -s https://laravel.build/[YOUR_PROJECT_NAME] | bash

Using Laravel Herd


You can also create new project using Laravel Herd. You just need to go to
Sites menu item and then add new Site.

Start the project


To start the Laravel project you have to navigate into project’s root directory
using terminal and execute

php artisan serve


If you see the output that Laravel was started you will also see the
address: http://127.0.0.1:8000. Open that in your browser and you will see
brand new Laravel project installed.

Artisan Challenge

Challenge 1
Execute artisan command to get the list of artisan commands
in queue namespace.
The result should be similar to this.

Php artisan queue help

Challenge 2
Execute artisan command to get all details of migrate:refresh command.
The result should be similar to this.

Php artisan migrate:refresh --help

Define a Basic Route With Basic View File


ℹ️Whenever you define a route make sure the following `Route` class is properly imported at
the top of the routes. If it is not imported, import it with the following code. `use Illuminate\
Support\Facades\Route;`
Open routes/web.php file and at the end of the file put the following code.

// routes/web.php
Route::get("/about", function() {
return view("about");
});

Create resources/views/about.blade.php and put the following HTML


there.

<h1>Hello, This course is on Laravel 11</h1>


<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit, nulla
quisquam! Expedita porro quos, omnis nulla reprehenderit sequi quas fugiat
ullam itaque repudiandae, eaque sapiente totam minus. Quasi, dignissimos
tempore.</p>
Now access the URL http://127.0.0.1:8000/about and you should see the
following result

Request Lifecycle

In Laravel the request starts


on public/index.php. index.php includes vedor/autoload.php file, then it
creates application in bootstrap/app.php. The application itself loads
configuration files and initiates service providers.

Service providers in Laravel prepare and configure the application, handling


tasks like registering services, event listeners, middleware, and routes. They
ensure both core and custom features are set up correctly, making the
application ready to function efficiently.

Then the request is passed to Router.

The Router takes the request, finds the corresponding function to execute and
executes that. Optionally there might be middleware registered on the route.
We will talk more about middlewares, but in a nutshell the purpose of the
middleware is to execute code before the request reaches to the action and
possible block the code. After this the controller will send the response back to
the user, or if the middleware is registered, the response will be passed to
middleware first and then returned to user.

İstek gönderildikten sonra ilk olarak index.php dosyasına gider. Ardından


yükleme sağlanması için vendor/autoload.php. Uygulamanın oluşturulması için
bootstrap/app.php. ardından laravel tarafından sağlanan servis sağlayıcıları
devreye girer. Sonrasın bu istek routerlara gider.

Configuration
Laravel 11 comes with several configuration files out of the box. Many
configuration options are available in .env file as well.

If you don’t need to modify these configuration files feel free to delete them,
the default files exist in vendor folder in Laravel’s core and they will be used
from core.

In order to create configuration files for different services in Laravel 11 you


have to publish the configuration file you need by artisan command: php
artisan config:publish

This will give you the following screen and you need to type the configuration
file name, like: app, or broadcasting

If you know exactly which configuration file you want to publish you can
directly execute php artisan config:publish [FILE_NAME].

Example: php artisan config:publish app

Let’s say you published cors configuration file. The content of the file looks
like this.

<?php

return [

/*

|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration

|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource
sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/

'paths' => ['api/*', 'sanctum/csrf-cookie'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => false,

];

If you want to only customize a single configuration line (Ex:


Change supports_credentials into true), you can just leave only that option
and delete others. So your final config/cors.php file will look like this.

<?php

return [

'supports_credentials' => true,

];

dump()
Prints the variable information and gives you the location from which it is
printed.

$person = [
"name" => "Zura",
"email" => "[email protected]",
];
dump($person);

dd()
Prints the exact same output as dump() , but stops the script execution.

$person = [
"name" => "Zura",
"email" => "[email protected]",
];
dd($person);

ddd()
Throws exception and start debugging from the line it is written.

Basic Routing
The default routes file is located in routes/web.php.

The default routes for console commands is located in routes/console.php.

Available request methods


Laravel 11 supports the following request methods when defining route

Route::get($uri, $callback); //bilgiyi almak için


Route::post($uri, $callback);//bilgiyi oluşturmak için(create)
Route::put($uri, $callback); //bilgiyi update etmek için
Route::patch($uri, $callback); //bu da update etmek için
Route::delete($uri, $callback); //silmek için
Route::options($uri, $callback);//spesifik bir şeyin bilgilerini almak için

Route that matches multiple request methods


Route::match(['get', 'post'], '/', function () {
// ...
});

Laravelde birden fazla metodu listeleyerek kullanan routelar tanımlamak da mümkün.

yukarıdaki örnekte route, get ve post metodunu kullanıyor. Fonksiyonun içine yazılan

şey iki metot için de çalışacak.

Route that matches all request methods


Route::any('/', function () {
// ...
});

Redirect routes
Route::redirect('/home', '/'); // sırasyla nereden nereye
Route::redirect('/home', '/', 301); //301 statu kodu, yukarıda yapılan
şeyle aynı
// the same as
Route::permanentRedirect('/home', '/');

View Routes
Route::view('/contact', 'contact'); bu şeklde kullanarak direkt ekrana view
da döndürebiliriz.

Route::view('/contact', 'contact', ['phone' => '+995557123456']);// eğer


istersek parametre de gönderebiliriz.

Required Parameters
This code defines a route with required parameter id

Route::get("/product/{id}", function(string $id) {


return "Product ID=$id"; // idnin ne tarz bir veri olacağını herhangi
bir şekilde tanımlamadığımız için integer string her türlü veri çalışır.
Veri çubuğuna ne yazarsak yazalım oraya gideriz.
});

Matches the following routes

 /product/1
 /product/test

 /product/{any_string}

You can also define multiple route parameters in the following way.

Route::get("{lang}/product/{id}", function(string $lang, string $id) {


return "Product Lang=$lang. ID=$id"; // urlin ilk kısmı language kodunu
içerir, ilgili dildeki ürünün idsinin girilmesiyle o dili ve id’yi
döndürür.
});

Matches the following routes

 /en/product/1

 /ka/product/test

 /{any_string}/product/{any_string}

Route::get("{lang}/product/{id}/review/{reviewId}", function(string $lang,


string $id, string $reviewId) {
return "Product Reviews Lang=$lang. ID=$id. ReviewID=$reviewId";
});

Matches the following routes

 /en/product/1/review/123

 /ka/product/test/review/foo

 /{any_string}/product/{any_string}/review/{any_string}

Route Optional parameters


⚠️You must make `$category` variable of the callback function as optional as well, with
default value. Otherwise it will fail.
Route::get('/posts/{category?}', function(string $category = null) {
// ...
return "Render Posts";
}); // burada categoryi optional olarak tanımladığımız için bu category
urlde olmadığı zamanlarda bu değişken de urla verilmeyebilir. Bunu
engellemek için bir de default değer tanımlıyoruz, null. Böyle yapmazsak
hata alırız.

Route Parameter Validation


You can define what should be the format of each route parameter.

Route::get("/product/{id}", function(string $id) {


// ...
})->whereNumber("id"); // Only digits // sadece sayı basması ve txtleri
kabul etmemesi için önceki yazdığımız koda böyle bir şart ekliyoruz.

Matches the following routes

 /product/1

 /product/01234

 /product/56789

Does not match!!

 /product/test

 /product/123test

 /product/test123

username must only contain uppercase and lowercase letters

Route::get('/user/{username}', function(string $username) {


// ...
})->whereAlpha('username');//kullanıcı adı sadece alfabe karakterleri
içerebilir.

Matches the following routes

 /user/zura

 /user/thecodeholic

 /user/ZURA

Does not match!!

 /user/zura123

 /user/123ZURA

username must only contain uppercase, lowercase letters and digits

Route::get('/user/{username}', function(string $username) {


// ...
})->whereAlphaNumeric('username');

Matches the following routes

 /user/zura123

 /user/123thecodeholic

 /user/ZURA123

Does not match!!

 /user/zura.123

 /user/123-ZURA

 /user/123_ZURA

You can also define constrains for several route parameters

Route::get("{lang}/product/{id}", function(string $lang, string $id) {


// ...
})
->whereAlpha("lang") // Only uppercase and lowercase letters
->whereNumber("id") // Only digits
;

Matches the following routes

 /en/product/123

 /ka/product/456

 /test/product/01234

Does not match!!

 /en/product/123abc

 /ka/product/abc456

 /en123/product/01234

lang route parameter must contain one of the provided values. Anything else
will not match the route
Route::get("{lang}/products", function(string $lang) {
// ...
})->whereIn("lang", ["en", "ka", "in"]);

Matches the following routes

 /en/products

 /ka/products

 /in/products

Does not match!!

 /de/products

 /es/products

 /test/products

Route Parameter Validation With Custom Regex


username must only contain lowercase letters

Route::get('/user/{username}', function(string $username) {


// ...
})->where('username', '[a-z]+');

lang must always be 2 letters and id must contain at least 4 digits

Route::get("{lang}/product/{id}", function(string $lang, string $id) {


// ...
})->where(["lang" => '[a-z]{2}', 'id' => '\d{4,}']);

Encoded Forward Slashes

By default Laravel allows every character to be presented in route parameter


except /. If you want / to be matched in your route parameter as well you
need to define the following ->where() on your route parameter.

Route::get('/search/{search}', function (string $search) {


return $search;
})->where('search', '.*');
Named Routes
You can also define name for each route.

Route::get("/about", function() {
// ...
})->name("about");

What is the point of assigning name to a route?

When we want to generate URLs without route names the only way to
generate URLs in our application is the following.

$aboutPageUrl = "/about"
// Use $aboutPageUrl in navigation:
// <a href="USE_IT_HERE">About</a>

Imagine that this URL is used in several places on your website:

1. In the main header navigation

2. In the footer navigation

3. And maybe in the sidebar

At some point if you decide to update the URL from /about into /about-
us you have to update it in all 3 places.

In reality it might be used in much more than just 3 places. You might miss
some of the places and did not update which leads to broken and not working
URLs.

Once, you assign name to your route you can generate routes by name.

$aboutPageUrl = route("about"); // route() function accepts name of the


route as argument
// Use $aboutPageUrl in navigation:
// <a href="USE_IT_HERE">About</a>

If you have all your URLs generated with route() function and then you
change the route from /about into /about-us

Route::get("/about-us", function() {
// ...
})->name("about");

Laravel will generate proper URLs and you will not have broken URLs.
Named route with parameter
Route::get("/{lang}/product/{id}", function(string $lang, string $id) {
// ...
})->name("product.view");

If we want to generate routes without route name

$productId = 123;
$lang = "en";
$productViewUrl = "/$lang/product/$productId";

Generate route with route name.

$productId = 123;
$lang = "en";
$productViewUrl = route("product.view", ["lang" => $lang, "id" =>
$productId]);

From the first look you see that you actually write more code, but it has great
benefits. If you update your URL pattern into this

Route::get("/p/{lang}/{id}", function(string $lang, string $id) {


// ...
})->name("product.view");

1. You don’t have to update the peace of code where you generate the
URLs.

2. At some point in your code, you might be checking what is the current
route and if you are on product view page, you might execute some
logic. With route names it’s super easy to detect what is the route of the
current request. (Will see it in later lessons).

3. Also when you want to perform redirect to a specific route, doing this
with route name is much easier.
// define a route with name "profile"
Route::get('/user/profile', function () {
// ...
})->name('profile');

Route::get("/current-user", function() {
// Generating Redirects...
return redirect()->route('profile');
// or
return to_route('profile');
});

Route Groups

Route Prefixes
Route::prefix('admin')->group(function () {
Route::get('/users', function () {
// Matches The "/admin/users" URL
});
});//prefixin içine koyudğumuz heer şey içerideki diğer routeların başına
gelecek. Mesela normalde /users ama prefix ile kulandığımızda /admin/users
şeklini alıyor. Ve /users yoluna da tarayıcıdan direkt ulaşılamıyor. Önünde
admin olmalı.

Route Name Prefixes


Route::name('admin.')->group(function () {
Route::get('/users', function () {
// Route assigned name "admin.users"...
})->name('users');
}); // bu şekilde de içeride kullandığımız her şeyin adının başına admin
atıyoruz. Users isimli route artık admin.users oluyor.

Fallback Routes
Typically when the route is not matched, Laravel will show 404 page, but if you
want to handle all unmatched routes, this is how you can do it.

Route::fallback(function () {
// Handle all unmatched routes
});

Artisan command to view existing routes

List all routes


php artisan route:list // bizim tarafımızdan ve laravel tarafından
tanımlanan tüm routelar
php artisan route:list –v //middlewares da listeler
php artisan route:list –vv //
php artisan route:list --path=api // api pathındeki routeları verir, her
projede olmayabilir.
php artisan route:list --except-vendor // sadece bizim tarafımızdan
tanımlanan routeları görmek istiyorsak.
php artisan route:list --only-vendor // sadece laravel tarafından üretilen
php artisan route:list -vv --except-vendor --path=home

Route Caching

Create cache for all routes


php artisan route:cache // routeları tanımladıktan sonra bu komutu
çalıştırmak tavsiye edilir.

Clear cache for all routes


php artisan route:clear // cache ile routlar daha hızlı yüklenir ama
kullanmak istemezsek bu şekilde temizleyebiliriz.

Basic Controllers

What is controller?
Controller is a class which is associated to one or more routes and is
responsible for handling requests of that routes. Generally controller is for
grouping similar routes together. For example: ProductController should
contain only logic associated to products, but not anything
else. CarController should not contain logic that is not associated to cars.

Generate controller with artisan


php artisan make:controller CarController

CarController.php class was generated in app/Http/Controllers folder.


This is the default content of the just generated controller in Laravel 11.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class CarController extends Controller


{
//
}

Create route and associate action


Now let’s open CarController and add method index, so that our controller
looks like this..

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CarController extends Controller


{
public function index()
{
return "Index method from CarController";
}
}

Now let’s open routes/web.php file and add new route which will be
associated to just created index method.

Route::get("/car", [\App\Http\Controllers\CarController::class, 'index']);

In the exact same way you can define other methods


in CarController and associate to new routes.

ℹ️Controller’s methods that are associated to routes are often mentioned as **actions.**
How let’s access http://127.0.0.1:8000/car into browser and you should see
the following output.

Index method from CarController

Routeların içine ne yapacaklarını raw kod şeklinde yazmak yerine belli


görevler için belirli controllerlar oluşturuyoruz. Routeları tanımlarken bu
controllerları kullanıyoruz ve ilgili controllerin içindeki ilgili metodun
kullanılmasını sağlıyoruz.

Eğer sayfanın üzerine controller dosyalarının olduğu yolu eklemezsek. Sondan


ikinci koddaki gibi route kodunun içine controllerin tum yolunu yazmamız
gerekiyor. Ama zaten vs code çoğu zaman otomatik olarak ekliyor ve bunu
kullanmamıza gerek yok. Eklememişse de sen ekle.

Route::get("/car", [CarController::class, 'index']);

Group actions by controller


If you want to associate multiple methods of your controller to routes, you can
use the controller name only once.

Route::controller(\App\Http\Controllers\CarController::class)-
>group(function () {
Route::get("/car", "index");
Route::get("/my-cars", "myCars");
Route::get("/search", "search");
});

Ya hepsini ayrı ayrı tek satırlık normal route kodu olarak yazacağız. Ya da
hepsini guruplayıp bu şekilde yazacağız. Ya da farklı url’lere de gidiyor olabilir
yukarıdaki örnekteki gibi. Sanırım amaç bir controllerle alaklı tüm routeları bir
arada tutmak. Evet controller adını bir kez kullanarak istediğimiz kadar route
oluşturmamızı sağlıyor.

Single Action Controllers


If the controller grows and becomes very large, it’s recommended practice to
split it into multiple other controllers or create Single Action Controllers.

ℹ️**Single Action Controllers** are controllers that are associated to a single route only.

Generate Single Action Controller


Open terminal and execute the following artisan command

php artisan make:controller ShowCarController --invokable

ShowCarController.php class was generated


in app/Http/Controllers folder. This is the default content of the just
generated invokable controller in Laravel 11.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ShowCarController extends Controller


{
/**
* Handle the incoming request.
*/
public function __invoke(Request $request)
{
//
}
}

__invoke method is the method that will be executed when route will be
matched. This is how we associate the controller to a route.

Route::get("/car", \App\Http\Controllers\ShowCarController::class);

Note that we only provided controller class name when defining route for /car.
We don’t need to provide methods for Single Action Controllers. Çünkü
zaten tek iş yapmakla görevli ve tek metodu var bu yüzden çağırılır çağırılmaz
sadece o işi yapıyor. Route koduna ek olarak metod adı yazmamıza gerek
kalmıyor.

A regular controller with regular methods can also have __invoke method. For
example we can modify our existing CarController and
add __invoke method. Bu şekilde kullandığımızda eğer route kısmına hiçbr
metot adı vermezsek invoke metodunu çalıştırır ama yine aynı controllerı
kullanıp içindeki diğer metodların adını route koduna eklersek bu sefer ilgili
metodu sorunsuz çalıştırır.

Aynı şekilde _invoke olarak oluşturduğun controller dosyasının içine başka bir
metod yazarsan ve yolunu verirsen çalışıyor, yol vermezsen invoke çalışıyor.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
class CarController extends Controller
{
public function __invoke(Request $request)
{
return "From __invoke";
}

public function index()


{
return "Index method from CarController";
}
}

💡 At this stage we don’t need `ShowCarController` so, delete it and delete it’s associated
route.
In routes we can use CarController in the following way.

Route::get("/car", [CarController::class, 'index']);


Route::get("/car/invokable", CarController::class);

For /car route we use regular method of the controller, but


for /car/invokable route we pass the entire controller class name and
Laravel’s router will execute __invoke method behind.

Resource Controllers
💡 Before we talk about Resource Controllers, let’s delete `CarController` delete the routes
associated to it.
In Laravel, a resource controller is a special type of controller that provides a
convenient way to handle typical CRUD (Create, Read, Update, Delete)
operations for a resource such as a database table.

Generate Resource Controller


To generate resource controller using artisan we should execute the following
command

php artisan make:controller ProductController --resource

When you generate a resource controller using Laravel's Artisan command-


line tool, it creates a controller class with predefined methods to handle
various HTTP verbs and corresponding actions:

This is how generated controller code will look like


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProductController extends Controller


{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}

/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}

/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}

/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}

/**
* Show the form for editing the specified resource.
*/
public function edit(string $id)
{
//
}

/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}

/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}

By using a resource controller, you can write cleaner and more concise code
for handling CRUD operations without having to define each route and
controller action individually. Laravel's resource controllers also integrate
seamlessly with Laravel's route model binding, making it easy to work with
model instances directly in controller methods.

Use Resource Controller in Route


Route::resource('/products', \App\Http\Controllers\
ProductController::class);
The line above will register 7 routes. You can inspect these routes if you
execute php artisan route:list in terminal. Along with other routes you
should see the following output.

Partial Resource Routes


If you want to exclude certain methods from the resource routes definition you
can provide except method after route declaration.

Route::resource('/products', \App\Http\Controllers\
ProductController::class)
->except(['destroy']);

Or if you want to only include specific routes in the declaration you can
provide only method.

Route::resource('/products', \App\Http\Controllers\
ProductController::class)
->only(['index', 'show']);

API Resource Routes


If you want to define only routes that is relevant for API and
exclude create and edit routes, which has the purpose to render HTML form
you can use apiResource method instead of resource when defining routes.

Route::apiResource('/products', \App\Http\Controllers\
ProductController::class);

If you want to even skip generating create and edit methods in the controller
you can provide --api flag to the controller generation.

php artisan make:controller CarController --api

You can also register many API resources at once if you provide array
in apiResource method.

Route::apiResource([
'/products', \App\Http\Controllers\ProductController::class,
'/cars', \App\Http\Controllers\CarController::class
]);

💡 For next lessons we don’t need `ProductController` and `CarController` so, delete them and
delete routes associated to them.
Challenge

Problem
Generate a controller with 2 methods: sum and subtract. Define
routes /sum and /subtract which will be associated to the controller
corresponding methods.

Both methods will accept tfwo arguments, both arguments should be numbers.
When accessing /sum route it should print the sum of arguments and when
accessing /subtract method it should print the difference.

Solution
Execute the following artisan command to create MathController

php artisan make:controller MathController

Then open generated MathController and add the following


methods: sum and subtract

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MathController extends Controller


{
public function sum(float $a, float $b)
{
return $a + $b;
}

public function subtract(float $a, float $b)


{
return $a - $b;
}
}

Then open routes/web.php and define routes


Route::get('/sum/{a}/{b}', [MathController::class, 'sum'])
->whereNumber(['a', 'b']);
Route::get('/subtract/{a}/{b}', [MathController::class, 'subtract'])
->whereNumber(['a', 'b']);

Now open the browser and access http://localhost:8000/sum/5/8. You should


see 13.

Then change sum into subtract in URL: http://localhost:8000/subtract/5/8.


You should see -3.

Now try to access: http://localhost:8000/sum/5/abc. You should see 404 Not


Found Page.

💡 We don’t need `MathController` any more so, delete it and delete the routes we defined in
this lesson.

Create HomeController
Create new controller for our final project

php artisan make:controller HomeController

Open HomeController and add index method

class HomeController extends Controller


{
public function index()
{
return 'index';
}
}

Now open web.php and change / route

Route::get('/', [HomeController::class, 'index'])->name('home');

Now we don’t need resources/views/welcome.blade.php file, so let’s it.

Creating and Rendering Views


Views are files that are responsible for presentation logic in your Laravel apps
and are stored in resources/views folder.

Typically views are in format of blade files


Blade is Laravel's templating engine that helps you build HTML views
efficiently. It allows mixing HTML with PHP using simple, clean syntax. Blade
supports template inheritance, enabling you to define a base layout and
extend it in other views. It provides directives with different purposes for
control flow. Blade also supports reusable components and slots.

Create a view
All blade view must have extension .blade.php .

You can create a file by hand under resources/views directory or execute the
following artisan command.

php artisan make:view index

Open just created file, delete its content and paste the following code.

<h1>Hello From Laravel Course</h1>

Now open HomeController and update its index method like this.

public function index()


{
return view("index");
}

If you open application’s home page the result will be something like this.

Rendering views from nested folders


Move your index.blade.php file into resource/views/home folder the blade
file becomes nested file in home folder. You can render it by updating
the index method like this.

Resource->views-> altına bir home klasörü oluşturup, index.blade.php


dosyamızı oraya taşıdık. Bu işlemden sonra HomeControllerdaki index
fonksiynu çalışmamaya başladı çünkü orası sadece view(‘index’), bunun
yerine tam yolunu yazmamız lazım. home.index şeklinde. Buradaki nokta
folder seperatior görevi görür.

public function index()


{
return view("home.index");
}
Php artisan make:view home.index // bu şekilde yazdığımızda ise view
altında direkt home adında bir klasör oluşturup index.blade.php dosyasını
oraya atar.

Render Views using View facade

Render with View::make()


One way to render view file is using view() function. Second way to achieve
the same thing is using View facade’s make() method.

public function index()


{
return View::make("home.index");
}

ℹ️In this case make sure you import `View` facade correctly. `use Illuminate\Support\Facades\
View;`
Bu şekilde View Facade kullanmanın bir çok avantajı var mesela aşağıdaki gibi ::first ile
kullanabiliriz. Parantez içindeki arrrayden ilk sıradakini ekrana verir, eğer ilk sıradakinde bir
sorun varsa ve ulaşılabilir değilse sıradakini verir.

Render first available view


You can use the following code in your action to render first available view.

return View::first(["index", "home.index"]);

Check if the view exists


if (!View::exists("index")) {
dump("View does not exist");
}

Yukarıda anlattığım şeyi yapmak için bir if bloğu kullanarak söz gelimi view var
mı yok mu kontrol edebiliriz.

Passing Data to Views

Option 1
public function index()
{
return view("index", [
"name" => "Zura",
"surname" => "Sekhniashvili"
]);
}

Option 2
public function index()
{
return view("index")
->with("name", "Zura")
->with("surname", "Sekhniashvili")
;
}

Access the variables in blade file like this.

<h1>Hello From Laravel</h1>


<p>My Name is {{ $name }} {{ $surname }}</p>

Open http://127.0.0.1:8000/ in your browser and you should see the following
output.

Sharing Data With All Views


Open AppServiceProvider.php file and add the following line
to boot() method, so that your boot method looks like this.

public function boot(): void


{
// ...

View::share('year', date('Y'));
}

This will make user variable available in all view files.

Open hello.blade.php and add the following line at the end of the file.

<p>Global shared variable: {{ $year }}</p>

Challenge
Problem
Create HelloController with welcome method. Create welcome view using
artisan and put it in hello subfolder.
From HelloController::welcome method render welcome view you just
created.

Pass your name and surname to the view and output it in blade file.
Define route /hello so that when you access it, it will output your name and
surname.

Solution
1. Create new controller

2. php artisan make:controller HelloController

3. Create view

4. php artisan make:view hello.welcome

5. Open the controller and add welcome method

6. public function welcome()


7. {
8. return view('hello.welcome', [
9. 'name' => 'Zura',
10. 'surname' => 'Sekhniashvili'
11. ]);
12. }

13. Now open welcome view and output name and surname

14. <div>
15. {{ $name }} {{ $surname }}
16. </div>

17. Now open routes/web.php and define the route

18. Route::get('/hello', [\App\Http\Controllers\HelloController::class,


'welcome']);

19. Now open http://localhost:8000/hello and you should see your


name and surname outputted
Use and Output PHP Function Results
1. You can also use PHP functions in blade.
{{ date('Y') }}

This will output current year in browser.

1. You can use functions with existing variables.


<p>{{ $name . ' ' . strtoupper($surname) }}</p>

This will output

ZURA SEKHNIASHVILI

1. You can use constants and static functions as well.


<p>{{ Illuminate\Support\Str::after("Hello World", "Hello ") }}</p>
<p>{{ Illuminate\Foundation\Application::VERSION }}</p>
<p>{{ PHP_VERSION }}</p>

The output

World
11.x
8.3.0

Displaying Unescaped Data


Passing job as HTML string

return view("hello", [
"name" => "Zura",
"surname" => "Sekhniashvili",
"job" => "<b>Developer</b>",
]);

and rendered it like this in blade file

<p>Your Job: {{ $job }}</p>

job rendered with HTML entities. The output will be

<b>Developer<b/>

If you want job to be rendered as HTML use {!! !!} expression.


<p>Your Job: {!! $job !!}</p>

The output will be

Your Job : Developer

Blade and JavaScript Frameworks


Sometimes you want to output the following string in browser {{ name }} .
That might be necessary for the JavaScript frameworks, which renders the
data like this. Trying to output this {{ name }} will give you the following error

Undefined constant "name"

That happens because blade engine evaluates {{ }} expression and tries to


find name constant. In order to tell the blade engine to stop evaluating this
particular expression, you need to provide @ symbol in front of the expression.

<p>@{{ name }}</p>

This will give you the following output in browser: {{ name }}.

In the similar way, if you want to output Blade directive (You will learn what
more about directives in upcoming sections) in browser you need to
add @ symbol in front of it. For example: If you want to output this in browser,
you will probably see syntax error, because blade engine tries to evaluate
that foreach.

@foreach

But if you add additional @ symbol and write this in your blade file, the output
will be @foreach.

@@foreach

The @verbatim Directive


If you have a large section of expressions and you don’t want blade to process
any of these expressions, you can mark the entire section, so that blade will
display them as they are.

<div>
Name: {{ name }}
Age: {{ age }}
Job: {{ job }}
Hobbies: {{ hobbies}}
@if
</div>
Wrap your section with @verbatim directive.

@verbatim
<div>
Name: {{ name }}
Age: {{ age }}
Job: {{ job }}
Hobbies: {{ hobbies}}
@if
</div>
@endverbatim

This output in the browser will be

Name: {{ name }} Age: {{ age }} Job: {{ job }} Hobbies: {{ hobbies}} @if

Rendering JSON
Let’s add hobbies variable

return view("hello", [
"name" => "Zura",
"surname" => "Sekhniashvili",
"job" => "<b>Developer</b>",
"hobbies" => ["Tennis", "Fishing"]
]);

The most correct way to output hobbies as JSON is using Js::from() in


blade.

<script>
const hobbies = {{ Js::from($hobbies) }}
</script>

If you check the page source the result is

<script>
const hobbies = JSON.parse('[\u0022Tennis\u0022,\u0022Fishing\u0022]')
</script>

Name: {{ name }} Age: {{ age }} Job: {{ job }} Hobbies: {{ hobbies}} @if


What are blade directives?
Blade directives are special keywords prefixed with an "@" symbol used within
Laravel's Blade templating engine to simplify common tasks like template
inheritance, conditional rendering, , and more. They convert these shorthand
notations into plain PHP code, enhancing readability and maintainability.
Examples include @if for conditionals, @foreach for loops, and @extends for
layout inheritance. By abstracting these common patterns, Blade directives
streamline template creation and reduce boilerplate code, allowing developers
to focus more on the content and logic of their views.

Comments
{{-- Sinle line comment --}}
<button>Click me</button>
{{--
Multi
line
comment
--}}// <!- şeklinde yazdığımız yorum sitede sayfa kaynağını görüntüle
deyince gözüküyor ama yukarıdaki php yorum satırı o şekilde de
görülemiyor.-->
<button>Click me</button>

Conditionals - @if, @unless, @isset, @empty,


@auth, @guest

@if directive
@if (count($cars) > 1)
<p>There is more than 1 car</p>
@endif
@if (count($cars) > 0)
<p>There is at least one car</p>
@else
<p>There are no cars</p>
@endif
@if (count($cars) > 1)
<p>There is at least one car</p>
@elseif (count($cars) === 1)
<p>There is exactly one car</p>
@else
<p>There are no cars</p>
@endif

@unless - It is opposite of @if

@unless (false)
<p>unless</p>
@endunless
Yani ifde parantez içi true olduğunda fonksiyon çalışıyordu, burada ise
false olduğunda
The same is

@if (true)
<p>unless</p>
@endif

@isset, @empty
// eğer bi değişkenin tanımlanıp tanımlanmadığını kontrol etmek istersek
isset kullanırı.
@isset($cars)
<p>isset</p>
@endisset
// aynısını yapıyor
@empty($cars)
<p>empty</p>
@endempty

@auth, @guest
//kullanıcı doğrulanmış
@auth
<p>User is authenticated</p>
@endauth

@guest
<p>User is guest</p>
@endguest
Switch Statement - @switch
@switch($country)
@case('ge')
<p>Georgia</p>
@break
@case('uk')
<p>United Kingdom</p>
@break
@case('us')
<p>USA</p>
@break
@default
<p>Unknown Country</p>
@endswitch

Loops - @for, @foreach, @forelse, @while

@for
@for ($i = 0; $i < 5; $i++)
<p> {{ $i + 1 }}</p>
@endfor

@foreach
@foreach ($cars as $car)
<p>Model: {{ $car->model }}</p>
@endforeach

@forelse
@forelse ($cars as $car)
<p>Model: {{ $car->model }}</p>
@empty
<p>There are no cars</p>
@endforelse

@while
@while (false)

@endwhile

@continue and @break

@continue
@foreach ([1, 2, 3, 4, 5] as $n)
@if ($n == 2)
@continue
@endif
<p>{{$n}}</p>
@endforeach

Or you can use shorthand version of @continue directive

@foreach ([1, 2, 3, 4, 5] as $n)


@continue($n == 2)
<p>{{$n}}</p>
@endforeach

@break
@foreach ([1, 2, 3, 4, 5] as $n)
<p>{{$n}}</p>
@if ($n == 4)
@break
@endif
@endforeach

Or you can use shorthand version of @break directive

@foreach ([1, 2, 3, 4, 5] as $n)


<p>{{$n}}</p>
@break($n == 4)
@endforeach

The Loop Variable


@foreach ($cars as $c)
{{ dd($loop) }}
@endforeach
@foreach ($cars as $c)
<p>index: {{ $loop->index }}</p>
<p>iteration: {{ $loop->iteration }}</p>
<p>remaining: {{ $loop->remaining }}</p>
<p>count: {{ $loop->count }}</p>
<p>first: {{ $loop->first }}</p>
<p>last: {{ $loop->last }}</p>
<p>even: {{ $loop->even }}</p>
<p>odd: {{ $loop->odd }}</p>
<p>depth: {{ $loop->depth }}</p>
<p>parent: {{ $loop->parent }}</p>

<h4>Start of inner loop</h4>


@foreach([1, 2, 3] as $n)
<p>{{ $loop->depth }}</p>
<p>{{ $loop->parent->depth }}</p>
@endforeach
<h4>End of inner loop</h4>
@endforeach

Conditional classes & Styles


<div @class([
'my-css-class',
'georgia' => $country === 'ge'
])>
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
</div>
<div @style([
'color: green',
'background-color: cyan' => $country === 'ge'
])>
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
</div>

Include sub views


It will include file located at shared/button.blade.php. Bu dosyayı
oluşturup içine bir button kodu atıyoruz. Style vs veriyoruz.
Sonra da index.blade. php içinde diğer adımlara geçiyoruz.

<button @style([
'background-color: '. $color
])>
{{$text}}
</button>

@include('shared.button')

Pass additional data to sub view

@include('shared.button', ['color' => 'brown'])

Conditionally rendering sub views


@include directive will fail if the view does not exist however @includeIf will
simple ignore it.

@includeIf('shared.search_form', ['year' => 2019])

You can also conditionally render sub views

@includeWhen($searchKeyword, 'shared.search_results', ['year' => 2019])


@includeUnless(!$searchKeyword, 'shared.search_results', ['year' => 2019])

Include the first sub view

@includeFirst(['admin.button', 'button'], ['color' => 'red'])

Using sub view inside loop - @each


If you want to iterate over the array and render a sub view for each array
element you can do it in the following way.

@foreach ($cars as $car)


@include('car.view', ['car' => $car])
@endforeach

Sub view file car.view.blade.php will receive a variable $car.

The same thing can be achieved using @each directive.

@each('car.view', $cars, 'car')

You can also pass 4th argument to the directive. That needs to be view file
name, which will be rendered if $cars array is empty.

@each('car.view', $cars, 'car', 'car.empty')

Raw PHP

Declare a variable
@php
$city = 'Tbilisi'
@endphp

The equivallent in PHP

<?php
$city = 'Tbilisi';
?>

Import classes

@use("Illuminate\Support\Str")
The equivallent in PHP

<?php
use Illuminate\Support\Str;
?>

💡 The benefit of `@use` directive is that even if you use it multiple times, if the class is
imported it will not throw an error.

Challenge

Problem
Create sub view alert.blade.php which will take two
variables $message and $color and use them in blade file.
Use @style directive to add color to the alert element.

Include that view into another blade file and pass these two variables.

There are many interpretations of this challenge, but the main is that you
create a second blade file, include it into another blade file and you provide
variables.

Solution
Create alert.blade.php in shared folder

php artisan make:view shared.alert

Open alert view and define html code

<div @style(['background-color: '.$color])>


{{ $message }}
</div>

Open another blade file and include alert view.

@include('shared.alert', ['message' => 'Your account was created', 'color'


=> 'green'])

-------------------------------Car Selling Website-----------------------------

Create App Layout


Create new blade file at resources/views/layouts/app.blade.php manually
or by executing

php artisan make:view layouts.app

Open the file and put the following content.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<title>@yield('title') | Car Selling Website</title>
</head>
<body>
<header>Your Header</header>
@yield('content')
<footer>Your Footer</footer>
</body>
</html>

This outputs content variables:

1. @yield('title')

2. @yield('content')

Now let’s open home/index.blade.php file and use the layout.

@extends('layouts.app')

@section('title', 'Home Page')

@section('content')
Home Page content goes here
@endsection

This extends layouts.app blade file, defines title section with Home
Page title and defines section content . In content section you need to put
your home page HTML content.

Using this way, we defined proper layouts with template inheritance.


View altında bir layouts klasoru oluşturuyoruz. Bu klasorun içine app.blade.php
dosyası oluşturuyoruz. Bu dosyaya sitemizin genel hatlarında olacak şeyleri
ekliyoruz. Şimdilik dil kısmını başlık header ve footer. Daha sonra
index.blade.php dosyamıza bu dosyası eklemek için @extends direktifini
kullanıyoruz. Ardından değiştirilebilen alanları bu sayfada olmasını istediğimiz
şekilde değiştiriyoruz. @section direktifleri kullanarak gerekli değişiklikleri
ekliyoruz.

Output language, Application Name and CSRF


token in App Layout

Output lang
Open layouts.app view file and modify <html> opening tag into this

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">


//.env dosyasında app_locale kısmını ne yaparsak onu alıyor. Ve en başına _
ile – yer değiştirmesini istedik bu da tr_Tr tarzı bir şeyler yazdığımızda
kullanışlı oluyor.

Output Application Name


Change the <title> tag content into this

<title>@yield('title') | {{ config('app.name', 'Laravel') }}</title


//isim için yine .env dosyasını en başındaki APP_NAME tagını kullanıyoruz.
Buraya ne yazarsak config fonksiyonu içindeki ‘app.name’ sayesinde. Env
dosyasındaki adı alıp ilgili yere basıyor. Ancak her ihtimale karşı bir
fallback isim de koyuyıruz. Eğer ilk isme ulaşmakta sorun yaşanırsa
virgülden sonra yer alan ifade devreye girecek ‘Laravel’.app.php dosyasında
yer alan bu fonksiyon sayede ilgili işlem yapılıyor: 'name' =>
env('APP_NAME', 'Laravel'),

Output CSRF Token


Just before the <title> tag put the following meta tag.csrf farklı kullanıcıların
sitemize veri göndermesini engelliyor. Güvenlik önlemi

<meta name="csrf-token" content="{{ csrf_token() }}">

Copy HTML Layout from the HTML Template


Open the HTML/CSS template that is uploaded in the course content using
vscode. Vscode’da Live Server eklentisinin olduğundan emin ol.
Open index.html file.

Copy entire html content into layouts.app view file. Ama az önce yazdığımız
doctype html dosyasını silmedik. O hala duruyor. Sadece biraz aşağıya
kaydırıp üzerine templatedeki index.html kodunu yapıştırdım. Sonra elimizdeki
kodu inceliyoruz. Buradaki kodun bir kısmı layouta ait ama bir kısmı sitenin
spesifik bilgilerini içeriyor. Bu spesifik bilgi kısımlarını kesip ilgili yerlere
yapıştıracağız. Layouta ait, her yerde standart olacak kod burada kalacak.

Home Slider kısmını alıp home.index dosyasındaki ilgili yere geçiriyoruz.


Buraya yapıştırıyoruz daha sonra find a new car ve new cars kısımlarını da
alıp contentin içine home sliderin altına yapıştırıyoruz. Artık app.blade.php
dosyasında sadece header footer vs kaldı. Biz de böyle olmasını istiyorduk.

Cut content starting with <!-- Home Slider --> and ending
with </main> and put it inside home.index view file
inside @section('content').

Inside layouts.app view file:

Şimdi önceden hazırladığımız buradaki koddan gerekli parçaları alıp yeni koda
yapıştıracağız sonra zaten aşağıya kaydırmış olduğumuz bu kodu tamamen
sileceğiz. Bu bir taslaktı.

1. Adjust <html> tag’s lang attribute


Az önce aşağıya kaydırdığımız ve bizim yazdığımız ilk koddaki lang
kısmını alıp yukarıdaki mevcut html lang ile değiştiriyoruz:

Normalde burada klasik şekilde lang= en ifadesi vardı ama biz önceden
hazırladığımız kodu buraya ekledik. Şimdi diğer değişiklikleri de
yapalım.

2. Output CSRF token <meta> tag

Önceden yazdığımız meta csrf kodunu alıp yeni koddaki title’ın hemen
üzerine geçiriyoruz.

3. Adjust <title> tag content

Sonra da bizim önceden yazdığımız title kodunu alıp buradaki titleın


yerine yapıştırıyoruz.
4. Output content section with @yield

Sonra header ve footer arasındaki alana bir yield ekliyoruz

Artık eski versiyonuna ihtiyacımız olmadığı için alttaki kodu silebiliriz.


ve bu templatede yer alan düz .html uzantılı kodu direkt kullanmıyoruz.
Biz bu .html uzantılı kodu alıp blade dosyamıza ekliyoruz ve laravelin
sağladığı değişiklikleri yapıyoruz. Yukarıdaki değişiklikler gibi.

-> şimdi bu işlemi tamamlasak da kod tam çalışmayacak, çünkü burada


js dosyası da var ama biz henüz onu kendi projemize ekleyip
düzenlemedik.
Ve css dosyamızı da eklemedik. Şimdi sıra bunlarda. Henüz js ve css
eklemediğimiz için böyle gözüküyor:

Şimdi js ve css
kodlarını eklemeye
geçiyoruz. Vscode
soldaki js klasorune
sağ tıklayıp
reveal in file explorer seçeneğini seçiyoruz. Buradan template dosyamızı
buluyoruz ve js img ve css adlı üç dosyanın hepsini seçiyoruz. Ve
kopyalıyoruz. Sonra bunları alıp public klasorunun altına koyuyoruz. En
başta js klasorune sağ tıklayıp file explorer açmıştık ama tıkladığımız yer
fark etmiyormuş.

Create Clean layout and extend it in App Layout


Create new view file - layouts.clean .

Move the base layout part from layouts.app into layouts.clean view file and
output childContent section, so that final version of layouts.clean file looks
like this. App.blade.phpden aldığımız kodu clean.blade.phpye atıyoruz. Ve
appdan o kısmı siliyoruz. Orada artık sadece header vs yer alacak. App.blade.
phpde sadece header, footer ve @yield kaldı oralar da boş zaten.

Clean.blade.phpnin içine bir childContent ekledik. Böylece diğer ögeler


tarafından extend edilip düzenlenebilecek. Sonra artık içinde pek bir şey
kalmayan app.blade.php dosyasının en üstüne @extends(‘layouts.app’)
ifadesini ekliyoruz. Bu sayede app’e eklediğimiz tüm kodları çağırıyor. Bunu
ekledikten sonra clean.blade.phpdeki childContent kısmı içerik bekliyor ve bu
içeriği app.blade.phpde tanımlamamız lazım. @section direktifleri kullanarak
bıunu yapacağız. Childcontentin içinde asıl content de olacak bu yüzden
sectionların arasına da bunu yerleştiriyrouz. Normalde header ve footer,
clean.bladeın bodysinede yer almalıydı. Bu yüzden üstte kalan header ve
footer kodarınıda childcontentin içine atıyoruz. Sonuç olarak buraya kadar
özetleyecek olursak. İndex.blade app.blade i extend ediyor. App.blade.
clean.bladeı extend ediyor. Clean.blade childContent ve title çıktısı veriyor.
App blade. Bu childcontent kısmına header ve footer ekliyor ve ayrıca kendi
contentini de ekleyip çıktısnı veriyor. İndex.blade hepsini içeriyor. Bundan
sonra headera bakıyoruz. Headerda baya kod var. Olduğu yerde de durabilir
ama ayrı bir dosyaya almak çok daha iyi olacak. Bu yüzden başka bir blade
oluşturuyoruz.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>@yield('title') | {{ config('app.name', 'Laravel') }}</title>

<link rel="preconnect" href="https://fonts.googleapis.com" />


<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?
family=Ubuntu:ital,wght@0,300;0,400;0,500;0,700;1,300;1,400;1,500;1,700&dis
play=swap"
rel="stylesheet"
/>
<link
rel="stylesheet"

href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/
all.min.css"

integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsO
MqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<!-- <link

href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.2.1/flowbite.min.cs
s"
rel="stylesheet"
/> -->

<link rel="stylesheet" href="css/app.css" />


<!-- <link rel="stylesheet" href="css/output.css" /> -->
</head>
<body>

@yield('childContent')
<script
src="https://cdnjs.cloudflare.com/ajax/libs/scrollReveal.js/4.0.9/
scrollreveal.js"
integrity="sha512-
XJgPMFq31Ren4pKVQgeD+0JTDzn0IwS1802sc+QTZckE6rny7AN2HLReq6Yamwpd2hFe5nJJGZL
vPStWFv5Kww=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<script src="js/app.js"></script>
</body>
</html>

Create a separate view file for header under layouts/partials folder.

php artisan make:view layouts.partials.header

Open the header blade file and put the entire <header> tag there.

Then open layouts.app file and extend it from clean layout.

Also include the header partial file in app layout, so that final content of app
layout looks like this.

@extends('layouts.clean')

@section('childContent')
@include('layouts.partials.header')
@yield('content')
<footer></footer>
@endsection

Laravel'de `@include` ve `@extends` direktifleri, Blade şablonları içinde


farklı amaçlarla kullanılır:

### `@extends`

- **Anlamı:** Bir şablonun başka bir ana şablonu miras almasını sağlar.

- **Kullanım Amacı:** Daha büyük bir düzen (layout) şablonunu belirleyip,


diğer sayfaların bu düzeni kullanmasını sağlar.

- **Ne Yapar:** Bir sayfa şablonunun belirli bir düzen dosyasını


kullanarak temel yapıdan faydalanmasına olanak tanır.

- **Örnek:**
```blade

<!-- resources/views/child.blade.php -->

@extends('layouts.master')

@section('content')

<h1>This is the content section</h1>

@endsection

```

Bu örnekte `child.blade.php`, `layouts/master.blade.php` dosyasını


kullanır ve bu düzenin içine içerik ekler.

### `@include`

- **Anlamı:** Bir şablonun başka bir dosyayı çağırmasını sağlar.

- **Kullanım Amacı:** Tekrar eden küçük parça şablonları yeniden


kullanmak için idealdir.

- **Ne Yapar:** Şablonun bir kısmını başka bir dosyadan alır ve doğrudan
sayfanın içine dahil eder.

- **Örnek:**

```blade

<!-- resources/views/welcome.blade.php -->

<h1>Welcome to the homepage</h1>

@include('partials.footer')

```

Bu örnekte `welcome.blade.php` dosyasına `partials/footer.blade.php`


dosyası eklenir.

### Özet:
- `@extends` daha büyük bir şablonu (genellikle layout) miras almak için
kullanılır.

- `@include` ise daha küçük, tekrar eden şablon parçalarını bir dosyada
toplamak ve onları farklı dosyalarda kullanmak için kullanılır.

Create Signup Page


Create SignupController by executing

php artisan make:controller SignupController

Then create a new view file.viewin içine elimizdeki templatten signup kodunun
main kısmını aldık. Clean layoutu da extend edeceğiz ve tiitle vs dolduracağız.

php artisan make:view auth.signup

Open SignupController and define create method

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SignupController extends Controller


{
public function create()
{
return view('auth.signup');
}
}

Then open routes/web.php and define new route for /signup

Route::get('/signup', [App\Http\Controllers\SignupController::class,
'create']);

Open HTML/CSS project and open signup.html file.

Copy the entire content of <main> tag.

Open auth.signup view file in your Laravel project, delete entire content and
put the following code inside.

@extends('layouts.clean', ['cssClass' => 'page-signup'])


@section('title', 'Signup')

@section('childContent')
{{--<main> tag goes here--}}
@endsection

Then replace {{--<main> tag goes here--}} with the actual <main> tag
content you copied from HTML/CSS project.

Open http://localhost:8000/signup and you should see signup page.

Challenge - Create Login Page

Problem
Define LoginController and login view. Copy login form from HTML/CSS
project and put in your Laravel login view.

Define /login route as well, so that when you access the URL it will render
the login page.

Solution
Create LoginController by executing

php artisan make:controller LoginController

Then create a new view file

php artisan make:view auth.login

Open LoginController and define create method

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class LoginController extends Controller


{
public function create()
{
return view('auth.login');
}
}

Then open routes/web.php and define new route for /login

Route::get('/login', [App\Http\Controllers\LoginController::class,
'create']);

Open HTML/CSS project and open login.html file.

Copy the entire content of <main> tag.

Open auth.login view file in your Laravel project, delete entire content and
put the following code inside.

@extends('layouts.clean', ['cssClass' => 'page-login'])

@section('title', 'Login')

@section('childContent')
{{--<main> tag goes here--}}
@endsection

Then replace {{--<main> tag goes here--}} with the actual <main> tag
content you copied from HTML/CSS project.

Open http://localhost:8000/login and you should see login page.

Directives - @section, @show, @parent


Update layouts.app view file and @yield inside <footer>.

@extends('layouts.clean')

@section('childContent')
@include('layouts.partials.header')
@yield('content')
<footer>
@yield('footerLinks')
</footer>
@endsection

Now let’s open home.index view file and define new section footerLinks.
@section('footerLinks')
<a href="#">Link 3</a>
<a href="#">Link 4</a>
@endsection

Now if we open our application in browser, we will see Link 3 and Link4.

Now let’s assume that we want Link 1 and Link 2 to be always displayed in
footer.

Let’s open layouts.app file and updated @yield('footerLinks') with the


following code. It will define the section, but also render the section’s default
content.

@section('footerLinks')
<a href="#">Link 1</a>
<a href="#">Link 2</a>
@show

The code above is pretty much the same as the following code.

@section('footerLinks')
<a href="#">Link 1</a>
<a href="#">Link 2</a>
@endsection
@yield('footerLinks')

Now if you remove the footerLinks section definition from home.index view
file it will render Link 1 and Link 2, but if you leave the section it will override
and render Link 3 and Link 4, in order both of the links to be rendered you
should update footerLinks section definition in home.index view file in the
following way.

@section('footerLinks')
@parent
<a href="#">Link 3</a>
<a href="#">Link 4</a>
@endsection

Adding @parent directive will take the content


of footerLinks from layouts.app view file and then append Link 3 and Link
4, so finally it will render all 4 links in <footer> tag.

More on Directives
@hasSection
@hasSection('navigation')
<div class="pull-right">
@yield('navigation')
</div>

<div class="clearfix"></div>
@endif

@sectionMissing
@sectionMissing('navigation')
<div class="pull-right">
@include('default-navigation')
</div>
@endif

@checked
This directive will print checked text if the expression is true.

<input type="checkbox" @checked(BOOLEAN_EXPRESSION) />

@disabled
<input type="checkbox" @disabled(BOOLEAN_EXPRESSION) />

@readonly
<input type="text" @readonly(BOOLEAN_EXPRESSION) />

@required
<input type="text" @required(BOOLEAN_EXPRESSION) />

@selected
<select name="year">
@foreach($years as $year)
<option value="{{ $year }}" @selected($year == date('Y'))>
{{ $year }}
</option>
@endforeach
</select>

@env
@env('staging')
// The application is running in "staging"...
@endenv

@env(['staging', 'production'])
// The application is running in "staging" or "production"...
@endenv

@production
@production
// Production specific content...
@endproduction

@session
@session('successMessage')
<div class="p-4 bg-green-100">
{{ $successMessage }}
</div>
@endsession

You might also like