#FormRequest
Explore tagged Tumblr posts
Link
Boolean field validation in Laravel
0 notes
Text
The UpdateBusiness Request
Having done the StoreBusiness request, I needed to do the same for the update() method. This time I expected things to go faster, since the most of the puzzles were solved with the first one. Of course, things weren’t that easy.
I started with “php artisan make:request UpdateBusiness” to make the file. In the Businesses Controller, I added “use App\Http\Requests\UpdateBusiness;” to the top and changed the definition of update() to use UpdateBusiness.
public function update(UpdateBusiness $request, Business $business) {
And that is my first clue this is going to be different. I was using route model binding to get the slug mapped into a Business object, but $business is not injected into the form request when the controller receives it. Fortunately, there’s a way to get at it from the request, which I used in the authorize method. The rule here is different than StoreBusiness, as only the owner may update.
public function authorize() { $business = $this->route('business'); return ($business->owner == $this->user()); }
This works, and the custom flash message is easily set.
public function forbiddenResponse() { flash('Only the business owner may edit the business profile information.', 'flash-alert'); return back(); }
The next two methods are identical to their versions in StoreBusiness. The all() method adds the slug to the request, and messages() adds a custom message for the unique check.
public function all() { $attributes = parent::all(); $attributes['slug'] = str_slug($attributes['name']); return $attributes; } public function messages() { return [ 'unique' => "That name is already taken.", ]; }
That leaves the rules() method. Since this requires the business, it needs to be fetched from the route model binding, the same way as the authorize() method above. Also, since this uses Rule, “use Illuminate\Validation\Rule;” needs to be included in the file.
public function rules() { $business = $this->route('business'); // The slug needs to be unique as well. return [ 'name' => [ 'required', Rule::unique('businesses')->ignore($business->id), ], 'slug' => [ 'required', Rule::unique('businesses')->ignore($business->id), ], 'zip_code' => 'required|regex:/\b\d{5}\b/', ]; }
In the controller the authorization and validation rules are removed from the update() method, simplifying it.
public function update(UpdateBusiness $request, Business $business) { $business->name = $request->name; $business->slug = $request->slug; $business->zip_code = $request->zip_code; $business->owner_id = $request->user()->id; $business->active = true; $business->update(); flash('Business profile updated.'); return redirect("/businesses/" . $request->slug); }
Finally now that “use Illuminate\Validation\Rule;” is no longer needed in the controller, it was removed. I ran some tests and verified everything was working as expected.
2 notes
·
View notes
Text
Nuevo método safe validation en Laravel
¿Qué pasa si quieres recuperar sólo una parte de los datos validados? ¿Cómo lo harías? para este tipo de casos se agrego al Form Request el método safe() que nos permite obtener una parte de los elementos validados.
Cuando validamos datos mediante el uso de un Form request o por medio del Request es posible recuperar los datos validados de forma muy sencilla. veamos como ejemplo el siguiente Form Request <?php namespace App\Http\Requests; class PostRequest extends FormRequest { /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return…
View On WordPress
1 note
·
View note
Text
Google reCaptcha Enterprise Package for Laravel
The Google reCaptcha Enterprise for Laravel is a package that provides easy configuration of reCaptcha and a handy validation rule to verify your user token scores.
Here’s an example of how you can use this package to validate the user’s Recaptcha score using the provided validation Rule class:
use Illuminate\Foundation\Http\FormRequest;use Oneduo\RecaptchaEnterprise\Rules\Recaptcha; class TestRequest extends FormRequest{ public function rules(): array { return [ 'g-recaptcha-response' => [ 'required', new Recaptcha() ], ]; } public function authorize(): bool { return true; }}
When validating a reCaptcha token, you need to configure a score threshold acceptable for considering the user as valid. You can customize your app’s score based on reCaptcha data using the provided configuration option in this package:
// config/recaptcha-enterprise.phpreturn [ 'score_threshold' => 0.7, // ...];
You can get started with this package on GitHub at oneduo/laravel-recaptcha-enterprise and install it via composer:
composer require oneduo/laravel-recaptcha-enterprise
#google#captcha#laravel#development#developer#coding#webdev#programmer#engineering#web developing company
1 note
·
View note
Text
Modern Web Scraping with Python using Scrapy and Splash

Description
Net Scraping now days has develop into one of many hottest matters, there are many paid instruments on the market out there that do not present you something how issues are performed as you'll be all the time restricted to their functionalities as a shopper. On this course you will not be a shopper anymore, i am going to educate you how one can construct your individual scraping device ( spider ) utilizing Scrapy. You'll be taught: The basics of Net Scraping How one can construct a whole spider The basics of XPath How one can find content material/nodes from the DOM utilizing XPath How one can retailer the information in JSON, CSV... and even to an exterior database(MongoDb) How one can write your individual customized Pipeline Fundamentals of Splash How one can scrape Javascript web sites utilizing Scrapy Splash The Crawling habits How one can construct a CrawlSpider How one can keep away from getting banned whereas scraping web sites How one can construct a customized Middleware Net Scraping finest practices How one can scrape APIs How one can use Request Cookies How one can scrape infinite scroll web sites Host spiders in Heroku without spending a dime Run spiders periodically with a customized script Forestall storing duplicated knowledge Deploy Splash to Heroku Write knowledge to Excel records data Login to web sites utilizing FormRequest Obtain Records data & Photos utilizing Scrapy Use Proxies with Scrapy Spider Use Crawlera with Scrapy & Splash Use Proxies with CrawlSpider What makes this course totally different from the others, and why you need to enroll ? First, that is essentially the most up to date course. You may be utilizing Python 3.6, Scrapy 1.5 and Splash 2.0 You'll have an in-depth step-by-step information on tips on how to develop into knowledgeable net scraper. I am going to present you ways different programs scrape Javascript web sites utilizing Selenium and why should not do it of their means. You'll discover ways to use Splash to scrape Javascript web sites and i can guarantee you will not discover any tutorials on the market that teaches tips on how to actually use Splash like i will be doing on this course. You'll discover ways to host spiders in Heroku in addition to Splash(Unique). You'll discover ways to create a customized script so spiders can run periodically with none intervention from you. Read the full article
0 notes
Text
Boolean field validation in Laravel
#laravel developers#technology#programming#developers & startups#laravel framework development company
0 notes
Text
Trimming Input Data
Certain input fields should have the spaces removed from the beginning and end of the string in order to better satisfy uniqueness constraints.
Say someone has a business named “Andy’s Art” and another person wants to register a business with the same name. This gets rejected due to the uniqueness constraint. But then the person decides to “get clever” and adds a space to the end. Now “Art’s Art” and “Art’s Art ” are technically different strings. So, PHP’s trim() function to the rescue.
But where to put it? Obviously the data needs to be trimmed before the rules validation occurs, but it can happen before or after authorization, as the text input fields aren’t used there. One approach is to create a TrimInput middleware and then deal with routing all the relevant requests through that. That seems a bit overkill for now, so I decided to go with a simpler method of just altering the data in the all() method.
I had previous altered all() on a couple of the business form requests to add the slug. So I opted to trim data there, starting with StoreBusiness.
public function all() { $attributes = parent::all(); $attributes['name'] = trim($attributes['name']); $attributes['slug'] = str_slug($attributes['name']); return $attributes; }
I ran some tests to confirm it worked. Overall though I am feeling like all() is getting to be too busy, but it’s a start. It can always be refactored out later.
The same change was done for UpdateBusiness. I also added a link to the businesses show view to get to the edit page.
@if ($isOwner) <p><a href="businesses/{{$business->slug}}/edit">Click here</a> to edit this business's profile data.</p> @endif
For lessons, I didn’t have slugs, so never made the all() method in StoreBusiness and UpdateBusiness. For these I created a new all() method.
public function all() { $attributes = parent::all(); $attributes['name'] = trim($attributes['name']); return $attributes; }
And that took care of my trim needs for now.
0 notes
Text
신학철의 역사화 연구 :1980년대 한국근·현대사 연작을 중심으로
New Post has been published on http://iofferwith.xyz/%ec%8b%a0%ed%95%99%ec%b2%a0%ec%9d%98-%ec%97%ad%ec%82%ac%ed%99%94-%ec%97%b0%ea%b5%ac-1980%eb%85%84%eb%8c%80-%ed%95%9c%ea%b5%ad%ea%b7%bc%c2%b7%ed%98%84%eb%8c%80%ec%82%ac-%ec%97%b0%ec%9e%91%ec%9d%84/
신학철의 역사화 연구 :1980년대 한국근·현대사 연작을 중심으로
신학철의 역사화 연구 :1980년대 한국근·현대사 연작을 중심으로
A study on Shin Hak-chul’s history paintings: focused on the series of Korean modern · contemporary history during 1980s
저자명
한재섭
문서유형
학위논문(석사)
학위수여기관
명지대학교
학위수여년도
2010
전공
미술사학
청구기호
709 -10-26 (국회도서관)
발행국가
한국
발행언어
한국어
서지링크
국회도서관 , 한국교육학술정보원
자료제공 |
원문파일 다운로드
<script type=”text/javascript”>var libraryLayer=new nhn.LayerControl();var loginToggle=new nhn.ToggleLayerControl(sToggleClassName:’login_toggle’);var libraryToggle=new nhn.ToggleLayerControl(sToggleClassName:’library_toggle’);function downloadInfo(src,docId,url)var formRequest=getXMLHTTPRequest();var response=callAjaxAndReturn(formRequest,”POST”,”buyInfo.nhn”,”docId=”+docId).trim();if(response!=”5″)layerControl.show(‘purchaseLayer’,src,18,0);returnlocation.href=url</script>
원문을 제공하는 도서관/공공기관 사이트에 직접 로그인해야 원문을 볼 수 있는 자료입니다.
레이어닫기
소속된 학교도서관 정보를 설정하여, 해당 학교와 제휴된 유료학술DB를 사용할 수 있습니다.
레이어닫기
무료다운로드
PDF 한국교육학술정보원 – 로그인 도움말
초록
목차
키워드
초록
이 논문은 1980년대 민중미술의 한 성과로 꼽히는 신학철의 <한국근대사> <한국현대사> 연작에 대한 연구이다. 한국근·현대사 연작은 1980년대 민중미술에서 발표된 역사화들 중 가장 대표적인 작품으로 평가받고 있다. 한국근·현대사 연작은 역사적 사건의 단순한 재현에서 벗어나 모더니즘적인 형식에 기반한 그만의 조형미를 창출한 것으로 평가된다. 1990년대 이후에도 계속된 신학철의 역사화는 민중미술이 제기한 사회적 발언으로써 미술의 역할에 대해 지속적인 질문을 해왔다. 따라서 그것은 미술이 한 시대의 징후와 특질들을 반영하고 있는 시각문화로써의 속성을 드러내는 작업이기도 하였다. 민중미술은 미술의 사회적 소통과 소외된 사람들의 현실을 형상화하는데 중점을 둔 리얼리즘 미술운동이었다. 신학철은 1980년 <한국근대사 1>부터 시작된 한국근현대사 관련 역사화 연작을 통해 민중미술 운동에 합류하였다. 그러나 신학철은 대학 시절부터 철저하게 미술의 순수성을 강조하는 모더니즘 계열의 작가였다. 1970년대 ‘한국아방가르드협회(AG)’에서 오브제작업으로 본격적인 작가활동을 시작한 그는 ‘AG’이전에는 팝 아트와 초현실주의적인 작업들을 하였다. 그러나 신학철은 모더니즘 미술의 자기모순에 대한 부정을 통해 세계와 미술에 대한 인식을 전환하였다. 이는 작가 자신의 미술과 현실에 대한 회의와 성찰이 1970년대 말 암울한 정치상황과 새로이 도래한 소비사회에 대한 반발감이 맞물리면서 작품으로 표면화된 것이었다. 이러한 변화과정에서 <한국근대사> 연작이 민중미술에서 역사화의 물꼬를 텄다. <한국근대사>연작은 한국사회의 문제점을 일본의 식민지부터 연유하는 분단체제로 보았다. 그리고 그러한 분단체제의 모순에 영위하는 정치권력이 만들어내는 현실의 사회문화적인 문제점을 비판하였다. 그것은 이제까지 국가와 제도권에 의해 침묵당해왔던 민중들의 관점에서 한국근대사를 형상화 해 낸 것이었다. <한국현대사>연작은 한국현대사의 분수령이었던 1987년 6월 항쟁이 가져다 준 낙관과 좌절을 그리고 있다. 6월항쟁은 구체제의 모순들이 해결되지 않은 상태에서 이루어진 형식적인 민주화에 그치고 말았다. 신학철은 6월 항쟁의 좌절을 가져온 반역사적인 지배계층과 중산층들의 이기적인 속물근성을 폭로하였다. <한국현대사-초혼곡> 연작은 1990년대 중반이후 진행되는 역사청산작업의 허구성에 대한 고발이었다. 또, 진전된 민주화의 공간속에서 정치적 수사와 사회적 통합을 위해 과거의 대상으로 전락하는 민중들을 신학철 특유의 조형언어로 기억하려는 반기념비적 성격을 지닌다. 신학철 역사화의 중간 결산이라 할 수 있는 <갑순이와 갑돌이-한국현대사(2002)>는 민중이나 대중이 아닌 개인(들)의 기억의 모음을 통해 한국근현대사를 재구성하는 작품이었다. 그것은 역사변화가 국가나 민중과 같은 집단이 가진 과거의 사실들의 기록이 아니라는 것이다. 오히려 역사는 개인(들)의 기억들과 욕망들이 끊임없이 생성과 소멸의 과정을 거쳐 역사를 구성하고 있다는 것이었다. 지배층과 피지배층으로 나누어진 수직적 사회구조의 변화가 아닌 모두가 하나의 소수자이고 한 명의 타자들이 그물망처럼 얽혀서 역사를 이루어왔다는 것이��. 나아가 작품의 수직구도에서 수평구도로의 변화는 1990년대 이후 변화된 작가의 역사의식과 한국사회를 반영한다. 신학철의 한국근·현대사 연작은 형식적으로도 역사적 사건의 사실적 재현에 집중하지 않고 모더니즘적인 전략을 취하였다. 소비사회의 광고 이미지와 역사적 사건을 기록한 사진들의 조합과 의도된 충돌로 이루어진 몽타주는 역동적으로 변화하는 한국사회의 총체성을 획득할 수 있는 형식이었다. 그리고 몽타주로 탄생된 초현실적인 근육-기계 덩어리는 한국근현대사의 압축적 근대화과정에서 억압되었던 상처와 괴물성을 환유해내고 있다. 신학철의 한국근·현대사 연작은 작품과 현실의 긴장관계 속에서 창출된 화면구성방식이자 사회가 지속되는 한 계속될 현실에 대한 작가의 시각적 성찰을 보여주는 형상화이다.
This dissertation is about Shin Hak-chul’s <the series of Korean modern · contemporary history>, which was a great result of 1980s Minjoong Art. The series of Korean modern · contemporary history works are considered as the most typical art of the published history paintings from 1980s Minjoong Art. The works were also known for it created a beauty of structure based on modernism, which was not just a reconstruction of a historical event. Shin Hak-chul’s history paintings continued even after the 1990s and continuously questioned about the role of Art as social statement. Therefore, it was a work which shows the attribute of visual culture reflecting the symptoms and features of that era. Minjoong Art was the social communication with art and a Realism Art Movement based on visualizing neglected people’s real life. Shin Hak-chul joined the Minjoong Art movement by his the series of Korean modern · contemporary history starting from 1980s <Korean modern history 1>. However Shin Hak-chul was an artist of affiliation with Modernism which was emphasizing purity of art starting ever since his college year. He started as an artist at ‘Korean Avant-garde Association(AG)’ with objets in 1970s. Before joining ‘AG’, he worked on Pop Art and Surrealism. On the other hand, Shin Hak-chul changed his point of view of the world and art by denying Modernism Art’s self-contradiction. It was put together to his piece by his doubts and introspections of the art and reality of the 1970s dark political situation and the resistance of the new consumer society. The <Korean modern history> work was born in these changes and opened the gate to history painting in Minjoong Art. The <Korean modern history> work saw Korea’s problem was from Japanese colony’s dividing system. And criticized the problem of politic powers living on the contradiction of the system. This was visualizing the Korean modern history from the public’s point of view, which was put to silence until then by the nation. The <Korean Contemporary history> work shows the optimistic view and the failure that came along with the 1987, ‘June Resistance’, which was the turning point of the Korean modern history. The ‘June Resistance’ ended as a perfunctorily democratization, leaving the old system’s problem unsolved. Shin Hak-chul exposed the selfish snobbery of the ahistorical hierarchies and the middle class, who brought failure to the ‘June Resistance’. The <Korean Contemporary history-Invocation of the Spirit of a Deceased> work was a report on the fabrication of the history settling operation after the middle 1990s. And it has the character of a monument memorial for a bad accident by remembering in Shin Hak-chul’s formative language of the people who were falling back in to the past for the political investigation and the social unification from the advanced democracy’s space. Shin Hak-chul history painting’s middle evaluation, <Gapsoonyee and Gapdolyee-Korean Contemporary history(2002)>, was a piece that restructured the Korean modern history by gathering the individual’s memory instead of the public. It meant that change of history was not a record of facts from the past of the nation or the people. It was rather the creation and destruction of the individual’s memory and desire that created the history. It was not a perpendicular social structure where it was divided in to ruling caste and subjugated class that created history, it was when everyone were a minority and were tied up together. Furthermore, the change from vertical to horizontal composition in works reflected the change in artist’s historical awareness and Korea society after the 1990s. Shin Hak-chul’s the series of Korean modern · contemporary history did not intend to formally reconstruct the historical accidents and chose to go with modernism. The combination and intended collision between the advertising image of consumer society and the pictures recording historical accidents created a montage, which catched the dynamic change of the whole Korean society. And the surreal muscle-mechanic mass, born by montage, showed the suppressed wounds and the monster like created by the Korean modern history’s compressed modernization. Shin Hak-chul’s the series of Korean modern · contemporary history were a layout of creation between the piece and the tension of reality, and a visualization of the artist’s introspect of the reality which will go on as long as the society exists.
목차
Ⅰ. 머리말 1 Ⅱ. 1980년대 민중미술과 신학철 4 1. 민중미술운동과 역사화 4 2. 신학철의 회화 세계 18 Ⅲ. 신학철 역사화 작품분석 26 1. 1987년 이전 : <한국근대사> 연작 26 1) 분단체제의 기원 26 2) 분단체제의 심화 34 2. 1987년 이후 : <한국현대사> 연작 42 1) 6월 항쟁의 낙관과 좌절 42 2) 역사청산에 맞서는 반(反)기념비 48 3. 2002년작 : <갑순이와 갑돌이-한국현대사> 54 Ⅳ. 신학철 역사화의 형식적 특징 64 1. 몽타주 65 2. 화면구성 :근육-기계 덩어리 74 Ⅴ. 맺음말 80 참고문헌 83 참고도판 90 Abstract 110
<script type=”text/javascript”>function keywordSearch(keyword)window.open(“/search.nhn?&field=0&dir_id=1&query=”+encodeURIComponent(keyword))</script>
키워드
민중미술, 신학철, 역사화, 한국근대사, 한국현대사, 분단, 몽타주
0 notes
Text
The DestroyLesson Form Request
This is used when owner decides to delete a lesson. Clearly, it must come from the owner!
Starting with “php artisan make:request DestroyLesson” and adding the appropriate use and type-hint to the LessonsController, this request starts out simpler than the others. The regular “use Illuminate\Http\Request;” was removed as it was no longer needed.
public function destroy(DestroyLesson $request, Lesson $lesson) { $lesson->delete(); flash('Lesson deleted.', 'flash-alert'); return redirect("/businesses/" . $lesson->business->slug); }
In the form request, I copied the authorization code from UpdateLesson, changing “edit” to “delete” in the message.
public function authorize() { return ($this->lesson->business->owner == $this->user()); } public function forbiddenResponse() { flash('Only the business owner may delete the business\'s lessons.', 'flash-alert'); return back(); }
That was it. There are no inputs to validate, as the user simply clicks the delete button to remove the lesson. Later, when lessons are tied to appointments (this is a scheduling app after all), I’ll need to make sure there are no pending appointments before allowing deletion.
This does raise questions. Should this be a soft delete? There may be a lot of historical data tied to the lessons in the future, it would be a shame to lose that if a user accidentally presses the wrong button. Yes, having an “undelete” feature could be desirable in the event of such mistakes. Of course this means yet another screen, to show the deleted lessons, as they shouldn’t normally appear. Perhaps a flag to the index()? Actually there is no index(), as the list of lessons is shown on the BusinessesController show() method. Should that method call an index() on LessonsController? That might separate concerns a little more.
0 notes
Text
The UpdateLesson Form Request
Just keep going. Here I’m updating the lesson based on the data posted from the Edit Lesson form.
So I kicked this off with “php artisan make:request UpdateLesson”, adding UpdateLesson to the top of the LessonsController and to the type-hint for update(). I was able to copy the authorization stuff from the EditLesson form request.
public function authorize() { return ($this->lesson->business->owner == $this->user()); } public function forbiddenResponse() { flash('Only the business owner may edit the business\'s lessons.', 'flash-alert'); return back(); }
Duplication of code again! I swear, I’ll address this with some middleware or something at some point.
EditLesson didn’t have validation rules, so I moved that over from the LessonsController update() function. This meant adding “use Illuminate\Validation\Rule;” to the top. The code had to be refactored a bit, but it was basically the validation rule from StoreLesson, with an ->ignore() tacked on so it would ignore the current record when testing uniqueness. Also, as my edit form did not have the business_id as a hidden field, I had to look that up from $this->lesson->business_id instead. Unlike the create lesson form, the update business form already has a lesson object to work with, so there was no need to set the business_id as a hidden field.
public function rules() { return [ 'name' => [ 'required', Rule::unique('lessons')->where(function ($query) { $query->where('business_id', $this->lesson->business_id); })->ignore($this->lesson->id), ], 'capacity' => 'required|numeric|min:1', ]; }
Back in the LessonsController, the validation was removed, and bit to “use Rule” at the top was removed as well, as those duties were now in the form requests. Again, the Rule was needed here, as the validation rule was too complex to use the simpler method I used for the business form requests.
0 notes
Text
Making the EditLesson Form Request
Continuing the refactor to FormRequest, this one handles the generation of the lesson edit view.
Starting with “php artisan make:request EditLesson” which creates the Form Request class, and comparing it to the EditBusiness, which acts in a similar fashion. LessonsController will need “use App\Http\Requests\EditLesson;” and the “EditLesson $request” type-hint added to the argument list for edit().
Since I’m operating on a lesson here, to find the business owner I have to find the lesson’s business first. Because of the belongsTo relationship this is easily done by referring to “$lesson->business->owner”.
public function authorize() { return ($this->lesson->business->owner == $this->user()); } public function forbiddenResponse() { flash('Only the business owner may edit the business\'s lessons.', 'flash-alert'); return back(); }
Now if the user is not the business owner, they should not be able to view the form, and this works. But really, they shouldn’t even see the edit icons on the business show page. This can be fixed by passing an $isOwner flag into the view for the BusinessesController show() method. This requires putting “use Illuminate\Http\Request;” back at the top, as I don’t think it is worth doing a full FormRequest for show(), at least, not at this time.
The $isOwner flag is checked in the usual way and passed into the view.
public function show(Business $business, Request $request) { $isOwner = ($business->owner == $request->user()); return view('businesses.show', compact(['business', 'isOwner'])); }
Then within the view, I used @if ($isOwner) / @endif blocks around the edit icon and the add lesson form.
0 notes
Text
Making the StoreLesson Form Request
Now that the BusinessesController has been refactored to use Form Requests, it is time to turn attention to the LessonsController.
With the experience of the BusinessesController and its Form Requests, I hoped that doing the same for LessonsController would be relatively straightforward. I started with “php artisan make:request StoreLesson” and looked to compare it to StoreBusiness. Oh, and the method signature for store() needs to use the StoreLesson type-hint.
To create a new Lesson, the user must be the business owner. Thus I was able to copy the authorize() and forbiddenResponse() from UpdateBusiness. Of course, now I have a duplication of code issue, which will need to be addressed before long. The authorize method did need changes though, as the lesson has not been created yet, so it doesn’t know the business object. Thus I had to find that using the hidden value.
At this time I decided to change the business show view so that the “businessId” hidden value to “business_id” instead. While the standards say to use camelCase for most things, I find having model attributes matching database attributes to be more convenient and it just feels better. Maybe someday I’ll have to go back on this but for now I’m making the change.
So now my logic becomes finding the business by looking up the business_id, and then from that finding the owner, and comparing it to the user. Unfortunately if both sides of the equation are null, that matches, and it would resolve true, which is no acceptable. So I have to check for the null first. Anyway, the authorize does appear a little more complicated than in the Business form requests. This required “use App\Business;” at the top.
Next the rules() method transfers out of the LessonsController. Because of the complexity of the uniqueness constraint, I had to use Rule() here, and that required a “use Illuminate\Validation\Rule;” at the top of StoreLesson. A lesson’s name has to be unique for a given business, but it’s okay for two businesses to have a lesson of the same name. Oh, and the method signature for store() needs to use the StoreLesson type-hint.
The all() message does not need to be overridden here, because I’m not adding a computed field to the lesson. (When I was working with the BusinessesController I was adding a computed slug.) Likewise the messages() does not need to be overridden either, as that was also a slug issue.
<?php namespace App\Http\Requests; use App\Business; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; class StoreLesson extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { $business = Business::find($this->business_id); return (!empty($business) and ($business->owner == $this->user())); } /** * Set the flash and redirect if unauthorized. * * @return \Illuminate\Http\RedirectResponse */ public function forbiddenResponse() { flash('Only the business owner may edit the business profile information.', 'flash-alert'); return back(); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => [ 'required', Rule::unique('lessons')->where(function ($query) { $query->where('business_id', $this->business_id); }), ], 'capacity' => 'required|numeric|min:1', ]; } }
So now the store() method in LessonsController is simplified. I had to make the change from businessId to business_id here as well.
public function store(StoreLesson $request) { $lesson = new Lesson; $lesson->name = $request->name; $lesson->capacity = $request->capacity; $business = Business::findOrFail($request->business_id); $business->lessons()->save($lesson); flash('Lesson added.'); return back(); }
Initially I forgot to change that latest business_id and the application gave me a 404 error, which took a bit to track down. The Business:findOrFail() was the problem, of course, but it was redirecting to a URL of /lessons, based on the method, instead of going back. I determined I didn’t need like this functionality, and changed it to a simple Business:find() instead. After all, if it fails to find, it will fail much earlier, at authorization.
0 notes
Text
The EditBusiness Form Request
There’s one more request used in BusinessController, so I made a form request class for edit() as well.
I started with “php artisan make:request EditBusiness” to make the class. Then I added “use App\Http\Requests\EditBusiness;” to the BusinessesController. In the edit() method, I replaced the Request type-hint with EditBusiness. The validation that was in the edit() method was moved to the EditBusiness form request class. This simplifies edit().
public function edit(EditBusiness $request, Business $business) { return view('businesses.edit', compact('business')); }
This is a bit weird in that it looks like, at first glance, that the $request is not used here and thus could be removed. That would remove the authorization checks though, so it must remain. I am not a fan of this approach and will probably refactor later when I play with policies and authorization middleware.
In the EditBusiness class, the authorize() and method are copied from UpdateBusiness.
public function authorize() { return ($this->business->owner == $this->user()); } public function forbiddenResponse() { flash('Only the business owner may edit the business profile information.', 'flash-alert'); return back(); }
The rules() method is left unchanged, it just returns an empty array. This is because there’s no input data when processing a request to show the edit form. The all() and messages() methods found in UpdateBusiness are not needed in EditBusiness.
Finally the “use Illuminate\Http\Request;” was removed from the BusinessesController as it was no longer used there.
0 notes