Despre middleware-uri in laravel

postat acum un an de Stefanescu Mihai in categorie iNoob

HTTP Middleware este un mecanism ce ne ajuta la filtrarea cererilor HTTP de a ajunge in aplicatia ta. In Laravel, de exemplu avem un middleware ce ne ajuta sa verificam daca un utlizator este autentificat.

La ce putem folosi Middleware

Iata unde va poate fi de folos un middleware. 

  • Daca lucrati la un api puteti face un middleware pentru a confirma  API key-ul
  • Putem schimba limba site-ului in functie de zona in care ne aflam
  • Putem porni modul de maintanance

La sfarsitul acestui articol ve-ti avea idee cum puteti crea un middleware si cum il puteti folosi in proiectul vostru. Pentru a va ajuta sa inetlegeti un middleware am sa fac impreuna cu voi un middleware ce va afisa un mesaj de mentenanta pe tot site-ul sau numai pe anumite rute.

Crearea unui middleware

Cu ajutorul artisan putem face un middlware foarte simplu, tot ce trebuie sa facem este sa deschidem un terminal si sa scriuem urmatoarea comanda:

php artisan make:middleware [nume middleware]

Aceasta comanda va crea un fisier nou in app/Http/Middleware.

Iata comanda executata de mine:

php artisan make:middleware DownForMaintenance

Acum putem deschide fisierul middleware si putem adauga codul. Primul lucru pe care trebuie sa-l facem este sa importam HttpException astfel:

use Symfony\Component\HttpKernel\Exception\HttpException;

In metoda handle a middleware-ului putem adauga acest cod:

