Sunteți pe pagina 1din 41

Pas1:Creare Migration

php artisan make:migration create_tasks_table --create=tasks

Pas2: In directorul D:\wamp\www\TestingLaravel\database\migrations

In fiierul rezultat n urma comenzii de la pasul 1 se creeaza fiierul


2017_04_29_182453_create_tasks_table.php

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTasksTable extends Migration


{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('tasks');
}
}

Dup adaptare fiierului de mai sus se executa pasul 3 in cmd

Pas3: php artisan migrate

1
Pas4. Creare Eloquent Model pt tabelul Task. In cmd se introduce comanda php artisan
make:model Task

Pas5. din directorul app/ se deschide fiierul Task.php i se introduce variabila $fillable

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model


{
public $fillable = [id,'name', 'description'];
}

pas6. Se verific MySql daca nu exist n baza de date totdo tabela tasks at aceasta se creaza si rezulta
astfel:

2
pas7. In app/Http/routes.php se defines cile spre fiierele folosite pt a realize operatii
CRUD .

Route::get('/', 'TaskController@index'); //afisare lista sarcini pe pagina de start

Route::resource('tasks', 'TaskController');// Ruta de resurse va genera CRUD URI

Pas8. Se creaz controllerul tasks routes prin comanda

php artisan make:controller TaskController resource

Controller se localizeaza in directorul Controllers din app/Http/ in fisierul cu numele:


TaskController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class TaskController extends Controller


