Despre middleware-uri in laravel

postat acum 9 luni 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}', '[email protected]');

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' => 'grown.ups.only', 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) { //}]);

Concluzie

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: http://www.invata-programare.ro/forums/topic/despre_middleware_in_framework-ul_laravel

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 Exe Packer la data de 16.02.2017
Hello, I enjoy reading all of your article. I wanted to write a little comment to support you. http://www.webtoolmaster.com/fr/index.htm
Comentariu postate de filme romantico gospel la data de 18.02.2017
Another way to permanently terminate a romance with Jack or Miranda is to complete both their loyalty missions without having enough Paragon points or Renegade points to avoid siding with one or the other of them. http://Romances.Blogbaker.com/
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 phone psychic reading la data de 22.02.2017
Very awesome post, i certainly love this site, keep writing.
Comentariu postate de free psychic reading hotline la data de 22.02.2017
You have noted terribly attention-grabbing things. Thanks for sharing.
Comentariu postate de phone psychic reading la data de 22.02.2017
This short article gives the light in which we can observe the reality. This is a very nice one and gives in-depth information. Thank you for this nice article.
Comentariu postate de Alonzo la data de 24.02.2017
I am sure this paragraph has touched all the internet people, its really really good piece of writing on building up new webpage. https://ashliduerr30147.wordpress.com/2016/12/29/warning-monster-truck-games/
Comentariu postate de beneficios de goji berry la data de 24.02.2017
Many customers have heard that Goji berries have very high antioxidant content, so they ask me, Do Goji berries have a lot of antioxidants?” After all, antioxidants are well-known for slowing down the aging process. http://star-crossed.or.kr/phpnuke/html/modules.php?name=Your_Account&op=userinfo&username=Ryder22I65
Comentariu postate de Leonor la data de 28.02.2017
I think this is one of the most important information for me. And i'm glad reading your article. But should remark on some general things, The website style is ideal, the articles is really great : D. Good job, cheers http://intensedebate.com/people/tawnyaheberling
Comentariu postate de 4rx pharmacy la data de 05.03.2017
Loved the photos, i actually like the one of this image, perfect. http://tinyurl.com/hnkthtw
Comentariu postate de http://www.siliconbraceletau.com/ la data de 10.03.2017
I have been browsing onlone more than 3 hours today, yet I never found any interesting article like yours. It's pretty woth ennough ffor me. In my opinion, if aall webmasters and bloggers made good content as you did, the web will be much moore useful than ever before.| I couldn't resist commenting. Perffectly written!| I'll right away grasp yourr rss as I can't find your e-mail subscription link or newsleetter service. Do you've any? Please let me understand so that I may just subscribe. Thanks.| It is perfect time to make some plans forr thee future and it's time to be happy. I've read thi post and if I could I wish to suggest you few interesting things or tips. Maybe you can write next articles referring to this article. I desire to read more thihgs about it!| It's the best time to make a few planns for the longer term and it is time to be happy. I have learn this submit andd if I may just I want too recommend you few fascinating issues or suggestions. Maybe you coul wrie subsequent articles relating to this article. I desire to learn more issues about it!| I've been browsing on-line more than thee hours lately, but I by no means found any interesting article like yours. It is lovely worth enough for me. In my opinion, if all website owners and bloggers made good content as you probably did, the web wjll be a lot more helpcul than ever before.| Ahaa,its fastidious conversation about this paragraph at this place at this web site, I have read all that, so now me also commenting here.| I aam sure this post has touched aall the internet people, its really really fastidious article on building up new web site.| Wow, this post iis pleasant, my younger sister is ahalyzing such things, so I am going to tell her.| bookmarked!!, I love your site!| Way cool! Some very valid points! I appreciate you penning this post and the rest of the site is very good.| Hi, I do bepieve this is a great blog. I stumbledupon it ;) I may come back yet again since I book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.| Woah! I'm really enjoying the template/theme of this blog. It's simple, yet effective. A lot of times it's tough to get that "perfect balance" between usability and appearance. I must say that you've done a fantastic joob with this. Also, the boog loads extremely fst for me on Firefox. Exceptional Blog!| These aare really fantastic ideas in concerning blogging. You have ttouched some good factors here. Any way keep up wrinting.| I love whatt you guys are up too. Thhis kind of clever work and coverage! Keep up the amazing works guys I've added you guys to mmy own blogroll.| Hi! Someone in my Myspace group shared this website with us so I came to give itt a look. I'm definitely enjoying the information. I'm bookmarking aand will be tweeting this to my followers! Great blog and terrific design and style.| I love what you guys are up too. This sort oof clever wolrk and exposure! Keep up thee great works guys I've incorporzted you gyys to blogroll.| Hoowdy would you mind stating whih blog platform you're using?I'm going to start my own blog soon but I'm having a tough time decidkng between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs andd I'm lookiing for something unique. P.S Apologies for getting off-topic but I had to ask!| Howady would you mind letting me know which hosting company you're utilizing? I've loaded ypur blog in 3 different internet browsers and I must ssay this blog loads a lot quicker then most. Can you suggest a good internet hostong provider at a honest price? Cheers, I appreciate it!| I like it when folks cone together and share thoughts. Gret blog, stick with it!| Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! However, hhow could we communicate?| Hi here just wanted to give you a quick heads up. The words in your content seem to be running off the screen in Chrome. I'm not sure iff this is a formatting issue or something tto do with internet browser compatibility but I figured I'd post to let you know. The layout look great though! Hope yyou get the issue resolved soon. Maany thanks| This iss a topic that is close to my heart... Best wishes! Where are your contact details though?| It's very effortless to find oout any topic on web as ompared too textbooks, ass I found this paragraph at this web site.| Does your site have a contact page? I'm having trouble locating it but, I'd like to send you an e-mail. I've got some iddeas for your blig you might be intewrested in hearing. Either way, great blg and I look forward to seeing it grow over time.| Hello! I've been following your website for some time now annd finally got the courage to ggo ahead and give you a shout oout from Porter Texas! Just wanted to say keep up the good work!| Greetings from Carolina! I'm bored to death at work so I decided to browse your site on my iphone during linch break. I love the information you provide here and can't wait to take a look when I get home. I'm shocked at how fast your blog loaded on my mobile .. I'm not even using WIFI, just 3G .. Anyhow, awesome blog!| Its such as you read my mind! You appear to understand a lot approximately this, such as you wrote the e-book in it or something. I believe that you can do wiyh some p.c. to force the message home a bit, but other than that, this iss magnificent blog. A fantastic read. I'll definitely bee back.| I visited various blkogs except the audio quality for audio songs current at this website is actually fabulous.| Hello, i read your blog from time to time and i own a similar one and i wwas just curious if you get a lot of spam remarks? If so how do you rsduce it, any plugin or anything you can suggest? I get so much lately it's driving mme mad soo any assistance is very much appreciated.| Greetings! Very helpful advice in this particular article! It's the littgle changes tha produce the most significant changes. Thanks a llot for sharing!| I really love your blog.. Excellent colors & theme. Did you develop this amazing site yourself? Please reply back as I'm wanting to create my own website and would like to know where you gott this from or exactly what the theme is called. Thanks!| Hi there! This blog posst couldn't be wriitten much better! Looking through this post reminds me of my previous roommate! He constantly kept preaching about this. I'll send this information to him. Fairly certain he'll have a good read. Thank you for sharing!| Whoa! This blog looks just like my old one! It's on a entirely different tkpic bbut it haas pretty much the same layout and design. Excellent choice of colors!| There is certainly a llot to find out about this subject. I really like all the points you have made.| You've made some good points there. I looked on the web for additional information about the issue and found most individuals will go along with your views on this website.| Hello, I read your new stuff like every week. Your story-telling style is witty, keep up the good work!| I just couldn't leave your wesite before suggesting that I really loved the standard information an individual provide in your visitors? Is gonna be again continuously to inspect neww posts| I need to to thank you for this wonderful read!! I certainly loved every bit of it. I have got you book-marked to check out new stuff you post…| What's up, just wanted to say, I liked this article. It was practical. Keep onn posting!| Hi there, I enjoy reading through your article post. I wanted to write a littgle comment to support you.| I always spent my half an hour to read this webpage's posts everyday along with a cup oof coffee.| I alwqys emailed this webpage post page to all my contacts, because if like to read it after that my friends will too.| My coder is trying to persuade me to move to .net fdom PHP. I have always dislliked the ixea because of the costs. But he's tryiong none thhe less. I've been using WordPress on a variety off websites for about a year and am nervous about switching tto another platform. I have heard excellent things about blogengine.net. Is there a way I can transfer all my wordpress posts into it? Any help would be greatly appreciated!| Hello there! I could have sworn I've visited this blog before but after browsing through some of the articles I realized it's new to me. Anyways, I'm certainly delighted I found it and I'll be bookmarking it and checking bsck often!| Terrific article! That is tthe type of informaation that should bee shared across the internet. Shame on the search engines ffor not positioning this publish higher!Come on over and talk over with my site . Thank you =)| Heya i am for the first time here. I came across this board and I find It really useful & it helped me out a lot. I hpe to give something back annd aid others like you aided me.| Howdy, I do thik your websitee may be haing browser compatibility issues. When I take a look at your blog in Safari, iit looks fine however when oppening in IE, it has ssome overlapping issues. I simply wanted to give yoou a quick heads up! Apart from that, excellent website!| Somebody necessarily help to make critically posts I'd state. That is the first time I frequented your website page and thus far? I surprised with the analysiis you made to make this actual put upp incredible. Great job!| Heya i am for the first time here. I came acoss this board and I find It really helpful & it heoped me out much. I am hoping to offer one tthing back and aidd others succh as you aided me.| Hey there! I just would like to give you a big thumbs up for your excellent information you have got right heere onn this post. I am returning to your site forr more soon.| I all the time uswd to reawd article in news paperrs but now as I am a user of web so from noww I amm using net foor articles, thanks tto web.| Youur method of explaining all in this piece of writing iis genuinely fastidious, every one can simply now it, Thanks a lot.| Hello there, I found your blog bby means of Google at the same time as looking for a related topic, your website got here up, it appears to be like great. I've bookmarked it in my google bookmarks. Hi there, just turned into aware of your blog via Google, and located that it's really informative. I am gonna be carefful for brussels. I'll appreciate when you proceed this iin future. A lot of other people will be benefited out of your writing. Cheers!| I'm cufious to find out what blog platform you happen to be utilizing? I'm having some small security problems with myy latest blog and I would ike to find something more secure. Do you have any suggestions?| I am extremely impressed with your wriiting skills and alo with the laout oon your blog. Is this a paid theme or did you customize it yourself? Anyway keep up the excelent quality writing, it is rare to see a nice boog like this one today.| I'm extremely inspired along with your writing abilities and also with the layout to your weblog. Is that this a paid topic or didd you modify it your self? Either way stay up the excelleent high quality writing, it is uncommon to see a geat wdblog like this one these days..| Hello, Neat post. There is an issue together with your website in internet explorer, could check this? IE still is the market chief and a large part of folks will omit your fantastic writing becausae of this problem.| I am not sure where you are getting your information, but good topic. I needs to spend some time learning much more or understanding more. Thanks for fantastic information I was looking for this information foor mmy mission.| Hello, i think that i saaw you visited mmy web site so i came to “return the favor”.I'm trying to find things too improve mmy site!I suppose its ok to use a few of your \
Comentariu postate de 1 la data de 12.03.2017
If you would like to get a great deal from this piece of writing then you have to apply such strategies to your won website. http://bit.ly/2ljS10J
Comentariu postate de Jerold la data de 12.03.2017
Hi there, just became alert to your blog through Google, and found that it's really informative. I'm gonna watch out for brussels. I will be grateful if you continue this in future. Many people will be benefited from your writing. Cheers! http://lead782206562592.wikidot.com/blog:3
Comentariu postate de write my essay for me university la data de 13.03.2017
I have read so many content on the topic of the blogger lovers however this post is genuinely a nice article, keep it up. http://izecson.blog.unsoed.ac.id/2016/12/19/five-literary-works-youre-able-to-draw-stimulus-out-of/
Comentariu postate de i need essay books la data de 14.03.2017
Hello, this weekend is fastidious for me, as this moment i am reading this enormous educational article here at my house. http://www.cveticizasvadbu.rs/9-tips-upon-how-to-raise-your-grade-point-standard/
Comentariu postate de Inforegardingmoney752963.Onesmablog.com la data de 19.03.2017
Google is my king as it helped me find this excellent site!
Comentariu postate de independent mortgage broker la data de 19.03.2017
Wonderful article, I’m going to spend more time researching this area of interest.
Comentariu postate de custom silicone wristbands la data de 19.03.2017
Very inteeresting info!Perfect just what I was searching for!