public function handle($request, Closure $next){ 
    throw new HttpException(503);

Aruncand aceasta exceptie laravel va afisa view-ul 503.blade.php care ar trebuii sa le afiseze un mesaj cum ca site-ul este in mentenanta.

Inregistrarea unui Middleware

Acum ca am creat un middleware trebuie sa anuntam si apicatia despre existenta acestuia. Daca doriti ca acest middleware sa poata fi folosit  la fiecare request intrati in app/Http/kernel.php si adaugati  urmatorul cod in array-ul $middleware:

'down.for.maintenance' => \App\Http\Middleware\DownForMaintenance::class,

Atasarea unu middleware unei rute

Stim deja cum arata o ruta:

Route::get('posts/{parametru}', 'PostController@getPost');

Metoda getPost din controller-ul PostController este rulata atunci cand este accesat link-ul posts/{parametru}

Putem adauga acest middleware rutei schimband ce-l de-al doilea parametru din string in array astfel:

Route::get('posts/{parametru}', ['middleware' => '', function () { return "NU! Nu vreau sa vezi aceasat pagina!";}]);

Acum daca cineva acceseaza ruta posts/{parametru} nu va mai ajunge in controller, ci va putea sa vada numai o pagina cu un mesaj.

Parametri in middleware

Pasarea de parametri unui middleware este destul de simpla. De exemplu, poate dorim sa verificam ce rol are utilizatorul care a accesat aceasta ruta, putem pasa atat un rol cat si o lista cu toate rolurile.

Pentru a pasa un parametru unui middleware,dupa $request si Closure adauga variabila ce dorim sa fie preluata ca parametru:

public function handle($request, Closure $next, $role){ 
    if (! $request->user()->hasRole($role)) { 
              // Redirect... 
    return $next($request);

Pentru a pasa o variabila cand atasam un middleware unei rute facem astfel:

Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) { //}]);


In acest articol am vorbit numai despre un mod in care poate fi folosit un middleware, de fapt le puteti folosi intr-o multume de moduri.

Pentru orice nelamurire puteti lasa un comentariu mai jos sau puteti posta pe forum aici:

Sunt un tanar programator din Bucuresti ce lucreaza in PHP/Mysql (MySqli/PDO), Laravel, CodeIgniter, MySQL, PostgreSQL, Wordpress, HTML5/CSS3, Sass, Photoshop si multe altele.
Google+ Community Facebook Group
Comentariu postate de Ilisei Cristian la data de 20.02.2017
salut , incerc sa fac un site laravel si nu reusesc sa fac sa fie in 2 limbi ( ro & en ) , vreau ca implicit limba sa fie romana, mentionez ca lucrez pe laravel 5.0 deoarece easyphp-ul in care lucrez nu-mi da voie sa folosesc laravel 5.4 . Ma puteti ajuta ? va multumesc
Comentariu postate de ??? ?? ?? la data de 25.07.2017
Good aanswer back in return of this difficulty with genuine arguments aand explaining all concerning that.
Comentariu postate de social media strategy la data de 31.07.2017
Greetings from California! I'm bored to tears at work so I decided to check out your blog on my iphone durring lunch break. I love thhe information you provide here and can't wait to take a look when I get home. I'm shocked at how quick your blog loaded on my cell phone .. I'm not even using WIFI, just 3G .. Anyhow, superb blog!
Comentariu postate de water damage los angeles la data de 01.08.2017
What's up colleagues, how is all, and what you wish for to say on the topic of this piece of writing, in my view its in fact remarkable in favor of me.
Comentariu postate de Cara la data de 11.08.2017
What's Happening i'm new to this, I stumbled upon this I've found It positively useful and it has helped me out loads. I am hoping to give a contribution & help different users like its aided me. Great job.
Comentariu postate de trolley coins la data de 20.08.2017
I'vebeen surffing online more than 3hours today, yet I never found any interesting article like yours. It's ptetty worth enough forr me. In my opinion, if all webmasters and bloggers made good content as you did, the internet wilkl be a lot more useful than evewr before.| I could not resist commenting. Exceptionally well written!| I'll right away clytch your rsss as I can't to find your email subscription hyperlink or newsletter service. Do you hav any? Please let me realize in order that I could subscribe. Thanks.| It's appropriate time to make some plans for the future and it's tume to be happy. I have read this post and if I could I desire to sugest you some interesting things or suggestions. Maybe you cann write next articles referring to this article. I desire too read even more things about it!| It is the best time to make a few plans for the longer term and it's time to be happy. I have read this publish and if I may I ddesire to counsel you few interesting things or tips. Perhaps you can write next articles referring to this article. I desire to learn even more issues abouut it!| I have been surfing on-line more than 3 hous these days, but I by no meaqns discovered any attention-grabbing article like yours. It's beautiful value sufficient for me. In my view, if all website owners and bloggers made just right content material as you did, the net can bee a lot more useful than ever before.| Ahaa, its pleasant conversation concerning this post here at tis website, I have read all that, soo now me also commenting here.| I am sure thhis piecee of writing has touched all the imternet users, its really really nice paragraph on building up new web site.| Wow, this paragraph is pleasant, my sister is analyzing these kinds of things, therefore I am going to tel her.| Saved as a favorite, I love your blog!| Way cool! Somee extremely valid points! I appreciate you writing this write-up and the rest off thee site is also really good.| Hi, I do think this is a great website. I stumbledupon it ;) I will come back yet again since I book-marked it. Money and freedom is the best way to change, may you be rich aand continue to help other people.| Woah! I'm really digging the template/theme of this blog. It's simple, yet effective. A lot of times it's hard to get that "perfect balance" between superb usabiliity and visual appearance. I mustt say you have done a great job with this. Additionally, the blog loads very fast for me on Opera. Superb Blog!| These are genuinnely great ideas in on the topic of blogging. You have touched some nice factors here. Any way keep upp wrinting.| I love what yyou guys are usually up too. This sort of clever work and exposure! Keep up the very good works guyss I've addesd yyou guys to blogroll.| Hi! Someone in my Facebook group sharded this website with us so I csme to check iit out. I'm definitely loving the information. I'm book-marking and will be tweeting this tto my followers! Wonderful blog and wonderful design.| I love what you guys tend too be up too. This kind of clever work and exposure! Keep up the grreat works guys I've added you guys to my own blogroll.| Hi there would you mind stating which blg platform you're using? I'm planning too start my own bloig soon but I'm having a difficult timme selecting between BlogEngine/Wordpress/B2evolution andd Drupal. The reason I ask is because your design and style seems different then most blogs and I'm looking for something commpletely unique. P.S My apologies for getting off-topic butt I had to ask!| Hello would you mnd letting me know which webhost you're working with? I've loaded your blog in 3 completely different browsers annd I must say this blog loads a lot quicker then most. Can you suggest a good hosting provider at a fair price? Cheers, I appreciate it!| Everyone loves it when individuals gget together and share thoughts. Greawt site,stick with it!| Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how can we communicate?| Hi there just wanted to give you a quick headfs up. The words in ylur post seem to be running off the screen in Chrome. I'm not sure if this is a formatting issue oor somethig to do with web browser compatibility but I thought I'd post to let you know. The design look great though! Hope you gget the issue solved soon. Thanks| This is a topic that is close to my heart... Cheers! Where are your contgact details though?| It's very trouble-free to finhd out any topic on web as compared to books, ass I found this piece off writing at this website.| Does your website have a contact page? I'm having a tough ttime loccating it but, I'd like to shoot youu an email. I've got some reative ideas for your blog you might bee interested in hearing. Either way, great website andd I look forward to seeing it develop over time.| Hola! I've been following ypur web site for a long time noww and finally got the courage to go ahead and give you a shout ouut from Dallas Texas! Just wanted to mention keep up the good work!| Greetings fropm Carolina! I'm bored at work so I decided to check out your siute on my iphgone during lunch break. I really like the knowedge you present here and can'twait to take a look when I get home. I'm surprised aat how fast your blog loaded on my mobile .. I'm not even usinjg WIFI, jusxt 3G .. Anyhow, awesome blog!| Itss like you read my thoughts! You appear to know so much about this, suchh as you wrote the e-book in it or something. I think that you juet could do with some percent to force the message home a little bit, however othher than that, this is fantastic blog. An excelent read. I will definitely be back.| I visited multiple web pages except the audio quality for auudio songs current at thks website is actually superb.| Howdy, i read your blog from time to time and i own a similar one and i was juszt wondering if you get a lot of spam remarks? If so how do you protect against it, any plugin or anything you can recommend? I gget so much lately it's driving me crazy so any support is very much appreciated.| Greetings! Very helpful advice within this article! It's the little changes that will ake the most important changes. Thanks for sharing!| I really love your site.. Pleasant colors & theme. Did you create this web sute yourself? Please reply back as I'm trying to create my own personal site and would lopve to fibd oout wjere you got this from or what the theme is called. Cheers!| Hello there! This article could not be written much better! Gong throuh this artucle reminds me of myy previous roommate! He always kept talking about this. I'll send this infordmation to him. Fairly certain he'll have a good read. Thank you for sharing!| Wow! Thhis blog looks exactly like my oold one! It's on a completely different topic but it has pretty much tthe same layout and design. Outstanding choice of colors!| There's definately a lot to find ouut about this issue. I love all the points you have made.| You made some really good points there. I checked on the web ffor more info about the issue and found most people will go along with your views on tis web site.| Hi there, I read your blogs daily. Your story-telling style is awesome, keep it up!| I simmply could not leave your web site before suggesting that I really loved the standard info a person supply for your visitors? Is gonna be back frequently in order to inspect new posts| I nereded to thank you for this wonderful read!! I definitely loved every little bit of it. I have yyou saved as a favorite to check ouut new stuff you post…| Hello, just wanted to say, I liked this article. It was funny. Keep on posting!| Hi there, I eenjoy reading all of our article. I wanted to write a little comment to support you.| I constantly spent my half an hour to read this webpage's coontent everyday along with a cup of coffee.| I all the time emailed this blog post page to all my associates, for the reaskn that if like to read it next my friends will too.| My developer is trying to convionce me to move to .net ffrom PHP. I have always disliked the idea because of the costs. But he's tryiong none the less. I've been using WordPress on several websites for bout a yeaar and am anxious about switching to another platform. I have heard very good things about Is there a way I can transfer all my worrdpress posts into it? Any help ould be really appreciated!| Hello there! I could have ssworn I've been to this blog before but after looking aat a few off the posts I realized it's new to me. Anyways, I'm certainly pleased I came across it and I'll be book-marking it and checking back often!| Great article! Thaat is the type of info that should be shared around the internet. Disgrace on the search engines foor no longer positioning this publish upper! Come on over and seek advice from my wedbsite . Thank you =)| Heya i'm for the first time here. I found this board aand I find It really useful & it helped me out much. I hope to give something back and aid others like yyou helped me.| Hello there, There's no doubt that your blog might be having web browser compatibility problems. Whenever Itake a look att our web site in Safari, it looks fine however when opening in IE, it has some overlapping issues. I merely wanted to provide you with a quick heads up! Apart from that, wonderful website!| Someone necessarily help to make seriously articles I might state. This is the very first time I frequented your web page and upp to now? I amazed with the research you made tto create this actual submit incredible. Wonderful process!| Heya i am for the primary time here. I found this board and I to find It really helpful & it helped me out a lot. I am hoping to give one thing back and aid others such as you aided me.| Hey there! I simply want to offer you a hyge thumbs up for the excellent information yoou have here on this post. I am returning to your web site ffor more soon.| Ialll thhe time used to rewad piece of writing in news papers but noww as I am a usser of web ths from nnow I am usung net for content, thanks to web.| Your mde of explainingg everything in this piece of writing is inn faft nice, alll be capable of easily know it, Thanks a lot.| Hi there, I found your blog via Google whhile searrching for a similar subject, your siute got hete up, it seems to be good. I have bookmarkked it in mmy google bookmarks. Hello there, simply chanted into aware of your weblog through Google, and located that it is really informative. I'm gonna be carefful for brussels. I will appreciate should you continue this in future. A lot of other people will probably be benefited from your writing. Cheers!| I am curious to find out what blog system yoou are working with? I'm having some small security problems with my latest site annd I'd like to find something more safe. Do you hsve any suggestions?| I am really impressed with your writing skills and also with the layout on ykur weblog. Is this a paidd theme or did you customize it yourself? Anyway keep up the excellent quality writing, iit is rare to see a nice blog like this oone these days.| I'm really inspired together with your wriing skills ass neatly as with the format to your blog. Is that this a paid subject or ddid you modify it your self? Anyway keep up the nice quality writing, it is uncomnmon to look a great blog like this one nowadays..| Hello, Neat post. There is a problem with your site in web explorer, may check this? IE still is the marketplace chief and a huge component to people will omit your great witing because of this problem.| I am not sure where you're getting your info, but good topic. I needs to spend some time learning much more or understanding more. Thanks for magnificent inhfo I was looking for this information for my mission.| Hi, i think that i saw you visited my blog so i ccame to “return the favor”.I'm attempting to find things to improve mmy site!I suppose itts ok to use a few of yo\