{
/**

3
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}

/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}

/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}

/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}

/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}

/**

4
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}

/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}

Pas9. Introduc in cmd comanda php artisan route:list

pt a verifica ca toate routele sunt setate pt a face operatiile CRUD

Pas 10: Design Layout folosind Blade Template:


Vom utiliza layout pt toate operatiile crud , Layout este master page pt toate paginile
proiectului, Laravel layouts ne ajuta sa refolosim codul in pagini multiple.
se impinge bootstrap scriind in cmd composer require twbs/bootstrap

5
Pas11. copy css,js, si font in directorul public

Pas12. In directorul public/view/tasks cream fisierele

Pas12 Create layout page in resources/views/layouts/master.blade.php cu codul:


<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task List</title>
<!-- Bootstrap CSS File -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 2 meta tags *must* come first in the head; any other head content must come
*after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>

6
<body>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Laravel CRUD Operations Demo</a>
</div>
<ul class="nav navbar-nav">
</ul>
</div>
</nav>
<head>
<h1></h1>
</head>
@yield('content')
</div>
</body>
</html>

Pas14.Pagina care afieaza taskurile se numeste list.blade.php in directorul public/view/tasks ;I va


inlocui n master pages zona @yield('content')

@extends('layouts.master')
@section('content')
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<div class="panel panel-default">
<div class="panel-heading">
Task List
</div>
<div class="panel-body">
<div class="form-group">
<div class="pull-right">
<a href="/tasks/create" class="btn btn-default">Add New Task</a>
</div>
</div>
<table class="table table-bordered table-stripped">
<tr>
<th width="20">No</th>
<th>Title</th>
<th>Description</th>
<th width="300">Action</th>
</tr>
@if (count($tasks) > 0)
@foreach ($tasks as $key => $task)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $task->name }}</td>

7
<td>{{ $task->description }}</td>
<td>
<a class="btn btn-success" href="{{ route('tasks.show',$task->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('tasks.edit',$task->id) }}">Edit</a>
{{ Form::open(['method' => 'DELETE','route' => ['tasks.destroy', $task-
>id],'style'=>'display:inline']) }}
{{ Form::submit('Delete', ['class' => 'btn btn-danger']) }}
{{ Form::close() }}
</td>
</tr>
@endforeach
@else
<tr>
<td colspan="4">Tasks not found!</td>
</tr>
@endif
</table>
{{ $tasks->render() }}// introducere nr pagin
</div>
</div>
@endsection

-se extinde pagina layout-ului i vom implementa seciunea de coninut pe care o vom face n
variabila de coninut a layout-ului @yield('content').
- seciunea de coninut n primul rnd, avem design bootstrap pt afisare cu panel-heading and panel-
body.
- tabel html pentru a afisa toate taskurile memorate in variabila $task
- rendor() este pt paginare
Pas15. Crearea unui task nou se face prin pagina create.blade.php n view pagina aferenta este
create.blade.php cu codul sursa de mai jos. n controller avem funciile create determina aparitia pe
ecran aformularului existent in pagina create.blade, store(..) este functia care va valida datele i
executa insertul redirectand la final spre functia index din controller care are rolul de a afisa
toate datele in tabela tasks in numar de 5 per pagina( cu view-ul list)
@extends(layouts.master')
@section('content')
<div class="panel panel-default">
<div class="panel-heading">
View Task
</div>
<div class="panel-body">
<div class="pull-right">
<a class="btn btn-default" href="{{ route('tasks.index') }}">Go Back</a>
</div>
<div class="form-group">
<strong>Name: </strong> {{ $task->name }}
</div>
<div class="form-group">
<strong>Description: </strong> {{ $task->description }}
</div>

8
</div>
</div>
@endsection

Pas16. Controllerul numit TaskController din directorul D:\wamp\www\ TestingLaravel\ app\ Http\
Controllers

<?php
namespace App\Http\Controllers;
use App\Task;
use Illuminate\Http\Request;
use App\Http\Requests;
class TaskController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$tasks = Task::orderBy('name','ASC')->paginate(5);
return view('tasks.list',compact('tasks'))->with('i', ($request->input('page', 1) - 1) * 5);
}

/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('tasks.create');
}

/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// validated input request
// validated input request
$this->validate($request, [
'name' => 'required',

9
'description' => 'required'
]);

// create new task


Task::create($request->all());
return redirect()->route('tasks.index')->with('success', 'Your task added successfully!');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$task = Task::find($id);
return view('tasks.show',compact('task'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$task = Task::find($id);
return view('tasks.edit', compact('task'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required'
]);
Task::find($id)->update($request->all());
return redirect()->route('tasks.index')->with('success','Task updated successfully');
}

/**
* Remove the specified resource from storage.

10
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Task::find($id)->delete();
return redirect()->route('tasks.index')->with('success','Task removed successfully');
}
}

Pas17. La click pe butonul show se activeaza n controller functia edit din TaskController care cauta si
afiseaza din table Task inregistrarea cu id Task-ului current. Pagina din view corespunzatoare acestei
actiuni este show.blade.php

@extends('layouts.master')
@section('content')
<div class="panel panel-default">
<div class="panel-heading">
View Task
</div>
<div class="panel-body">
<div class="pull-right">
<a class="btn btn-default" href="{{ route('tasks.index') }}">Go Back</a>
</div>
<div class="form-group">
<strong>Name: </strong> {{ $task->name }}
</div>
<div class="form-group">
<strong>Description: </strong> {{ $task->description }}
</div>
</div>
</div>
@endsection

Pas18. La click pe butonul edit se activeaza n controller functia update din TaskController care cauta si
afiseaza din table Task inregistrarea cu id Task-ului current ntr-un formular. Pagina din view
corespunzatoare acestei actiuni este edit.blade.php

@extends('layouts.master')

@section('content')

<div class="panel panel-default">


<div class="panel-heading">Edit Task</div>

11
<div class="panel-body">
//am inregistrari
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Errors:</strong>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
//populez campurile formularului cu datele aferente din tabela task
{!! Form::model($task, ['method' => 'PATCH','route' => ['tasks.update', $task->id]]) !!}
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" value="{{ $task->name }}">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" class="form-control" rows="3">{{ $task->description
}}</textarea>
</div>
<div class="form-group">
<input type="submit" value="Save Changes" class="btn btn-info">
<a href="{{ route('tasks.index') }}" class="btn btn-default">Cancel</a>
</div>
{!! Form::close() !!}
</div>
</div>
@endsection

pas19. La click pe butonul delete se activeaza n controller functia destroy din TaskController care cauta
si terge din table Task inregistrarea cu id Task-ului. Pagina din view corespunzatoare acestei actiuni este
list.blade.php.

{{ Form::open(['method' => 'DELETE','route' => ['tasks.destroy', $task->id],'style'=>'display:inline']) }}


{{ Form::submit('Delete', ['class' => 'btn btn-danger']) }}
{{ Form::close() }}

pas20. In cmd se introduce comanda php artisan serve

in browser se executa http://localhost:8000/tasks

in browser avem

12
13
Exemplu 2 ----Aplicatie CRUD
pas1. Pas1:Creare Migration

php artisan make:migration create_nerds_table --create=nerds

Pas2: In directorul D:\wamp\www\TestingLaravel\database\migrations

In fiierul rezultat n urma comenzii de la pasul 1 avem

Dup adaptare fiierului de mai sus se executa pasul 3 in cmd

Pas3: php artisan migrate

Pas4. Creare Eloquent Model pt tabelul Nerd. In cmd se introduce comanda php artisan
make:model Nerd

Pas5. din directorul app/ se deschide fiierul nerd.php i se introduce variabila $fillable

<?php

14
namespace App;

use Illuminate\Database\Eloquent\Model;

class nerd extends Model


{
//
protected $fillable=['id','name','email','nerd_level'];
}
pas6. Se verific MySql daca nu exist n baza de date totdo, tabela nerds at aceasta se creaza si rezulta
asfel:

Pas7. In route.php vom introduce

Route::resource('nerds', 'NerdController');
Route::get('nerds', [
'as' => 'nerd',
'uses' => 'NerdController@index'
]);

Pas8. Se creaz controllerul tasks routes prin comanda

php artisan make:controller NerdController resource

Controller se localizeaza in directorul Controllers din app/Http/ in fisierul cu numele:

15
NerdController.php pe care il vom complete si vom obine :

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Nerd;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator;
//use Input;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class NerdController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$nerds = Nerd::all();
return view('nerds.index', ['nerds' => $nerds]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
// load the create form (app/views/nerds/create.blade.php)
return view('nerds.create');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
public function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255',
'nerd_level' => 'required|numeric'
]);
}
/**
* Store a newly created resource in storage.
*

16
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
//public function store()
public function store(Request $request)
{
$rules = array(
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:nerds',
'nerd_level' => 'required|numeric'
);
$validator = $this->validator($request->all(), $rules);
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
} else {
$nerd = new Nerd;
$nerd->name = $request->input('name');
$nerd->email = $request->input('email');
$nerd->nerd_level = $request->input('nerd_level');
$nerd->save();
return redirect('nerds')->with('message', 'Successfully created nerd!');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
// get the nerd
$nerd = Nerd::find($id);
// show the nerd
return view('nerds.show')->withNerd($nerd);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
// get the nerd
$nerd = Nerd::find($id);
// show the edit form and pass the nerd
return view('nerds.edit')->withNerd($nerd);
}
/**
* Update the specified resource in storage.

17
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$rules = array(
'name' => 'required',
'email' => 'required|email',
'nerd_level' => 'required|numeric'
);
$validator = $this->validator($request->all(), $rules);
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
} else {
$nerd = Nerd::find($id);
$nerd->name = $request->input('name');
$nerd->email = $request->input('email');
$nerd->nerd_level = $request->input('nerd_level');
$nerd->save();
return redirect('nerds')->with('message', 'Successfully updated nerd!');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
// delete
$nerd = Nerd::find($id);
$nerd->delete();
// redirect
return redirect('nerds')->with('message', 'Successfully deleted the nerd!');
}
}

Pas10. In D:\wamp\www\TestingLaravel\resources\views\ cream directorul nerds n care vom cera


fiierele

18
pas11. n fisierul index.blade.php avem codul sursa. n controller se apeleaza functia index

<!DOCTYPE html>
<html>
<head>
<title>Look! I'm CRUDding</title>
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">

<nav class="navbar navbar-inverse">


<div class="navbar-header">
<a class="navbar-brand" href="{{ URL::to('nerds') }}">Nerd Alert</a>
</div>
<ul class="nav navbar-nav">
<li><a href="{{ URL::to('nerds') }}">View All Nerds</a></li>
<li><a href="{{ URL::to('nerds/create') }}">Create a Nerd</a>
</ul>
</nav>

<h1>All the Nerds</h1>

<!-- will be used to show any messages -->


@if (Session::has('message'))
<div class="alert alert-info">{{ Session::get('message') }}</div>
@endif

<table class="table table-striped table-bordered">


<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Nerd Level</td>
<td>Actions</td>
</tr>
</thead>
<tbody>
@foreach($nerds as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
<td>{{ $value->nerd_level }}</td>

<!-- we will also add show, edit, and delete buttons -->

19
<td>

<!-- delete the nerd (uses the destroy method DESTROY /nerds/{id} -->
<!-- we will add this later since its a little more complicated than the
first two buttons -->
{!! Form::open(array('url' => 'nerds/' . $value->id, 'class' => 'pull-right'))
!!}
{!! Form::hidden('_method', 'DELETE') !!}
{!! Form::submit('Delete this Nerd', array('class' => 'btn btn-
warning')) !!}
{!! Form::close() !!}

<!-- show the nerd (uses the show method found at GET /nerds/{id} -->
<a class="btn btn-small btn-success" href="{{ URL::to('nerds/' . $value-
>id) }}">Show this Nerd</a>

<!-- edit this nerd (uses the edit method found at GET /nerds/{id}/edit --
>
<a class="btn btn-small btn-info" href="{{ URL::to('nerds/' . $value->id .
'/edit') }}">Edit this Nerd</a>

</td>
</tr>
@endforeach
</tbody>
</table>

pas12. Inserare inregistrare noua se face activand linkul Create a Nerd actiune care apeleaza pagina
create.blade.php i funciile aferente din controller sunt:

12.1. create care permite afisare pagina create.

12.2. store care cheama functia validator cu rol de a valida datele introduce in camd de utilizator. In caz
de date corecte se inseraza in tabela Nerd. in caz de date incorecte apar mesaje.

<!-- app/views/nerds/create.blade.php -->


<!DOCTYPE html>
<html>
<head>
<title>Look! I'm CRUDding</title>
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-inverse">
<div class="navbar-header">

20
<a class="navbar-brand" href="{{ URL::to('nerds') }}">Nerd Alert</a>
</div>
<ul class="nav navbar-nav">
<li><a href="{{ URL::to('nerds') }}">View All Nerds</a></li>
<li><a href="{{ URL::to('nerds/create') }}">Create a Nerd</a>
</ul>
</nav>
<h1>Create a Nerd</h1>
<!-- if there are creation errors, they will show here -->
{!! Html::ul($errors->all() )!!}
{!! Form::open(array('url' => 'nerds')) !!}
<div class="form-group">
{!! Form::label('name','Name') !!}
{!! Form::text('name',null,array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('email', 'Email') !!}
{!! Form::email('email', null, array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('nerd_level', 'Nerd Level') !!}
{!! Form::select('nerd_level', array('0' => 'Select a Level', '1' => 'Sees Sunlight', '2' =>
'Foosball Fanatic', '3' => 'Basement Dweller'), null, array('class' => 'form-control')) !!}
</div>
{!! Form::submit('Create the Nerd!', array('class' => 'btn btn-primary')) !!}
{!! Form::close() !!}
</div>
</body>
</html>

pas 13. Afiare detalii informaii despre inregistrarea curenta la click pe butonul Show this nerd se
apeleaza pagina show.blade.php din views in controller functia este edit

<!-- app/views/nerds/show.blade.php -->


<!DOCTYPE html>
<html>
<head>
<title>Look! I'm CRUDding</title>
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">

<nav class="navbar navbar-inverse">


<div class="navbar-header">
<a class="navbar-brand" href="{{ URL::to('nerds') }}">Nerd Alert</a>

21
</div>
<ul class="nav navbar-nav">
<li><a href="{{ URL::to('nerds') }}">View All Nerds</a></li>
<li><a href="{{ URL::to('nerds/create') }}">Create a Nerd</a>
</ul>
</nav>
<h1>Showing {{ $nerd->name }}</h1>

<div class="jumbotron text-center">


<h2>{{ $nerd->name }}</h2>
<p>
<strong>Email:</strong> {{ $nerd->email }}<br>
<strong>Level:</strong> {{ $nerd->nerd_level }}
</p>
</div>
</div>
</body>
</html>

pas14. Modificare inregistrare curenta cu click pe butonul edit this nerd se apeleaza pagina
edit.blade.php iar in controller functia update. in care se valideaza datele si daca sunt corecte se face
modificarea in tabela nerds altfel se afiseaza mesaj de eroare.

<!-- app/views/nerds/edit.blade.php -->

<!DOCTYPE html>
<html>
<head>
<title>Look! I'm CRUDding</title>
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">

<nav class="navbar navbar-inverse">


<div class="navbar-header">
<a class="navbar-brand" href="{{ URL::to('nerds') }}">Nerd Alert</a>
</div>
<ul class="nav navbar-nav">
<li><a href="{{ URL::to('nerds') }}">View All Nerds</a></li>
<li><a href="{{ URL::to('nerds/create') }}">Create a Nerd</a>
</ul>
</nav>

<h1>Edit {{ $nerd->name }}</h1>

22
<!-- if there are creation errors, they will show here -->
{!! Html::ul($errors->all()) !!}

{!! Form::model($nerd, array('action' => array('NerdController@update', $nerd->id), 'method' => 'PUT'))


!!}

<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', null, array('class' => 'form-control')) !!}
</div>

<div class="form-group">
{!! Form::label('email', 'Email') !!}
{!! Form::email('email', null, array('class' => 'form-control')) !!}
</div>

<div class="form-group">
{!! Form::label('nerd_level', 'Nerd Level') !!}
{!! Form::select('nerd_level', array('0' => 'Select a Level', '1' => 'Sees Sunlight', '2' =>
'Foosball Fanatic', '3' => 'Basement Dweller'), null, array('class' => 'form-control')) !!}
</div>

{!! Form::submit('Edit the Nerd!', array('class' => 'btn btn-primary')) !!}

{!! Form::close() !!}

</div>
</body>
</html>

pas 15. Stergere inregistrare curenta la click pe butonul Delete this nerd care in view index.blade.php
avem codul sursa care apeleaza in controller functia destroy

{!! Form::open(array('url' => 'nerds/' . $value->id, 'class' => 'pull-right')) !!}


{!! Form::hidden('_method', 'DELETE') !!}
{!! Form::submit('Delete this Nerd', array('class' => 'btn btn-
warning')) !!}
{!! Form::close() !!}

23
Pt a crea o aplicatie de gestiune a cartilor se poate consulta

http://georgehk.blogspot.ro/2015/04/crud-operations-in-laravel-5-with-mysql.html?spref=bl

https://scotch.io/tutorials/simple-laravel-crud-with-resource-controllers

https://medium.com/@connorleech/create-and-edit-records-form-reuse-in-laravel-5-3-f70a4b1d5f9b

http://www.itechempires.com/2016/07/laravel-5-crud-operations/

http://www.hc-kr.com/2016/10/laravel-5-crud-using-ajax-modals.html

https://mattstauffer.co/blog/the-auth-scaffold-in-laravel-5-2

24
O aplicaie cu autentificare

pas1: Creare Migration

Creare tabela User in baza de date todo

php artisan make:migration create_users_table create=users

rezultat se creaza in directorul app/database/migrations fisierul

Dup adaptare fiierului de mai sus se executa pasul 1 in cmd

Pas3: php artisan migrate

Pas4. Creare Eloquent Model pt tabelul User. In cmd se introduce comanda php artisan
make:model User

in D:\wamp\www\TestingLaravel\app apare fisier User.php i se introduce variabila $fillable

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable


{
/**
* The attributes that are mass assignable.

25
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];

/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}

pas6. Se verific MySql daca nu exist n baza de date totdo tabela users at aceasta se creaza si rezulta
astfel:

pas7: php artisan make:auth

se creaza directorul auth in caleaD:\wamp\www\TestingLaravel\resources\views\auth

directorul va contine

26
Rolul comenzii este:

1.se utilizeaz pt aplicaii noi i va instala o vizualizare a aspectului, se va instala automat un layout view
pentru login, autentificare, precum i o ruta pentru toate punctele de autentificare.

2. Un HomeController va fi, de asemenea, pentru a gestiona cererile post-login la dashboard

In directorul Controller avem

HomeController.php se adapteaza astfel incat va contine

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Auth;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class HomeController extends Controller


{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;

/**
* Where to redirect users after login / registration.
*

27
* @var string
*/
protected $redirectTo = '/';

/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}

