La Ravel
La Ravel
La Ravel
1.
Intai se downloadeaza si se instaleaza composerul
In CLI exista o serie de comnezi disponibile pentru composer pe care le putem afla cu
composer list
2.
apoi se instaleaza laravel
- fie prin comanda directa in CLI:
composer create-project laravel/laravel --prefer-dist
- downloadam "Laravel installer PHAR archive" apoi in CLI :
laravel new numelefolderului
- fie downloadam ultima versiune a laravel si extragem continutul intru folder pe server
apoi in CLI:
selecta directrorul root al laravel si dam comanda:
composer install
Acest proces necesita ca Git sa fie instalat in prealabil
3.
Apoi mergem in xampp/apache/conf/httpd.conf la linia 243
Document root si 244 Directory si modificam
din C:/xampp/htdocs in C:/xampp/htdocs/laravel/public
Astfel cand tastam in browser localhost/ va aprea route de baza si nu va fi nevoie sa
scriem C:/xampp/htdocs/laravel/public
4.
In acelasi fisier xampp/apache/conf/httpd.conf trebuie sa verificam daca
xampp/apache/conf/httpd.conf este activat (nu trebuie sa fie comentat)
CONFIGURATION
By default toate configuratiile din app/configure sunt setate pentru environment
production.
- App::environment()
- app()->environment()
- app()->env
- $GLOBALS['env'] // nu e recomandat , dar e posibil
Pentru a verifica daca suntem intr-un anumit mediu (sau mai multe)
if (App::environment('local', 'staging'))
{
// The environment is either local OR staging...
}
Pentru a seta alte environment decat cel default ( productie) vom modifica boostrap/start:
$env = $app->detectEnvironment(array(
'local' => array('philips-mbp.home'),
'staging' => array('staging-server'),
'production' => array('production-server')
));
$env = $app->detectEnvironment(function()
{
return $_SERVER['MY_LARAVEL_ENV'];
});
Un dot file este un fisier pozitionat in directorul de baza laravel care contine informatii
sensitive sau detalii care sunt legate strict de mediul in care lucrezi.
Pentru fiecare mediu se poate crea un nou dot file.
NU DENUMITI fisierul cu termenul de ‘testing’ deoarece acesta este folosit pentru UNIT
TESTING.
De ex:
Pentru a pastra ascunse informatiile despre baza de date.
Se poate creea un fisier nou cu numele:
.env.local.php care va fi pozitionat in directorul de baza. In interiorul lui vom returna o
matrice de perechi key valori specifice mediului current(local)
<?php
return array(
'DATABASE_NAME' => 'my_database',
'DATABASE_USER' => 'username',
'DATABASE_PASSWORD' => 'totally_secure_password'
);
Astfel cand lucram in mediul local, laravel va prelua configuratiile specifice despre baza
de date.
Mainteince mode
Pentru a trece aplicatia in modul mainteince modificam app/start/global:
App::down(function()
{
return Response::view("view_utilizat", array() , 503);
});
Artisan vine la pachet cu laravel daca e instalat in CLI prin composer install.
Pentru a vedea comenzile disponibile tasteaza in folderol root in CLI: php
artisan list.
Pentru a vedea comenzile disponibile in composer tasteaza in CLI: composer list
In bootstrap/start.php putem
- seta mediul de lucru astfel:
$env = $app->detectEnvironment(function()
$env = $app->detectEnvironment(array(
'local' => array('your-machine-name'),));
- setam mediul de lucru intrun mod dinamic
$env = $app->detectEnvironment(function()
{ return $_SERVER['MY_LARAVEL_ENV']; });
Daca dorim sa facem o migratie intrun alt mediu vom specifica asta in CLI :
$ php artisan migrate --env=local
Artisan command
Pe langa toate comenzile disponibile din CLI putem defini propria noastra comanda in
app/commands sau oricunde alt undeva caza in care trebuie sa fim atenti sa poate fi
incarcate de composer.json.
1. Pentru a creea o comanda tastam in CLI
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::guest('login');
});
Route::when('admin/*', 'admin');
Toate URL care sunt namespaced sub folderol admin/*
vor fi filtrate automat.
ROUTES
1. Route::get( '/', function(){ return 'Hello World'; });
- primul parametru este pagina din browser
- al doilea paremtru este functia closure ca raspuns la accesarea paginii
- get sa foloseste la accesarea unei pagini, post la crearea sau updatare
2. Route::match(array('GET', 'POST'), '/', function(){ return 'Hello World';});
- primul parametru contine tipul de accesare
- al doilea este pagina din browser
- al treilea parametru este functia closure
3. Route::any('foo', function(){ return 'Hello World';});
- pentru orice tip de accesare
4. Route::get('foo', array('https', function(){ return 'Must be over HTTPS';}));
- fortam un route sa fie HTTPS
5. URL::to('foo')
- genereaza url catre un anume route
23. URL::route('profile');
- definim un URL catre un route
24. Redirect::route('profile');
- redirectionam catre un route din alt route
25. Route::currentRouteName();
- accesam numele route care lucreaza momentan
Route::get('user/profile', function()
{ // Has Auth Filter });
});
- aplicam un filter unui grup de route
33. App::abort(404);
- utilizam pentru a chema o pagina cu eroare din route
Request & Input
1. Input::get(‘name);
- Accesam valorile din form dupa name din form
2. Input::get(‘name’,’default_value’)
- Setam o valoare default in cazul in care in form nu exista un name specificat
3. Input::all();
- Stocam intro matrice toate valorile din form
4. if (Input::has('name'))
- verificam daca exista in matricea Input un element cu name specificat
5. Input::only('username', 'password')
- Returnam doar anumite valori din Input
6. Input::except('credit_card')
- Returnam toate valorile mai Input mai putin pe cele specificate
7. Input::get('products.0.name')
- Cand vrem sa accesam in interiorul matricei putem folosi .
11. Cookie::get('name')
- Returnam valoarea unui cookie dupa nume
12. Input::flash()
- Trimitem o valoarea catre session pana la urmatoarea cerere
14. Input::flashExcept('password');
- Trimite toate valorile mai putin cele specificate
15. Redirect::to('form')->withInput(Input::except('password'))
- Dupa validare vom trimite inputurile catre form din pagina precedenta
16. Input::old('username')
- Daca validarea nu a reusit , insa valoarea introdusa a fost corecta, vom folosi
aceasta metoda pentru a accesa vechea valoare introdusa
17. Input::file('photo')
- Returneaza un fisier incarcat
18. Input::hasFile('photo')
- Verifica daca exista un anumit input in form
19. Input::file('photo')->isValid()
- Verifica daca fisierul uplodad este valid
21. Input::file('photo')->getRealPath()
- Returneaza calea fisierului incarcat
22. Input::file('photo')->getClientOriginalName()
- Returneaza numele original al fisierului incarcat
23. Input::file('photo')->getClientOriginalExtension()
- Returneaza extensia fisierului
24. Input::file('photo')->getSize()
- Returneaza marimea unui fisier incarcat
25. Input::file('photo')->getMimeType()
- Returneaza tipul fisierului incarcat
26. Request::path()
- Returneaza tot doar URL incarcat
27. Request::method()
- Returneza tipul de metoda utilizat
28. Request::isMethod('post')
- Verifica daca tipul metodei este ca cel specificat
29. Request::is('admin/*')
- Verifica daca o anumita cerere verifica un anumit patern
30. Request::url()
- Returneaza calea completa
31. Request::segment(1)
- Returneaza numele secgemtul din URL specificat ca argument
32. Request::header('Content-Type')
- Returneaza un anumit header
33. Request::server('PATH_INFO')
- Returneaza valori din $_SERVER
34. Request::secure()
- Verifica daca cererea este sigura (secure)
35. Request::ajax()
- Determina daca cererea utilizeaza ajax
36. Request::isJson()
- Determina daca cererea are continut JSON
37. Request::wantsJson()
- Determina daca cererea cere continut JSON
1. Request::format()
- Returneaza formatul rasounsului la cerere bazanduse pe header Accept
Controller
2. URL::action(‘FooController@method’)
– pentru a accesa functionalitatea unei metode prin controller
3. action(‘FooController@method’)
– pentru a accesa functionalitatea unei motode prin controller (helper action)
4. URL::route(‘home’)
– pentru a acceas functionalitatea unei motode utilizsand numele routeului
5. Route::currentRouteAction()
– accesam numele metodei si al controlerului care este actionat momentan
8. Route::resource('photo', 'PhotoController');
- defineste un route care creeaza mai multe route care vor controla mai multe
actiuni asupra resursei atribuite.
Verb Path Action Route Name
RESPONSES
VIEWS
47. @section
@show
- defineste o sectiune in template unde va fi introdus text in view.
- Poate contine si un text in template care va fi mostenit in view daca se foloseste
@parent in view
- Folosit pentru sectiuni mari de text
-
48. @yield
- defineste o sectiune in template unde va fi introdus text in view
- putem defini un text default care va fi introdus in view daca nu exista in template
aceasta sectiune
- utilizat pentru a introduce in view sectiuni compacte precum: title, description
,css, javascript
49. Route::get('/',
function(){ return View::make('greeting', array('name' =>'Taylor'));});
- returnam un view in care introducem variabile
51. View::make('greeting')->withName('steve')
- returnam un view in care introducem variabile
57. View::composers(array(
'AdminComposer' => array('admin.index', 'admin.profile'),
'UserComposer' => 'user',
));
- putem define mai multi composeri simultan
1. $logFile = 'laravel.log';
Log::useDailyFiles(storage_path().'/logs/'.$logFile);
- Default laravel salveaza toate erorile intrun singur fisier localizat in
storage/log/laravel.log. Daca dorim ca erorile sa le salvam in fisierele separate
in functie de zi tot in storage/log vom folosi codul de mai sus in
app/start/global.
2. Daca vrem sa dezactivam afisarea de erori (ceea ce e indicat in modul productie) vom
seta optiunea debug ca FLASE in app/config/app.php
5. App::error(function(InvalidUserException $exception)
{ Log::error($exception);
return 'Sorry! Something is wrong with this account!';
});
- Daca un handler returneaza un rasouns, acel raspuns va fi afisat in browser si nici
un alt handler nu va mai fi chemat
6. App::fatal(function($exception){ // });
- Daca vrem sa prindem erori fatale atunci putem folosi App:fatal
- Daca definim mai multe handler pentru exceptii ele trebuie sa fie definite de la cel
mai general la cel mai specific
- Handelrele pot fi definite in start/global.php iar daca acesta devine prea aglomerat
putem creea un fisier app/errors.php
8. App::missing(function($exception)
{ return Response::view('errors.missing', array(), 404);});
- Daca vrem sa definim o pagina 404 personalizata
Vom returna din DB toate question si vor fi introduce in cache unde vor ramane 60
minute. Astfel in urmatoarea ora acest query ramanme in cache si toate cererile catre baza
de date vor lua informatia de aici.
E util atunci cand nu modificam baza de date frecvent.
$questions = Question::remember(60)->get();
Simple Laravel CRUD with Resource
Controllers
Creating, reading, updating, and deleting resources is used in pretty much every
application. Laravel helps make the process easy using resource controllers. Resource
Controllers can make life much easier and takes advantage of some cool Laravel routing
techniques. Today, we’ll go through the steps necessary to get a fully functioning CRUD
application using resource controllers.
For this tutorial, we will go through the process of having an admin panel to create, read,
update, and delete (CRUD) a resource. Let’s use nerds as our example. We will also make
use of Eloquent ORM.
To get started, we will need the controller, the routes, and the view files.
Nerd Migration
(This sounds like a bunch of nerds moving south for the winter). We need to set up a quick
database so we can do all of our CRUD functionality. In the command line in the root
directory of our Laravel application, let’s create a migration.
This will create our nerd migration in app/database/migrations. Open up that file and let’s add
name, email, and nerd_level fields.
// app/database/migrations/####_##_##_######_create_nerds_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNerdsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('nerds', function(Blueprint $table)
{
$table->increments('id');
$table->string('name', 255);
$table->string('email', 255);
$table->integer('nerd_level');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('nerds');
}
Now from the command line again, let’s run this migration. Make sure your database
settings are good in app/config/database.php and then run:
php artisan migrate
Our database now has a nerds table to house all of the nerds we CRUD (create, read, update,
and delete). Read more about migrations at the Laravel docs.
// app/models/Nerd.php
<?php
That’s it! Eloquent can handle the rest. By default, this model will link to our nerdstable and
and we can access it later in our controllers.
Let’s go ahead and do that. This is the easy part. From the command line in the root
directory of your Laravel project, type:
This will create our resource controller with all the methods we need.
// app/controllers/NerdController.php
<?php
class NerdController extends \BaseController {
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
}
// app/routes.php
<?php
Route::resource('nerds', 'NerdController');
This will automatically assign many actions to that resource controller. Now if you, go to
your browser and view your application at example.com/nerds, it will correspond to the proper
method in your NerdController.
Tip: From the command line, you can run php artisan routes to see all the routes associated with your
application.
The Views
Since only four of our routes are GET routes, we only need four views. In our app/views folder,
let’s make those views now.
app
o views
nerds
index.blade.php
create.blade.php
show.blade.php
edit.blade.php
In this function, we will get all the nerds and pass them to the view.
// app/controllers/NerdController.php
<?php
...
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
// get all the nerds
$nerds = Nerd::all();
...
Now let’s create our view to loop over the nerds and display them in a table. We like
using Twitter Bootstrap for our sites, so the table will use those classes.
<!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">
<!-- we will also add show, edit, and delete buttons -->
<td>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</body>
</html>
We can now show all of our nerds on a page. There won’t be any that show up currently
since we haven’t created any or seeded our database with nerds. Let’s move on to the form
to create a nerd.
Creating a New Resource nerds.create
In this function, we will show the form for creating a new nerd. This form will be processed
by the store() method.
// app/controllers/NerdController.php
<?php
...
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
// load the create form (app/views/nerds/create.blade.php)
return View::make('nerds.create');
}
...
<!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">
<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', Input::old('name'), array('class' => 'form-
control')) }}
</div>
<div class="form-group">
{{ Form::label('email', 'Email') }}
{{ Form::email('email', Input::old('email'), 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'),
Input::old('nerd_level'), array('class' => 'form-control')) }}
</div>
{{ Form::close() }}
</div>
</body>
</html>
We will add the errors section above to show validation errors when we try tostore() the
resource.
Tip: When using {{ Form::open() }}, Laravel will automatically create a hidden input field with a token to
protect from cross-site request forgeries. Read more at the Laravel docs.
We now have the form, but we need to have it do something when it the submit button gets
pressed. We set this form’s action to be a POST to example.com/nerds. The resource
controller will handle this and automatically route the request to the store() method. Let’s
handle that now.
Storing a Resource store()
Process the create form submit and save the nerd to POST example.com/nerds store() NONE
the database.
As you can see from the form action and the URL, you don’t have to pass anything extra into
the URL to store a nerd. Since this form is sent using the POST method, the form inputs will
be the data used to store the resource.
To process the form, we’ll want to validate the inputs, send back error messages if they
exist, authenticate against the database, and store the resource if all is good. Let’s dive in.
// app/controllers/NerdController.php
<?php
...
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'name' => 'required',
'email' => 'required|email',
'nerd_level' => 'required|numeric'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('nerds/create')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$nerd = new Nerd;
$nerd->name = Input::get('name');
$nerd->email = Input::get('email');
$nerd->nerd_level = Input::get('nerd_level');
$nerd->save();
// redirect
Session::flash('message', 'Successfully created nerd!');
return Redirect::to('nerds');
}
}
...
If there are errors processing the form, we will redirect them back to the create form with
those errors. We will add them in so the user can understand what went wrong. They will
show up in the errors section we setup earlier.
Now you should be able to create a nerd and have them show up on the main page! Navigate
to example.com/nerds and there they are. All that’s left is showing a single nerd, updating,
and deleting.
Showing a Resource show()
// app/controllers/NerdController.php
<?php
...
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
// get the nerd
$nerd = Nerd::find($id);
...
<!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">
</div>
</body>
</html>
To edit a nerd, we need to pull them from the database, show the creation form, but populate
it with the selected nerd’s info. To make life easier, we will use form model binding. This
allows us to pull info from a model and bind it to the input fields in a form. Just makes it
easier to populate our edit form and you can imagine that when these forms start getting
rather large this will make life much easier.
Controller Function edit()
// app/controllers/NerdController.php
<?php
...
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
// get the nerd
$nerd = Nerd::find($id);
...
<!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">
<!-- if there are creation errors, they will show here -->
{{ HTML::ul($errors->all()) }}
<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::close() }}
</div>
</body>
</html>
Note that we have to pass a method of PUT so that Laravel knows how to route to the
controller correctly.
Process the create form submit and save the nerd to PUT example.com/nerds update() NONE
the database.
This controller method will process the edit form. It is very similar to store(). We
willvalidate, update, and redirect.
// app/controllers/NerdController.php
<?php
...
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'name' => 'required',
'email' => 'required|email',
'nerd_level' => 'required|numeric'
);
$validator = Validator::make(Input::all(), $rules);
// redirect
Session::flash('message', 'Successfully updated nerd!');
return Redirect::to('nerds');
}
}
...
Deleting a Resource destroy()
Process the create form submit and save the DELETE example.com/nerds/ destroy() NONE
nerd to the database. {id}
The workflow for this is that a user would go to view all the nerds, see a delete button, click
it to delete. Since we never created a delete button in ourapp/views/nerds/index.blade.php, we
will create that now. We will also add a notification section to show a success message.
We have to send the request to our application using the DELETE HTTP verb, so we will
create a form to do that since a button won’t do.
Alert: The DELETE HTTP verb is used when accessing the nerds.destroy route. Since you can’t just create
a button or form with the method DELETE, we will have to spoof it by creating a hidden input field in our
delete form.
...
<!-- we will also add show, edit, and delete buttons -->
<td>
</td>
</tr>
@endforeach
...
Now when we click that form submit button, Laravel will use the nerds.destroy route and we
can process that in our controller.
// app/controllers/NerdController.php
<?php
...
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
// delete
$nerd = Nerd::find($id);
$nerd->delete();
// redirect
Session::flash('message', 'Successfully deleted the nerd!');
return Redirect::to('nerds');
}
...
Conclusion
That’s everything! Hopefully we covered enough so that you can understand how resource
controllers can be used in all sorts of scenarios. Just create the controller, create the single
line in the routes file, and you have the foundation for doing CRUD.
As always, let us know if you have any questions or comments. We’ll be expanding more on
Laravel in the coming articles so if there’s anything specific, throw it in the comments or
email us.