In acest tutorial vom crea si testa o
aplicatie CRUD simpla cu Laravel (
Create-Read-Update-Delete) folosind date
stocate intr-o Baza de Date MySQL, folosind clasa DB pentru interogari SQL.
- Acest exemplu il puteti folosi ca punct de inceput pentru un CMS.
• Pentru a descarca fisierele cu codurile prezentate aici, clic pe:
Laravel MySQL Exemplu CRUD.
1. Cream un
resource controller numit
PagesMysql.
Copiati urmatorul cod si salvati-l in "
app/Http/Controllers/PagesMysql.php".
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
//resource controller to Insert, Update, Show, delete pages in mysql
class PagesMysql extends Controller {
protected $table ='pages';
//create the table if not exists
//@return string
public function createTable(){
$sql ='CREATE TABLE IF NOT EXISTS '. $this->table .' (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, title VARCHAR(100), description VARCHAR(150), content MEDIUMTEXT, dtreg TIMESTAMP NOT NULL DEFAULT NOW()) CHARACTER SET utf8 COLLATE utf8_general_ci';
if(DB::statement($sql)) return 'Table: '. $this->table .' successfully created.<br><a href="/mysql">Main Page</a>';
else return 'Unable to create table: '. $this->table;
}
//@return view() with list of pages
public function index(){
$pages = DB::select('select id, title from '. $this->table);
return view('pages.index',['title'=>'Pages List', 'pages'=>$pages]);
}
//Show the form for creating a new page
//@return view
public function create(){
return view('pages.form_insert', ['title'=>'Create New Page']);
}
//Insert /Store a newly created page
//@return string
public function store(Request $request){
$re ='No valid request';
if($request->has(['title', 'description', 'content'])){
$sql ='INSERT INTO '. $this->table .' (title, description, content) VALUES (:title, :description, :content)';
$vals =['title'=>$request->title, 'description'=>$request->description, 'content'=>$request->content];
if(DB::insert($sql, $vals)){
$idpg = DB::getPdo()->lastInsertId(); //auto-increment id for newly created page
$re ='Record inserted successfully.<br><a href="/page/'. $idpg .'">See the page</a>';
}
else $re = 'Unable to insert data in table: '. $this->table;
}
return $re;
}
//Display the specified page
//@param int $id
//@return view
public function show($id){
$page = DB::select('select title, description, content from '. $this->table .' where id =:id LIMIT 1', ['id'=>$id]);
//keep data for variables in view
$page =[
'title'=>$page[0]->title,
'description'=>$page[0]->description,
'content'=>$page[0]->content
];
return view('pages.page', $page);
}
//Show the form for editing the specified page
//@param int $id
//@return view
public function edit($id){
$page = DB::select('select id, title, description, content from '. $this->table .' where id =:id LIMIT 1', ['id'=>$id]);
//keep data for variables in view
$page =[
'title'=>'Edit page',
'id'=>$page[0]->id,
'f_title'=>$page[0]->title,
'f_description'=>$page[0]->description,
'f_content'=>$page[0]->content
];
return view('pages.form_update', $page);
}
//Update the specified resource in storage.
//@param Request $request
//@param int $id
//@return string
public function update(Request $request, $id){
$re ='No valid request';
if($request->has(['title', 'description', 'content'])){
$sql ='UPDATE '. $this->table .' SET title=:title, description=:description, content=:content WHERE id=:id';
$vals =['title'=>$request->title, 'description'=>$request->description, 'content'=>$request->content, 'id'=>$id];
if(DB::update($sql, $vals)){
$re ='Record updated successfully.<br><a href="/page/'. $id .'">See the page</a>';
}
else $re = 'Unable to update data in table: '. $this->table;
}
return $re;
}
//Remove the specified page
//@param int $id
//@return string
public function destroy($id){
$nrd = DB::delete('delete from '. $this->table .' where id =:id LIMIT 1', ['id'=>$id]);
if($nrd >.0) return 'Record deleteed successfully.<br><a href="/mysql">Click Here</a> to go back.';
else return 'Unable to delete data in table: '. $this->table;
}
}
2. Creati un director numit "
pages" in directorul
resources/views/. In directorul "pages/" vom crea cinci fisiere blade template pentru aceasta aplicatie.
a) Creati un template pt. sectiunea <head> a paginilor, in fisierul:
resources/views/pages/head.blade.php. Copiati urmatorul cod in acel fisier. Acest fisier va fi inclus in celelalte.
<!doctype html>
<html lang="{{app()->getLocale()}}">
<head>
<meta charset="utf-8">
<title>{{$title}}</title>
</head>
<body>
<h1>{{$title}}</h1>
b) Creati inca un fisier template in:
resources/views/pages/index.blade.php si copiati urmatorul cod in acel fisier. Va afisa o pagina cu un link catre formularul de adaugare date in mysql, si o lista cu paginile existente in baza de date.
@include('pages.head')
<a href="{{route('mysql.create')}}" title='Create New Page'>Create New Page</a>
<div id='pages'>
@if($pages && count($pages)>0)
<ol>
@foreach($pages as $page)
<li><a href="/page/{{$page->id}}">{{$page->title}}</a> - <a href="/mysql/{{$page->id}}/edit">Edit</a> - <form method="post" action="/mysql/{{$page->id}}" style='display:inline'>{{ csrf_field() }} {{method_field('DELETE')}} <input type='submit' value='DELETE'/></form></li>
@endforeach
</ol>
@endif
</div>
</body>
</html>
c) Acum cream al treilea fisier view in "pages/". Copiati si salvati acest cod in:
resources/views/pages/page.blade.php.
- Acest view va arata datele paginii cand e accesata o adresa de forma: '
page/{id}'.
@include('pages.head')
Description: {{$description}}
<h3>Content</h3>
{!!$content !!}
</body>
</html>
d) Creati formularul pentru
introducere date in MySQL. Copiati si salvati acest cod in:
resources/views/pages/form_insert.blade.php.
- Acest view este returnat cand e accesata pagina:
/mysql/create
@include('pages.head')
<form method="post" action="/mysql">
{{ csrf_field() }}
Title: <input type='text' name='title' required /><br>
Description: <input type='text' name='description' /><br>
Content:<br>
<textarea name='content'>Content</textarea><br>
<input type='submit' value='Store'/>
</form>
</body>
</html>
e) Creati formularul pentru
update date in MySQL. Copiati si salvati acest cod in:
resources/views/pages/form_update.blade.php.
- Acest view este returnat cand e accesata o pagina de forma:
/mysql/{id}/edit
@include('pages.head')
<form method="post" action="/mysql/{{$id}}">
{{ csrf_field() }}
{{method_field('PUT')}}
Title: <input type='text' name='title' value='{{$f_title}}' required /><br>
Description: <input type='text' name='description' value='{{$f_description}}' /><br>
Content:<br>
<textarea name='content'>{!!$f_content!!}</textarea><br>
<input type='submit' value='Update'/>
</form>
</body>
</html>
3. Acum se defineste codul pt. Route care foloseste controller-ul PagesMysql; adaugati urmatorul cod in fisierul
routes/web.php:
//calls the method to create the table in mysql
Route::get('mysql/createtable','PagesMysql@createTable');
//on /page/{id} request, calls the method to show page data
Route::get('page/{id}','PagesMysql@show')->where('id', '[0-9]+');
/*
This resource handle multiple requests to Insert, Update, Show, delete pages in mysql
Automatically calls methods according to request
*/
Route::resource('mysql','PagesMysql');
Folosire aplicatie CRUD
Acum puteti folosi aceasta aplicatie simpla CRUD pentru a stoca, edita si sterge date de pagini web in mysql.
1. Mai intai, accesati urmatoarea adresa URL pentru a
crea tabelul in baza de date:
//localhost:8000/mysql/createtable
- Rezultat:
Table: pages successfully created.
Main Page
2. Vizitati acest URL (sau apasati pe link-ul "Main Page"):
//localhost:8000/mysql
- Rezultatul va aparea precum se vede in imaginea urmatoare:
3. Apasati pe link-ul
Create New Page. Va deschide o pagina cu un formular pentru a aduga datele unei noi pagini; cum se vede in aceasta imagine:
4. Adaugati date in campurile formularului, apoi apasati pe butonul "Store" pentru a trimite formularul. Ar trebui sa returneze un raspuns ca acesta:
Record inserted successfully.
See the page
- Daca apasati pe link-ul "See the page", va deschide pagina pe care tocmai ati creat-o.
5. Acum, accesati din nou adresa:
//localhost:8000/mysql
- Va afisa un link catre pagina pe care ati creat-o, si butoane
Edit si
Delete; ca in aceasta imagine:
Acum, puteti crea inca o pagina, sau edita si sterge pagina existenta.
- Daca apasati pe link-ul "Edit", va afisa o pagina cu un formular ca in aceasta imagine:
• Pentru a descarca fisierele cu codurile prezentate aici, apasati pe:
Laravel MySQL Exemplu CRUD.