/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('home');
}
public function getLogout(){
Auth::logout();
return redirect('/home');
}
public function homeRegister(){
Auth::register();
return redirect('/home');
}

ne asiguram ca Auth\AuthController contine

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

28
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/

use AuthenticatesAndRegistersUsers, ThrottlesLogins;

/**
* Where to redirect users after login / registration.
*
* @var string
*/
// protected $redirectTo = '/';

/**
* Create a new authentication controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'getLogout','except' => 'homeRegister']);
}

/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}

/**

29
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}

public function getRegister()


{
if (! Auth::user()->is_admin == '1')
return abort(403);

return $this->showRegistrationForm();
}

/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function postRegister(Request $request)
{
if (! Auth::user()->is_admin == '1')
return abort(403);

return $this->register($request);
}
public function getLogout(){
Auth::logout();
return redirect('/home');

}
public function homeRegister(){
//Auth::register();
return redirect('/home');
}

30
In routes.php va contine

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
// Authentication routes...
//Route::auth();
//Route::get('auth/login', 'Front@login');
//Route::post('auth/login', 'Front@authenticate');
//Route::get('auth/logout', 'Front@logout');

// Registration routes...
//Route::post('/register', 'Front@register');

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

//Route::get('contact','WelcomeController@contact');

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

//Route::auth();
//Route::get('/home', 'HomeController@index');

//Route::resource('articles', 'ArticlesController');
//Route::get('articles','ArticlesController@index');
//Route::get('articles/create','ArticlesController@create');
//Route::post('articles', 'ArticlesController@store');
//Route::get('articles/{id}','ArticlesController@show');

//Route::resource('articles', 'ArticlesController@index');
Route::get('articles', [
'as' => 'article',
'uses' => 'ArticlesController@index'
]);
//Route::group(['middleware' => 'auth'], function () {
//Route::auth();
Route::get('register', 'Auth\AuthController@getRegister');
Route::post('/register', 'Auth\AuthController@postRegister');

31
Route::auth();
Route::get('/home', 'HomeController@index');
Route::get('/logout', 'HomeController@getLogout');

Route::resource('nerds', 'NerdController');
Route::get('nerds', [
'as' => 'nerd',
'uses' => 'NerdController@index'
]);

//Route::get('/', 'TaskController@index');
Route::group(['middleware' => 'auth'], function(){
Route::resource('tasks', 'TaskController');
});
//}

In directorul public ne asiguram sa existe subdiretoarele css, font i js care sunt necesare lui Bootstrap

In D:\wamp\www\TestingLaravel\resources\views\layouts vom avea app.blade.php care va contine

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Laravel</title>

<!-- Fonts -->


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-
awesome.min.css" integrity="sha384-
XdYbMnZ/QjLh6iI4ogqCTaIjrFk87ip+ekIjefZch0Y+PvJ8CDYtEs1ipDmPorQ+" crossorigin="anonymous">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700">

<!-- Styles -->


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-
bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-
1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
{{-- <link href="{{ elixir('css/app.css') }}" rel="stylesheet"> --}}

<style>
body {
font-family: 'Lato';
}

32
.fa-btn {
margin-right: 6px;
}
</style>
</head>
<body id="app-layout">
<nav class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">

<!-- Collapsed Hamburger -->


<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-
target="#app-navbar-collapse">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>

<!-- Branding Image -->


<a class="navbar-brand" href="{{ url('/') }}">
Laravel
</a>
</div>

<div class="collapse navbar-collapse" id="app-navbar-collapse">


<!-- Left Side Of Navbar -->
<ul class="nav navbar-nav">
<li><a href="{{ url('/home') }}">Home</a></li>

</ul>

<!-- Right Side Of Navbar -->


<ul class="nav navbar-nav navbar-right">
<!-- Authentication Links -->
@if (Auth::guest())
<li><a href="{{ url('/login') }}">Login</a></li>
<li><a href="{{ url('/register') }}">Register</a></li>
@else
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-
expanded="false">
{{ Auth::user()->name }} <span class="caret"></span>
</a>

<ul class="dropdown-menu" role="menu">


<li><a href="{{ url('/logout') }}"><i class="fa fa-btn fa-sign-out"></i>Logout</a></li>

33
</ul>
</li>
@endif
</ul>
</div>
</div>
</nav>

@yield('content')

<!-- JavaScripts -->


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js" integrity="sha384-
I6F5OKECLVtK/BL+8iSLDEHowSAfUo76ZL9+kGAgTRdiByINKJaqTPH/QVNS1VDb"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
crossorigin="anonymous"></script>
{{-- <script src="{{ elixir('js/app.js') }}"></script> --}}
</body>
</html>

in directorul D:\wamp\www\TestingLaravel\resources\views vom sala paginile:

1. login.blade.php-pagina de login

@extends('layouts.app')

@section('content')
<section id="form"><!--form-->
<div class="container">
<div class="row">
<div class="col-sm-4 col-sm-offset-1">
<div class="login-form"><!--login form-->
<h2>Login to your account</h2>
<form method="POST" action="{{url('auth/login')}}">
{!! csrf_field() !!}
<input type="email" name="email" id="email" placeholder="Email Address" />
<input type="password" name="password" id="password" placeholder="Password" />
<span>
<input name="remember" id="remember" type="checkbox" class="checkbox">
Keep me signed in
</span>
<button type="submit" class="btn btn-default">Login</button>
</form>
</div><!--/login form-->
</div>
<div class="col-sm-1">

34
<h2 class="or">OR</h2>
</div>
<div class="col-sm-4">
<div class="signup-form"><!--sign up form-->
<h2>New User Signup!</h2>
<form method="POST" action="{{url('register')}}">
{!! csrf_field() !!}
<input type="text" name="name" id="name" placeholder="Name">
<input type="email" name="email" placeholder="Email Address"/>
<input type="password" name="password" placeholder="Password">
<button type="submit" class="btn btn-default">Signup</button>
</form>
</div><!--/sign up form-->
</div>
</div>
</div>
</section><!--/form-->
@endsection
3.register.blade.php-pagina de inregistrare

@extends('layouts.app')

@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Register</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}">
{{ csrf_field() }}

<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">


<label for="name" class="col-md-4 control-label">Name</label>

<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{
old('name') }}">

@if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
@endif
</div>
</div>

<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">

35
<label for="email" class="col-md-4 control-label">E-Mail Address</label>

<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{
old('email') }}">

@if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>

<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">


<label for="password" class="col-md-4 control-label">Password</label>

<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password">

@if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
@endif
</div>
</div>

<div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">


<label for="password-confirm" class="col-md-4 control-label">Confirm
Password</label>

<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control"
name="password_confirmation">

@if ($errors->has('password_confirmation'))
<span class="help-block">
<strong>{{ $errors->first('password_confirmation') }}</strong>
</span>
@endif
</div>
</div>

<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-user"></i> Register

36
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
4. home.blade.php dashboard-ul pe baza caruia vom apela nerd.php I task.php

@extends('layouts.app')

@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>

<div class="panel-body">
<div>

</div>
<div>
<a href="{{ URL::to('nerds') }}">View All Nerds</a>
</div>
<div>
<a href="{{ URL::to('tasks') }}">View All Task</a>
</div>
</div>
</div>
</div>
</div>
</div>
@endsection

Pt a introduce in autentificare nerd si task am modificat

la Nerd 1. index.blade.php

<!DOCTYPE html>
<html>

37
<head>
<title>Look! I'm CRUDding</title>
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

</head>
<body>
<div class="container">

<nav class="navbar navbar-inverse">

<div class="navbar-header">
<a class="navbar-brand" href="{{ URL::to('nerds') }}">Nerd Alert</a>
</div>
<ul class="nav navbar-nav">
<li><a href="{{ URL::to('nerds') }}">View All Nerds</a></li>
<li><a href="{{ URL::to('nerds/create') }}">Create a Nerd</a></li>

</ul>
</nav>
@extends('layouts.app')
<h1>All the Nerds</h1>
<!-- will be used to show any messages -->
@if (Session::has('message'))
<div class="alert alert-info">{{ Session::get('message') }}</div>
@endif

<table class="table table-striped table-bordered">


<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Nerd Level</td>
<td>Actions</td>
</tr>
</thead>
<tbody>
@foreach($nerds as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
<td>{{ $value->nerd_level }}</td>

<!-- we will also add show, edit, and delete buttons -->
<td>

38
<!-- delete the nerd (uses the destroy method DESTROY /nerds/{id} -->
<!-- we will add this later since its a little more complicated than the
first two buttons -->
{!! Form::open(array('url' => 'nerds/' . $value->id, 'class' => 'pull-right'))
!!}
{!! Form::hidden('_method', 'DELETE') !!}
{!! Form::submit('Delete this Nerd', array('class' => 'btn btn-
warning')) !!}
{!! Form::close() !!}

<!-- show the nerd (uses the show method found at GET /nerds/{id} -->
<a class="btn btn-small btn-success" href="{{ URL::to('nerds/' . $value-
>id) }}">Show this Nerd</a>

<!-- edit this nerd (uses the edit method found at GET /nerds/{id}/edit --
>
<a class="btn btn-small btn-info" href="{{ URL::to('nerds/' . $value->id .
'/edit') }}">Edit this Nerd</a>

</td>
</tr>
@endforeach
</tbody>
</table>

</div>
</body>
</html>

si la taskl

in create.blade.php; edit.blade.php;list.blade.php, show.blade.php am introdus linia

@extends('layouts.app')

39
pt a avea un proiect compact in routes.php se creaza un cod sursa de genul:

Route::group(['middleware' => 'auth'], function(){


Route::get('/about', 'AboutController@index');
Route::get('/home', 'HomeController@index');
});

Daca doriti sa aprofundati

40
1. http://bgui.github.io/php-the-right-way//#sabloane_de_proiectare---exista exemplu de testare

2. https://www.codecourse.com/lessons/eloquent-by-example

41

S-ar putea să vă placă și