├── 9781484249901.jpg
├── Contributing.md
├── LICENSE.txt
├── README.md
├── chapter-eight
├── chapter-eleven
├── chapter-five
├── chapter-four
├── chapter-nine
├── chapter-one
├── chapter-seven
├── chapter-six
├── chapter-ten
├── chapter-three
├── chapter-twelve
├── chapter-two
└── errata.md
/9781484249901.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Apress/beginning-laravel-2e/f1816bcecc736a36daf7bd095e74a041adf2ba89/9781484249901.jpg
--------------------------------------------------------------------------------
/Contributing.md:
--------------------------------------------------------------------------------
1 | # Contributing to Apress Source Code
2 |
3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers.
4 |
5 | ## How to Contribute
6 |
7 | 1. Make sure you have a GitHub account.
8 | 2. Fork the repository for the relevant book.
9 | 3. Create a new branch on which to make your change, e.g.
10 | `git checkout -b my_code_contribution`
11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted.
12 | 5. Submit a pull request.
13 |
14 | Thank you for your contribution!
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Freeware License, some rights reserved
2 |
3 | Copyright (c) 2019 Sanjib Sinha
4 |
5 | Permission is hereby granted, free of charge, to anyone obtaining a copy
6 | of this software and associated documentation files (the "Software"),
7 | to work with the Software within the limits of freeware distribution and fair use.
8 | This includes the rights to use, copy, and modify the Software for personal use.
9 | Users are also allowed and encouraged to submit corrections and modifications
10 | to the Software for the benefit of other users.
11 |
12 | It is not allowed to reuse, modify, or redistribute the Software for
13 | commercial use in any way, or for a user’s educational materials such as books
14 | or blog articles without prior permission from the copyright holder.
15 |
16 | The above copyright notice and this permission notice need to be included
17 | in all copies or substantial portions of the software.
18 |
19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 | SOFTWARE.
26 |
27 |
28 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Apress Source Code
2 |
3 | This repository accompanies [*Beginning Laravel, 2nd Edition*](https://www.apress.com/9781484249901) by Sanjib Sinha (Apress, 2019).
4 |
5 | [comment]: #cover
6 | 
7 |
8 | Download the files as a zip using the green button, or clone the repository to your machine using Git.
9 |
10 | ## Releases
11 |
12 | Release v1.0 corresponds to the code in the published book, without corrections or updates.
13 |
14 | ## Contributions
15 |
16 | See the file Contributing.md for more information on how you can contribute to this repository.
--------------------------------------------------------------------------------
/chapter-eight:
--------------------------------------------------------------------------------
1 | //code 8.1
2 | $ php artisan make:middleware CheckRole
3 | Middleware created successfully.
4 |
5 | //code 8.2
6 | // app/Http/Middleware/CheckRole.php
7 | check() && $request->user()->admin == 0){
32 | return redirect()->guest('home');
33 | }
34 | return $next($request);
35 | }
36 | }
37 |
38 |
39 |
40 | //code 8.4
41 | //‘routes/web.php’
42 | Route::group(['middleware' => ['web', 'auth']], function(){
43 | Route::get('/adminonly', function () {
44 | if(Auth::user()->admin == 0){
45 | return view('restrict');
46 | }else{
47 | $users['users'] = \App\User::all();
48 | return view('adminonly', $users);
49 | }
50 | });
51 | });
52 |
53 |
54 | //code 8.5
55 | // resources/views/adminonly.blade.php
56 | @extends('layouts.app')
57 | @section('content')
58 |
506 | @if (session('status'))
507 |
508 | {{ session('status') }}
509 |
510 | @endif
511 | Hello
{{ $user->name }}
512 | @if(Auth::user()->role_id === 1)
513 |
Dashboard for Admin
514 | You are logged in as an Administrator!
515 |
516 | Now you can view, add, edit or delete
517 | any company, project, and user
518 |
519 |
520 |
521 | Companies
522 |
523 |
529 |
530 |
531 |
532 | Projects
533 |
534 |
540 |
541 |
542 |
543 | Users
544 |
545 |
549 |
550 |
551 | -------------
552 |
553 |
554 | // code 8.17
555 | // app/HTTP/Controllers/CompanyController.php
556 | id)->get();
575 |
576 | if(Auth::user()->role_id == 1){
577 | return view('companies.index', ['companies'=> $companies]);
578 | }
579 | }
580 | return view('auth.login');
581 | }
582 |
583 | /**
584 | * Show the form for creating a new resource.
585 | *
586 | * @return \Illuminate\Http\Response
587 | */
588 | public function create()
589 | {
590 | if( Auth::check() ){
591 | if(Auth::user()->role_id == 1){
592 | return view('companies.create');
593 | }
594 | }
595 | return view('auth.login');
596 |
597 | }
598 |
599 | /**
600 | * Store a newly created resource in storage.
601 | *
602 | * @param \Illuminate\Http\Request $request
603 | * @return \Illuminate\Http\Response
604 | */
605 | public function store(Request $request)
606 | {
607 | if(Auth::check()){
608 | $company = Company::create([
609 | 'name' => $request->input('name'),
610 | 'description' => $request->input('description'),
611 | 'user_id' => Auth::user()->id
612 | ]);
613 | if($company){
614 | return redirect()->route('companies.show', ['company'=> $company->id])
615 | ->with('success' , 'Company created successfully');
616 | }
617 |
618 | }
619 |
620 | return back()->withInput()->with('errors', 'Error creating new company');
621 | }
622 | /**
623 | * Display the specified resource.
624 | *
625 | * @param \App\Company $company
626 | * @return \Illuminate\Http\Response
627 | */
628 | public function show(Company $company)
629 | {
630 | if( Auth::check() ){
631 | if(Auth::user()->role_id == 1){
632 | $company = Company::find($company->id);
633 | return view('companies.show', ['company' => $company]);
634 | }
635 | }
636 | return view('auth.login');
637 | }
638 | /**
639 | * Show the form for editing the specified resource.
640 | *
641 | * @param \App\Company $company
642 | * @return \Illuminate\Http\Response
643 | */
644 | public function edit(Company $company)
645 | {
646 | if( Auth::check() ){
647 | if(Auth::user()->role_id == 1){
648 | $company = Company::find($company->id);
649 | return view('companies.edit', ['company' => $company]);
650 | }
651 | }
652 | }
653 | /**
654 | * Update the specified resource in storage.
655 | *
656 | * @param \Illuminate\Http\Request $request
657 | * @param \App\Company $company
658 | * @return \Illuminate\Http\Response
659 | */
660 | public function update(Request $request, Company $company)
661 | {
662 | $updateCompany = Company::where('id', $company->id)->update(
663 | [
664 | 'name'=> $request->input('name'),
665 | 'description'=> $request->input('description')
666 | ]
667 | );
668 | if($updateCompany){
669 | return redirect()->route('companies.show', ['company'=> $company->id])
670 | ->with('success' , 'Company updated successfully');
671 | }
672 | //redirect
673 | return back()->withInput();
674 | }
675 |
676 | /**
677 | * Remove the specified resource from storage.
678 | *
679 | * @param \App\Company $company
680 | * @return \Illuminate\Http\Response
681 | */
682 | public function destroy(Company $company)
683 | {
684 | }
685 | public function getDestroy($id)
686 | {
687 | $company = Company::findOrFail($id);
688 | if($company->destroy($id)){
689 | return redirect()->route('companies.index')->with('success' , 'Company deleted successfully');
690 | }
691 | }
692 | }
693 |
694 |
695 |
696 |
697 |
698 |
699 | -----------------
700 |
701 |
702 | //code 8.18
703 | //resources/views/companies/create.blade.php
704 | @extends('layouts.app')
705 |
706 | @section('content')
707 |
708 |
709 |
710 |
711 |
712 | All Companies
713 |
714 |
744 |
745 |
746 |
747 | @endsection
748 |
749 |
750 | ---------------------
751 |
752 |
753 | //code 8.19
754 | //app/Providers/AuthServiceProvider.php
755 | /**
756 | * Register any authentication / authorization services.
757 | *
758 | * @return void
759 | */
760 | public function boot()
761 | {
762 | $this->registerPolicies();
763 |
764 | Gate::define('admin-only', function ($user) {
765 | if($user->admin == 1){
766 | return TRUE;
767 | }
768 | return FALSE;
769 |
770 | });
771 | }
772 |
773 |
774 | --------------------
775 |
776 | //code 8.20
777 | //routes/web.php
778 | Route::get('/admin', function () {
779 | if (Gate::allows('admin-only', Auth::user())) {
780 | // The current user can view this page
781 | return view('admin');
782 | }
783 | else{
784 | return view('restrict');
785 | }
786 | });
787 |
788 |
789 |
790 | ---------------------
791 |
792 |
793 | //code 8.21
794 | // resource/views/layouts/app.blade.php
795 |
796 |
833 |
834 |
835 |
836 | --------------------
837 |
838 |
839 | //code 8.22
840 | //App/Policies/admin.php
841 | admin == 1){
865 | return TRUE;
866 | }
867 | return FALSE;
868 | }
869 | }
870 |
871 |
872 |
873 | -------------------------
874 |
875 |
876 | //code 8.23
877 | //App/Policies/mod.php
878 | mod == 1){
901 | return TRUE;
902 | }
903 | return FALSE;
904 | }
905 | }
906 |
907 |
908 | -----------------
909 |
910 | //code 8.24
911 | //app/Policies/ AuthServiceProvider.php
912 | 'App\Policies\ModelPolicy',
931 | 'App\User' => admin::class,
932 | 'App\User' => mod::class
933 | ];
934 |
935 | /**
936 | * Register any authentication / authorization services.
937 | *
938 | * @return void
939 | */
940 | public function boot()
941 | {
942 | $this->registerPolicies();
943 |
944 | Gate::define('admin-only', 'App\Policies\admin@admin_only');
945 |
946 | Gate::define('mod-only', 'App\Policies\mod@mod_only');
947 | }
948 | }
949 |
950 |
951 | ----------------
952 |
953 |
954 |
--------------------------------------------------------------------------------
/chapter-eleven:
--------------------------------------------------------------------------------
1 | //code 11.1
2 | $ php artisan make:controller CreatemessageController –resource
3 |
4 |
5 | //code 11.2
6 | //app/Http/Controllers/ CreatemessageController.php
7 | middleware('auth');
29 | }
30 | /**
31 | * Display a listing of the resource.
32 | *
33 | * @return \Illuminate\Http\Response
34 | */
35 | public function index()
36 | {
37 | if (Auth::check()){
38 | $messages = Message::get();
39 | return view('messages.index', compact('messages'));
40 | }
41 | }
42 |
43 | /**
44 | * Show the form for creating a new resource.
45 | *
46 | * @return \Illuminate\Http\Response
47 | */
48 | public function create()
49 | {
50 | if( Auth::check() ){
51 | return view('messages.create');
52 | }
53 | return view('auth.login');
54 |
55 | }
56 |
57 | /**
58 | * Store a newly created resource in storage.
59 | *
60 | * @param \Illuminate\Http\Request $request
61 | * @return \Illuminate\Http\Response
62 | */
63 | public function store(Request $request)
64 | {
65 | if(Auth::check()){
66 | $name = Auth::user();
67 | $message = Message::create([
68 | 'user_id' => Auth::user()->id,
69 | 'message' => $request->input('message')
70 |
71 | ]);
72 |
73 | if($name){
74 |
75 | //step one: fire the event
76 | event(New AboutTheUser($name));
77 |
78 | }
79 |
80 | }
81 | }
82 |
83 | /**
84 | * Display the specified resource.
85 | *
86 | * @param int $id
87 | * @return \Illuminate\Http\Response
88 | */
89 | public function show(Message $message)
90 | {
91 | if( Auth::check() ){
92 | $message = Message::find($message->id);
93 | return view('messages.show', ['message' => $message]);
94 | }
95 | return view('auth.login');
96 |
97 | }
98 | }
99 |
100 |
101 |
102 |
103 | //code 11.3
104 | $ php artisan make:model Message -m
105 |
106 |
107 |
108 | //code 11.4
109 | //app/Message.php
110 | belongsTo(User::class);
133 | }
134 | }
135 |
136 |
137 |
138 | //code 11.5
139 | //app/User.php
140 | hasMany(Message::class);
177 | }
178 | }
179 |
180 |
181 |
182 | //code 11.6
183 | //resources/views/messages/index.blade.php
184 |
185 |
186 | @foreach ($messages as $message)
187 |
190 |
191 | Edit
192 | @endforeach
193 |
194 |
195 |
196 |
197 |
198 | //code 11.7
199 | //resources/views/messages/show.blade.php
200 |
201 |
204 |
205 | {{ $message->message }} posted by {{ $message->user['name'] }}
206 |
207 |
208 |
209 |
210 |
211 | //code 11.8
212 | //resources/views/messages/create.blade.php
213 |
214 |
215 | All Messages
216 |
217 |
238 |
239 |
240 |
241 |
242 |
243 | //code 11.9
244 | //routes/web.php
245 | Route::get('/', function () {
246 | return view('welcome');
247 | });
248 |
249 | Auth::routes();
250 |
251 | Route::resource('messages', 'CreatemessageController');
252 |
253 | Route::get('/home', 'HomeController@index')→name('home');
254 |
255 |
256 |
257 | //code 11.10
258 | ss@ss-H81M-S1:~/code/laraeventandlisteners$ php artisan make:event AboutTheUser
259 | Event created successfully.
260 |
261 |
262 |
263 | //code 11.11
264 | //app/Events/AboutTheUser.php
265 | name = $name;
294 | }
295 |
296 | /**
297 | * Get the channels the event should broadcast on.
298 | *
299 | * @return \Illuminate\Broadcasting\Channel|array
300 | */
301 | public function broadcastOn()
302 | {
303 | return new PrivateChannel('channel-name');
304 | }
305 | }
306 |
307 |
308 |
309 | //code 11.12
310 | ss@ss-H81M-S1:~/code/laraeventandlisteners$ php artisan make:listener SendMailForNewMessage --event=AboutTheUser
311 | Listener created successfully.
312 | ss@ss-H81M-S1:~/code/laraeventandlisteners$ php artisan make:listener AlertForNewMessage
313 | Listener created successfully.
314 | ss@ss-H81M-S1:~/code/laraeventandlisteners$ php artisan make:listener AboutTheUser
315 | Listener created successfully.
316 |
317 |
318 |
319 | //code 11.13
320 | //app/Providers/EventServiceProvider.php
321 | //original one
322 |
323 | [
341 | SendEmailVerificationNotification::class,
342 | ],
343 | ];
344 |
345 | /**
346 | * Register any events for your application.
347 | *
348 | * @return void
349 | */
350 | public function boot()
351 | {
352 | parent::boot();
353 |
354 | //
355 | }
356 | }
357 |
358 |
359 |
360 | //code 11.14
361 | //app/Providers/EventServiceProvider.php
362 | //changed code where the listen property takes new values
363 |
364 | [
386 | AlertForNewMessage::class,
387 | AboutTheUser::class,
388 | SendMailForNewMessage::class,
389 |
390 | ],
391 | ];
392 |
393 | /**
394 | * Register any events for your application.
395 | *
396 | * @return void
397 | */
398 | public function boot()
399 | {
400 | parent::boot();
401 |
402 | //
403 | }
404 | }
405 |
406 |
407 |
408 | //code 11.15
409 | //app/Listeners/AboutTheUser.php
410 | email)->send(new MailForNewMessage());
490 | }
491 | }
492 |
493 |
494 |
495 | //code 11.18
496 | //.env
497 | MAIL_DRIVER=smtp
498 | MAIL_HOST=smtp.mailtrap.io
499 | MAIL_PORT=2525
500 | MAIL_USERNAME=*****************
501 | MAIL_PASSWORD=*****************
502 | MAIL_ENCRYPTION=tls
503 |
504 |
505 | //code 11.19
506 | ss@ss-H81M-S1:~/code/laraeventandlisteners$ php artisan make:mail MailForNewMessage --markdown emails.new-message
507 | Mail created successfully.
508 |
509 |
510 |
511 | //code 11.20
512 | //app/Mail/ MailForNewMessage.php
513 | markdown('emails.new-message');
534 | }
535 | }
536 |
537 |
538 |
539 | //code 11.21
540 | @component('mail::message')
541 | # New Message
542 |
543 | Hi a new message have been just posted
544 |
545 | @component('mail::button', ['url' => ''])
546 | Button Text
547 | @endcomponent
548 |
549 | Thanks,
550 | {{ config('app.name') }}
551 | @endcomponent
552 |
553 |
554 |
555 | //code 11.22
556 | $ php artisan event:generate
557 |
558 |
559 |
560 |
--------------------------------------------------------------------------------
/chapter-five:
--------------------------------------------------------------------------------
1 | //code 5.1
2 | php artisan make:migration create_tests_table
3 |
4 |
5 | //code 5.2
6 | php artisan make:migration create_tests_table –create=tests
7 | php artisan make:migration add_names_to_tests_table –table=tests
8 |
9 | //code 5.3
10 | php artisan make:model Test
11 |
12 | //code 5.4
13 | php artisan make:model Test --migration
14 | php artisan make:model Test -m
15 |
16 |
17 | //code 5.5
18 | //app/Article.php
19 | belongsTo('App\User');
34 | }
35 |
36 | /**
37 | * Get the tags for the article
38 | */
39 |
40 | public function tags() {
41 | return $this->belongsToMany('App\Tag');
42 | }
43 |
44 | /**
45 | * Get all of the profiles' comments.
46 | */
47 | public function comments(){
48 | return $this->morphMany('App\Comment', 'commentable');
49 | }
50 | }
51 |
52 |
53 | // code 5.7
54 | // resources/views/welcome.blade.php
55 | @extends('layouts.app')
56 | @section('content')
57 |
58 |
59 |
60 |
61 |
62 | @foreach($articles as $article)
63 |
64 |
65 | {{ $article->title }}
66 |
67 |
68 | @endforeach
69 |
70 |
71 |
75 |
76 |
77 |
95 |
96 |
97 | @endsection
98 |
99 |
100 | // code 5.7
101 | // resources/views/welcome.blade.php
102 |
120 |
121 |
122 |
123 | //code 5.8
124 | // routes/web.php
125 | Auth::routes();
126 | Route::get('/home', 'HomeController@index')->name('home');
127 | Route::resources([
128 | 'users' => 'UserController',
129 | 'profiles' => 'ProfileController',
130 | 'articles' => 'ArticleController',
131 | 'comments' => 'CommentController'
132 | ]);
133 | Route::get('/users/{id}/articles', 'ArticleController@articles');
134 | Route::get('/', 'ArticleController@main');
135 |
136 |
137 | // code 5.9
138 | // app/HTTP/Controllers/ArticleController.php
139 | paginate(4);
160 | //$articles = Article::where('active', 1)->orderBy('title', 'desc')->take(10)->get();
161 | $users = User::all();
162 | $tags = Tag::all();
163 | //$posts = Article::orderBy('created_at','desc')->paginate(3);
164 | return view('articles.index', compact('articles', 'users', 'tags'));
165 | }
166 |
167 | public function main()
168 | {
169 | $articles = Article::where('user_id', 1)->orderBy('title', 'desc')->take(4)->get();
170 | $tags = Tag::all();
171 | return view('welcome', ['articles' => $articles, 'tags' => $tags]);
172 | }
173 |
174 | /**
175 | * Show the form for creating a new resource.
176 | *
177 | * @return \Illuminate\Http\Response
178 | */
179 | public function create()
180 | {
181 | //
182 | }
183 |
184 | /**
185 | * Store a newly created resource in storage.
186 | *
187 | * @param \Illuminate\Http\Request $request
188 | * @return \Illuminate\Http\Response
189 | */
190 | public function store(Request $request)
191 | {
192 | //
193 | }
194 |
195 | /**
196 | * Display the specified resource.
197 | *
198 | * @param \App\Article $article
199 | * @return \Illuminate\Http\Response
200 | */
201 | public function show(Article $article)
202 | {
203 | $tags = Article::find($article->id)->tags;
204 | $article = Article::find($article->id);
205 | $comments = $article->comments;
206 | $user = User::find($article->user_id);
207 | $country = Country::where('id', $user->country_id)->get()->first();
208 |
209 | return view('articles.show', compact('tags','article',
210 | 'country', 'comments', 'user'));
211 | }
212 | /**
213 | * Display the specified resource.
214 | *
215 | * @param \App\Article $article
216 | * @return \Illuminate\Http\Response
217 | */
218 | public function articles($id)
219 | {
220 | $user = User::find($id);
221 |
222 | return view('articles.articles', compact('user'));
223 | }
224 |
225 | /**
226 | * Show the form for editing the specified resource.
227 | *
228 | * @param \App\Article $article
229 | * @return \Illuminate\Http\Response
230 | */
231 | public function edit(Article $article)
232 | {
233 | //
234 | }
235 |
236 | /**
237 | * Update the specified resource in storage.
238 | *
239 | * @param \Illuminate\Http\Request $request
240 | * @param \App\Article $article
241 | * @return \Illuminate\Http\Response
242 | */
243 | public function update(Request $request, Article $article)
244 | {
245 | //
246 | }
247 |
248 | /**
249 | * Remove the specified resource from storage.
250 | *
251 | * @param \App\Article $article
252 | * @return \Illuminate\Http\Response
253 | */
254 | public function destroy(Article $article)
255 | {
256 | //
257 | }
258 | }
259 |
260 |
261 | // code 5.10
262 | // app.User.php
263 | public function articles() {
264 | return $this->hasMany('App\Article');
265 | }
266 |
267 |
268 |
269 | // code 5.11
270 | // app/Article.php
271 | public function user() {
272 | return $this->belongsTo('App\User');
273 | }
274 |
275 |
276 | // code 5.14
277 | // resources/views/articles.blade.php
278 |
279 |
280 | @foreach($user->articles as $article)
281 |
282 |
285 |
286 | @endforeach
287 |
288 | …
289 |
290 |
Know about {{ $article->user->name }}
291 |
292 |
293 |
294 |
{{ $article->user->name }}'s Profile
295 |
296 |
Name : {{ $article->user->name }}
297 | Email: {{ $article->user->email }}
298 | City: {{ $article->user->profile->city }}
299 | About: {{ $article->user->profile->about }}
300 |
301 |
302 |
303 |
304 |
305 |
306 |
307 | //code 5.15
308 | //app/Repositories/ Interfaces/UserRepositoryInterface.php
309 | Illuminate\Foundation\ComposerScripts::postAutoloadDump
355 | > @php artisan package:discover
356 | Discovered Package: beyondcode/laravel-dump-server
357 | Discovered Package: fideloper/proxy
358 | Discovered Package: laravel/tinker
359 | Discovered Package: nesbot/carbon
360 | Discovered Package: nunomaduro/collision
361 | Package manifest generated successfully.
362 |
363 |
364 | // code 5.18
365 | //app/HTTP/Controllers/UserController.php
366 | users = $users;
380 | }
381 |
382 | public function index(){
383 | $users = $this->users->all();
384 | return view('users.index', compact('users'));
385 | }
386 | }
387 |
388 |
389 | //code 5.19
390 | //resources/views/users/index.blade.php
391 | @foreach($users as $user)
392 |
393 |
396 |
397 | @endforeach
398 |
399 |
400 |
401 | // code 5.20
402 | // app/Article.php
403 | /**
404 | * Get the tags for the article
405 | */
406 | public function tags() {
407 | return $this->belongsToMany('App\Tag');
408 | }
409 |
410 |
411 | // code 5.21
412 | // app/Country.php
413 | hasMany('App\User');
428 | }
429 |
430 | public function articles(){
431 | return $this->hasManyThrough('App\Article', 'App\User');
432 | }
433 | }
434 |
435 |
436 |
437 | // code 5.22
438 | // database/migrations/countries table
439 | public function up()
440 | {
441 | Schema::create('countries', function (Blueprint $table) {
442 | $table->increments('id');
443 | $table->string('name');
444 | $table->timestamps();
445 | });
446 | }
447 |
448 |
449 |
450 | // database/migrations/users table
451 | public function up()
452 | {
453 | Schema::create('users', function (Blueprint $table) {
454 | $table->increments('id');
455 | $table->integer('country_id');
456 | $table->string('name');
457 | $table->string('email')->unique();
458 | $table->timestamp('email_verified_at')->nullable();
459 | $table->string('password');
460 | $table->rememberToken();
461 | $table->timestamps();
462 | });
463 | }
464 |
465 |
466 |
467 | // database/factories/UserFactory.php
468 | $factory->define(App\User::class, function (Faker $faker) {
469 | return [
470 | 'country_id' => $faker->randomDigit,
471 | 'name' => $faker->name,
472 | 'email' => $faker->unique()->safeEmail,
473 | 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
474 | 'remember_token' => str_random(10),
475 | ];
476 | });
477 |
478 |
479 |
480 | //code 5.23
481 | //resources/views/articles/show.blade.php
482 | @extends('layouts.app')
483 |
484 | @section('content')
485 |
486 |
487 |
488 |
489 |
490 |
{{ $article->title }} by
491 |
{{ $article->user->name }}
492 |
493 |
494 |
495 |
{{ $article->body }}
496 | Tags:
497 | @foreach($tags as $tag)
498 | {{ $tag->tag }}...
499 | @endforeach
500 |
Other Articles by
501 |
502 | {{ $article->user->name }}
503 |
504 | This user belongs to {{ $country->name }}
505 |
506 |
507 |
508 | All articles from {{ $country->name }}
509 |
510 | @foreach($country->articles as $article)
511 |
512 |
513 | {{ $article->title }}
514 |
515 |
516 | @endforeach
517 |
518 |
519 |
520 |
521 |
522 | @endsection
523 |
524 |
525 |
526 |
527 | //code 5.24
528 | //database/migrations/comments table
529 | class CreateCommentsTable extends Migration
530 | {
531 | /**
532 | * Run the migrations.
533 | *
534 | * @return void
535 | */
536 | public function up()
537 | {
538 | Schema::create('comments', function (Blueprint $table) {
539 | $table->increments('id');
540 | $table->integer('user_id');
541 | $table->text('body');
542 | $table->integer('commentable_id');
543 | $table->string('commentable_type');
544 | $table->timestamps();
545 | });
546 | }
547 |
548 | /**
549 | * Reverse the migrations.
550 | *
551 | * @return void
552 | */
553 | public function down()
554 | {
555 | Schema::dropIfExists('comments');
556 | }
557 | }
558 |
559 |
560 |
561 |
562 | // code 5.25
563 | // app/Comment.php
564 | morphTo();
577 | }
578 |
579 | public function user() {
580 | return $this->belongsTo('App\User');
581 | }
582 |
583 | public function users() {
584 | return $this->belongsToMany('App\User');
585 | }
586 |
587 | public function article() {
588 | return $this->belongsTo('App\Article');
589 | }
590 |
591 | public function articles() {
592 | return $this->belongsToMany('App\Article');
593 | }
594 |
595 |
596 | }
597 |
598 |
599 |
600 | -----------------------
601 |
602 | // app/Article.php
603 | belongsTo('App\User');
618 | }
619 |
620 | /**
621 | * Get the tags for the article
622 | */
623 |
624 | public function tags() {
625 | return $this->belongsToMany('App\Tag');
626 | }
627 |
628 | /**
629 | * Get all of the profiles' comments.
630 | */
631 | public function comments(){
632 | return $this->morphMany('App\Comment', 'commentable');
633 | }
634 | }
635 |
636 |
637 | ----------------------
638 |
639 |
640 | // app/Profile.php
641 | belongsTo('App\User');
661 |
662 | }
663 |
664 | /**
665 | * Get all of the profiles' comments.
666 | */
667 | public function comments(){
668 | return $this->morphMany('App\Comment', 'commentable');
669 | }
670 | }
671 |
672 |
673 | --------------------
674 |
675 | // app/User.php
676 | hasOne('App\Profile');
708 |
709 | }
710 |
711 | public function article() {
712 | return $this->hasOne('App\Article');
713 | }
714 |
715 | public function articles() {
716 | return $this->hasMany('App\Article');
717 | }
718 |
719 | public function role() {
720 | return $this->hasOne('App\Role');
721 | }
722 |
723 | public function roles() {
724 | return $this->hasMany('App\Role');
725 | }
726 |
727 | public function country() {
728 | return $this->beongsTo('App\Country');
729 | }
730 |
731 | public function comment() {
732 | return $this->hasOne('App\Comment');
733 | }
734 |
735 | public function comments() {
736 | return $this->hasMany('App\Comment');
737 | }
738 | }
739 |
740 |
741 | ---------------------------
742 |
743 | //code 5.26
744 | // database/factories/UserFactory.php
745 | define(App\User::class, function (Faker $faker) {
761 | return [
762 | 'country_id' => $faker->biasedNumberBetween($min = 1, $max = 20, $function = 'sqrt'),
763 | 'name' => $faker->name,
764 | 'email' => $faker->unique()->safeEmail,
765 | 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
766 | 'remember_token' => str_random(10),
767 | ];
768 | });
769 |
770 | $factory->define(App\Article::class, function (Faker $faker) {
771 | return [
772 | 'user_id' => App\User::all()->random()->id,
773 | 'title' => $faker->sentence,
774 | 'body' => $faker->paragraph(random_int(3, 5))
775 | ];
776 | });
777 |
778 | $factory->define(App\Profile::class, function (Faker $faker) {
779 | return [
780 | 'user_id' => App\User::all()->random()->id,
781 | 'city' => $faker->city,
782 | 'about' => $faker->paragraph(random_int(3, 5))
783 | ];
784 | });
785 |
786 | $factory->define(App\Tag::class, function (Faker $faker) {
787 | return [
788 | 'tag' => $faker->word
789 | ];
790 | });
791 |
792 | $factory->define(App\Role::class, function (Faker $faker) {
793 | return [
794 | 'name' => $faker->word
795 | ];
796 | });
797 |
798 | $factory->define(App\Country::class, function (Faker $faker) {
799 | return [
800 | 'name' => $faker->country
801 | ];
802 | });
803 |
804 | $factory->define(App\Comment::class, function (Faker $faker) {
805 |
806 | return [
807 | 'user_id' => $faker->biasedNumberBetween($min = 1, $max = 10, $function = 'sqrt'),
808 | 'body' => $faker->paragraph(random_int(3, 5)),
809 | 'commentable_id' => $faker->randomDigit,
810 | 'commentable_type' => function(){
811 | $input = ['App\Article', 'App\Profile'];
812 | $model = $input[mt_rand(0, count($input) - 1)];
813 | return $model;
814 | }
815 | ];
816 | });
817 |
818 |
819 |
820 | ----------------
821 |
822 | //code 5.27
823 | //database/seeds/DatabaseSeeder.php
824 | call(UsersTableSeeder::class);
838 | // $this->call(UsersTableSeeder::class);
839 | factory(App\User::class, 10)->create()->each(function($user){
840 | $user->profile()->save(factory(App\Profile::class)->make());
841 | });
842 |
843 | factory(App\Tag::class, 20)->create();
844 |
845 | factory(App\Country::class, 20)->create();
846 |
847 | factory(App\Comment::class, 50)->create();
848 |
849 | factory(App\Article::class, 50)->create()->each(function($article){
850 | $ids = range(1, 50);
851 | shuffle($ids);
852 | $sliced = array_slice($ids, 1, 20);
853 | $article->tags()->attach($sliced);
854 | });
855 |
856 | factory(App\Role::class, 3)->create()->each(function($role){
857 | $ids = range(1, 2);
858 | shuffle($ids);
859 | $sliced = array_slice($ids, 1, 5);
860 | $role->users()->attach($sliced);
861 | });
862 | }
863 | }
864 |
865 |
866 |
867 | -----------------------
868 |
869 |
870 | //code 5.28
871 | mysql> USE laravelmodelrelations
872 | Reading table information for completion of table and column names
873 | You can turn off this feature to get a quicker startup with -A
874 |
875 | Database changed
876 | mysql> SHOW TABLES;
877 | +---------------------------------+
878 | | Tables_in_laravelmodelrelations |
879 | +---------------------------------+
880 | | article_tag |
881 | | articles |
882 | | comments |
883 | | countries |
884 | | migrations |
885 | | password_resets |
886 | | profiles |
887 | | role_user |
888 | | roles |
889 | | tags |
890 | | users |
891 | +---------------------------------+
892 | 11 rows in set (0.00 sec)
893 |
894 | mysql> SELECT * FROM COMMENTS;
895 |
896 |
897 |
898 | -----------------------
899 |
900 |
901 | //code 5.29
902 | //app/HTTP/Controllers/ArticleController.php
903 | orderBy('title', 'desc')->take(10)->get();
925 | $users = User::all();
926 | $tags = Tag::all();
927 | return view('articles.index', compact('articles', 'users', 'tags'));
928 | }
929 |
930 | public function main()
931 | {
932 | $articles = Article::where('user_id', 1)->orderBy('title', 'desc')->take(4)->get();
933 | $tags = Tag::all();
934 | return view('welcome', ['articles' => $articles, 'tags' => $tags]);
935 | }
936 | /**
937 | * Display the specified resource.
938 | *
939 | * @param \App\Article $article
940 | * @return \Illuminate\Http\Response
941 | */
942 | public function show(Article $article)
943 | {
944 | $tags = Article::find($article->id)->tags;
945 | $article = Article::find($article->id);
946 | $comments = $article->comments;
947 | $user = User::find($article->user_id);
948 | $country = Country::where('id', $user->country_id)->get()->first();
949 |
950 | return view('articles.show', compact('tags','article',
951 | 'country', 'comments', 'user'));
952 | }
953 | /**
954 | * Display the specified resource.
955 | *
956 | * @param \App\Article $article
957 | * @return \Illuminate\Http\Response
958 | */
959 | public function articles($id)
960 | {
961 | $user = User::find($id);
962 |
963 | return view('articles.articles', compact('user'));
964 | }
965 | }
966 |
967 |
968 | -----------------------
969 |
970 |
971 | // code 5.30
972 | // resources/views/articles/show.blade.php
973 | @extends('layouts.app')
974 |
975 | @section('content')
976 |
977 |
978 |
979 |
980 |
981 |
{{ $article->title }} by
982 |
{{ $article->user->name }}
983 |
984 |
985 |
986 |
{{ $article->body }}
987 | Tags:
988 | @foreach($tags as $tag)
989 | {{ $tag->tag }}...
990 | @endforeach
991 |
992 |
993 |
994 |
995 | All Comments for this Article
996 |
997 | @foreach($user->profile->comments as $comment)
998 |
{{ $comment->body }}
999 |
by
1000 | {{ $comment->user->name }}
1001 |
1002 | @endforeach
1003 |
1004 |
1005 |
1006 |
1034 |
1035 |
1036 | @endsection
1037 |
1038 |
1039 | -----------------------
1040 |
1041 |
1042 | // code 5.31
1043 | // app/HTTP/Controllers/UserController.php
1044 | users = $users;
1062 |
1063 | }
1064 | /**
1065 | * Display a listing of the resource.
1066 | *
1067 | * @return \Illuminate\Http\Response
1068 | */
1069 | public function index()
1070 | {
1071 | $users = $this->users->all();
1072 | return view('users.index', compact('users'));
1073 | }
1074 |
1075 | /**
1076 | * Show the form for creating a new resource.
1077 | *
1078 | * @return \Illuminate\Http\Response
1079 | */
1080 | public function create()
1081 | {
1082 | //
1083 | }
1084 |
1085 | /**
1086 | * Store a newly created resource in storage.
1087 | *
1088 | * @param \Illuminate\Http\Request $request
1089 | * @return \Illuminate\Http\Response
1090 | */
1091 | public function store(Request $request)
1092 | {
1093 | //
1094 | }
1095 |
1096 | /**
1097 | * Display the specified resource.
1098 | *
1099 | * @param \App\User $user
1100 | * @return \Illuminate\Http\Response
1101 | */
1102 | public function show(User $user)
1103 | {
1104 | //$roles = User::find($user->id)->roles;
1105 | $user = User::find($user->id);
1106 | return view('users.show', compact('user'));
1107 | }
1108 |
1109 | /**
1110 | * Show the form for editing the specified resource.
1111 | *
1112 | * @param \App\User $user
1113 | * @return \Illuminate\Http\Response
1114 | */
1115 | public function edit(User $user)
1116 | {
1117 | //
1118 | }
1119 |
1120 | /**
1121 | * Update the specified resource in storage.
1122 | *
1123 | * @param \Illuminate\Http\Request $request
1124 | * @param \App\User $user
1125 | * @return \Illuminate\Http\Response
1126 | */
1127 | public function update(Request $request, User $user)
1128 | {
1129 | //
1130 | }
1131 |
1132 | /**
1133 | * Remove the specified resource from storage.
1134 | *
1135 | * @param \App\User $user
1136 | * @return \Illuminate\Http\Response
1137 | */
1138 | public function destroy(User $user)
1139 | {
1140 | //
1141 | }
1142 | }
1143 |
1144 |
1145 | ----------------------
1146 |
1147 | // code 5.32
1148 | // resources/views/users/show.blade.php
1149 | @extends('layouts.app')
1150 |
1151 | @section('content')
1152 |
1153 |
1154 |
1155 |
1156 |
1157 |
1158 | Profile of {{ $user->name }}
1159 |
1160 |
1161 |
1162 | Name :
1163 |
{{ $user->name }}
1164 | Email :
1165 | {{ $user->email }}
1166 | City :
1167 | {{ $user->profile->city }}
1168 | About :
1169 | {{ $user->profile->about }}
1170 |
1171 |
1172 |
1173 |
1174 |
1175 | All Comments about {{$user->name}}
1176 |
1177 |
1178 | @foreach($user->profile->comments as $comment)
1179 |
{{ $comment->body }}
1180 |
by
1181 | {{ $comment->user->name }}
1182 |
1183 | @endforeach
1184 |
1185 |
1186 |
1187 |
1188 |
1189 |
1190 |
1191 |
1192 | @endsection
1193 |
1194 |
1195 | --------------------
1196 |
1197 |
1198 |
--------------------------------------------------------------------------------
/chapter-four:
--------------------------------------------------------------------------------
1 | //code 4.1
2 | //app/HTTP/Controllers/TaskController.php
3 | public function show($id)
4 | {
5 | $task = Task::findOrFail($id);
6 | return view('tasks.show', compact('task'));
7 | }
8 |
9 |
10 | ---------
11 |
12 |
13 | //code 4.2
14 | //resources/views/tasks/edit.blade.php
15 |
16 | {!! Form::model($task, ['route' => ['tasks.update', $task->id], 'method' => 'PUT']) !!}
17 |
18 |
19 | {!! Form::label('title', 'Title', ['class' => 'awesome']) !!}
20 | {!! Form::text('title', $task->title, ['class' => 'form-control']) !!}
21 |
22 |
23 | {!! Form::label('body', 'Body', ['class' => 'awesome']) !!}
24 | {!! Form::textarea('body', $task->body, ['class' => 'form-control']) !!}
25 |
26 |
27 | {!! Form::submit('Edit Task', ['class' => 'btn btn-primary form-control']) !!}
28 |
29 | {!! Form::close() !!}
30 |
31 |
32 |
33 | ---------------
34 |
35 | //code 4.3
36 | //app/HTTP/Controllers/TaskController.php
37 | public function edit($id)
38 | {
39 | if(Auth::user()->is_admin == 1){
40 | $task = Task::findOrFail($id);
41 | return view('tasks.edit', compact('task'));
42 | }
43 | else {
44 | return redirect('home');
45 | }
46 | }
47 |
48 |
49 | ---------------
50 |
51 | //code 4.4
52 | //app/HTTP/Controllers/TaskController.php
53 | public function edit(Task $task)
54 | {
55 | if(Auth::user()->is_admin == 1){
56 | return view('tasks.edit', compact('task'));
57 | }
58 | else {
59 | return redirect('home');
60 | }
61 | }
62 |
63 |
64 | ---------------
65 |
66 |
67 | //code 4.5
68 | /**
69 | * Get the route key for the model.
70 | *
71 | * @return string
72 | */
73 | public function getRouteKeyName()
74 | {
75 | return 'slug';
76 | }
77 |
78 |
79 | ----------------
80 |
81 | // code 4.6
82 | // database/migrations/create_password_resets_table.php
83 | public function up()
84 | {
85 | Schema::create('password_resets', function (Blueprint $table) {
86 | $table->string('email')->index();
87 | $table->string('token');
88 | $table->timestamp('created_at')->nullable();
89 | });
90 | }
91 | public function down()
92 | {
93 | Schema::dropIfExists('password_resets');
94 | }
95 |
96 |
97 | --------------
98 |
99 | // code 4.7
100 | $ php artisan make:model Profile -m
101 | Model created successfully.
102 | Created Migration: 2018_09_16_235301_create_profiles_table
103 |
104 |
105 | -------------
106 |
107 | // code 4.8
108 | //profiles table comes up by default
109 |
110 | public function up()
111 | {
112 | Schema::create('profiles', function (Blueprint $table) {
113 | $table->increments('id');
114 | $table->timestamps();
115 | });
116 | }
117 |
118 |
119 | ------------
120 |
121 | // code 4.9
122 | public function up()
123 | {
124 | Schema::create('profiles', function (Blueprint $table) {
125 | $table->increments('id');
126 | $table->integer('user_id');
127 | $table->string('city', 64);
128 | $table->text('about');
129 | $table->timestamps();
130 | });
131 | }
132 |
133 |
134 | --------------
135 |
136 | // code 4.10
137 | $ php artisan make:model Profile -m
138 | Model created successfully.
139 | Created Migration: 2018_09_17_233619_create_profiles_table
140 | $ php artisan make:model Tag -m
141 | Model created successfully.
142 | Created Migration: 2018_09_18_013602_create_tags_table
143 | $ php artisan make:model Article -m
144 | Model created successfully.
145 | Created Migration: 2018_09_18_013613_create_articles_table
146 | $ php artisan make:model Comment -m
147 | Model created successfully.
148 | Created Migration: 2018_09_18_013629_create_comments_table
149 |
150 | $ php artisan make:migration create_article_tag_table --create=article_tag
151 | Created Migration: 2018_09_17_094743_create_article_tag_table
152 |
153 |
154 | ----------------
155 |
156 | // code 4.11
157 | // app/User.php
158 | public function profile() {
159 |
160 | return $this->hasOne('App\Profile');
161 |
162 | }
163 |
164 |
165 | ------------
166 |
167 |
168 | // code 4.12
169 | // app/Profile.php
170 | public function user() {
171 |
172 | return $this->belongsTo('App\User');
173 | }
174 |
175 |
176 |
177 |
178 | --------------
179 |
180 | // code 4.13
181 | // tags table
182 | public function up()
183 | {
184 | Schema::create('tags', function (Blueprint $table) {
185 | $table->increments('id');
186 | $table->string('tag');
187 | $table->timestamps();
188 | });
189 | }
190 |
191 |
192 | -------------
193 |
194 | //Tag.php
195 | belongsToMany('App\Articles');
211 |
212 | }
213 | }
214 |
215 |
216 | ----------------
217 |
218 | // code 4.14
219 | // articles table
220 | public function up()
221 | {
222 | Schema::create('articles', function (Blueprint $table) {
223 | $table->increments('id');
224 | $table->integer('user_id');
225 | $table->string('title');
226 | $table->text('body');
227 | $table->timestamps();
228 | });
229 | }
230 |
231 |
232 | ---------------
233 |
234 | //Article.php
235 | belongsTo('App\User');
250 | }
251 |
252 | /**
253 | * Get the tags for the article
254 | */
255 |
256 | public function tags() {
257 | return $this->belongsToMany('App\Tag');
258 | }
259 |
260 | /**
261 | * Get all of the profiles' comments.
262 | */
263 | public function comments(){
264 | return $this->morphMany('App\Comment', 'commentable');
265 | }
266 | }
267 |
268 |
269 | ---------------
270 |
271 | // code 4.15
272 | // article_tag table
273 | public function up()
274 | {
275 | Schema::create('article_tag', function (Blueprint $table) {
276 | $table->increments('id');
277 | $table->integer('article_id');
278 | $table->integer('tag_id');
279 | $table->timestamps();
280 | });
281 | }
282 |
283 |
284 | ---------------
285 |
286 | // app/Role.php
287 | belongsTo('App\User');
297 | }
298 | public function users() {
299 | return $this->belongsToMany('App\User');
300 | }
301 | }
302 |
303 | ------------------
304 |
305 | //app.User.php
306 | public function role() {
307 | return $this->belongsTo('App\Role');
308 | }
309 | public function roles() {
310 | return $this->belongsToMany('App\Role');
311 | }
312 |
313 |
314 | ----------------
315 |
316 | // database/migrations/roles table
317 | public function up()
318 | {
319 | Schema::create('roles', function (Blueprint $table) {
320 | $table->increments('id');
321 | $table->string('name');
322 | $table->timestamps();
323 | });
324 | }
325 |
326 |
327 | -------------
328 |
329 | // database/migrations/roles table
330 | public function up()
331 | {
332 | Schema::create('role_user', function (Blueprint $table) {
333 | $table->increments('id');
334 | $table->integer('role_id');
335 | $table->integer('user_id');
336 | $table->timestamps();
337 | });
338 | }
339 |
340 |
341 | --------------
342 |
343 | // code 4.16
344 | $ php artisan migrate
345 | Migrating: 2018_09_17_233619_create_profiles_table
346 | Migrated: 2018_09_17_233619_create_profiles_table
347 | Migrating: 2018_09_18_013602_create_tags_table
348 | Migrated: 2018_09_18_013602_create_tags_table
349 | Migrating: 2018_09_18_013613_create_articles_table
350 | Migrated: 2018_09_18_013613_create_articles_table
351 | Migrating: 2018_09_18_013629_create_comments_table
352 | Migrated: 2018_09_18_013629_create_comments_table
353 | Migrating: 2018_09_18_013956_create_article_tag_table
354 | Migrated: 2018_09_18_013956_create_article_tag_table
355 | …
356 | the list is incomplete
357 |
358 | -----------------
359 |
360 | // code 4.17
361 | // database/factory/UserFactory.php
362 | $factory->define(App\User::class, function (Faker $faker) {
363 | return [
364 | 'name' => $faker->name,
365 | 'email' => $faker->unique()->safeEmail,
366 | 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
367 | 'remember_token' => str_random(10),
368 | ];
369 | });
370 |
371 | $factory->define(App\Article::class, function (Faker $faker) {
372 | return [
373 | 'user_id' => App\User::all()->random()->id,
374 | 'title' => $faker->sentence,
375 | 'body' => $faker->paragraph(random_int(3, 5))
376 | ];
377 | });
378 |
379 | $factory->define(App\Profile::class, function (Faker $faker) {
380 | return [
381 | 'user_id' => App\User::all()->random()->id,
382 | 'city' => $faker->city,
383 | 'about' => $faker->paragraph(random_int(3, 5))
384 | ];
385 | });
386 |
387 | $factory->define(App\Tag::class, function (Faker $faker) {
388 | return [
389 | 'tag' => $faker->word
390 | ];
391 | });
392 | $factory->define(App\Role::class, function (Faker $faker) {
393 | return [
394 | 'name' => $faker->word
395 | ];
396 | });
397 |
398 |
399 | -------------------
400 |
401 | // code 4.18
402 | // database/seeds/DatabaseSeeder.php
403 | public function run()
404 | {
405 | factory(App\User::class, 10)->create()->each(function($user){
406 | $user->profile()->save(factory(App\Profile::class)->make());
407 | });
408 |
409 | factory(App\Tag::class, 20)->create();
410 |
411 | factory(App\Article::class, 50)->create()->each(function($article){
412 | $ids = range(1, 50);
413 | shuffle($ids);
414 | $sliced = array_slice($ids, 1, 20);
415 | $article->tags()->attach($sliced);
416 | });
417 |
418 | factory(App\Role::class, 3)->create()->each(function($role){
419 | $ids = range(1, 5);
420 | shuffle($ids);
421 | $sliced = array_slice($ids, 1, 20);
422 | $role->users()->attach($sliced);
423 | });
424 |
425 | }
426 |
427 |
428 | ------------------
429 |
430 | // code 4.19
431 | $ php artisan migrate:refresh –seed
432 |
433 |
434 | ----------------
435 |
436 | // code 4.20
437 | mysql> use laravelmodelrelations
438 | Reading table information for completion of table and column names
439 | You can turn off this feature to get a quicker startup with -A
440 |
441 | Database changed
442 | mysql> show tables;
443 | +---------------------------------+
444 | | Tables_in_laravelmodelrelations |
445 | +---------------------------------+
446 | | article_tag |
447 | | articles |
448 | | comments |
449 | | migrations |
450 | | password_resets |
451 | | profiles |
452 | | role_user |
453 | | roles |
454 | | tags |
455 | | users |
456 | +---------------------------------+
457 | 10 rows in set (0.00 sec)
458 |
459 | mysql> select * from users;
460 |
461 | --------------------
462 |
463 | // code 4.21
464 | // routes/web.php
465 | use App\Article;
466 | use App\Tag;
467 | Route::get('/', function () {
468 | $articles = Article::all();
469 | $tags = Tag::all();
470 | return view('welcome', ['articles' => $articles, 'tags' => $tags]);
471 | });
472 |
473 |
474 | ----------------
475 |
476 | // code 4.22
477 | // resources/views/ welcome.blade.php
478 | @extends('layouts.app')
479 | @section('content')
480 |
512 | @endsection
513 |
514 |
515 | -----------------------
516 |
517 | // code 4.23
518 | // app/Article.php
519 | belongsTo('App\User');
533 | }
534 |
535 | public function users() {
536 | return $this->belongsToMany('App\User');
537 | }
538 |
539 | public function tags() {
540 | return $this->belongsToMany('App\Tag');
541 | }
542 | }
543 |
544 |
545 | ------------------
546 |
547 | // code 4.24
548 | // app/Profile.php
549 | belongsTo('App\User');
568 | }
569 | }
570 |
571 |
572 | -----------------
573 |
574 | // code 4.25
575 | // app/Tag.php
576 | belongsToMany('App\Articles');
592 |
593 | }
594 | }
595 |
596 | -----------------
597 |
598 | // code 4.26
599 | // app/User.php
600 | hasOne('App\Profile');
631 | }
632 |
633 | public function article() {
634 | return $this->hasOne('App\Article');
635 | }
636 |
637 | public function articles() {
638 | return $this->hasMany('App\Article');
639 | }
640 | }
641 |
642 |
643 | ---------------
644 |
645 | // code 4.27
646 | $ php artisan make:controller CommentController --resource --model=Comment
647 |
648 | --------------
649 |
650 | // code 4.28
651 | // app/HTTP/Controllers/CommentController.php
652 | name('home');
707 |
708 | Route::resource('users', 'UserController');
709 | Route::resource('profiles', 'ProfileController');
710 | Route::resource('articles', 'ArticleController');
711 | Route::resource('comments', 'CommentController');
712 | Route::get('/users/{id}/articles', 'ArticleController@articles');
713 | Route::get('/', 'ArticleController@main');
714 |
715 | ---------------------
716 |
717 | // code 4.31
718 | // app/HTTP/Controllers/ArticleController.php
719 | public function index()
720 | {
721 | $articles = Article::orderBy('created_at','desc')->paginate(4);
722 | $users = User::all();
723 | $tags = Tag::all();
724 | return view('articles.index', compact('articles', 'users', 'tags'));
725 | }
726 |
727 |
728 | -----------------
729 |
730 | // code 4.32
731 | // resources/views/articles/index.blade.php
732 | @extends('layouts.app')
733 | @section('content')
734 |
735 |
736 |
737 |
738 |
739 | @foreach($articles as $article)
740 |
741 | {{ $article->title }}
742 |
743 |
744 |
745 | @endforeach
746 | {{ $articles->render() }}
747 |
748 |
749 |
752 |
753 |
761 |
769 |
770 |
771 | @endsection
772 |
773 | -------------------
774 |
775 | // code 4.33
776 | // app/HTTP/Controllers/ ArticleController.php
777 | public function main()
778 | {
779 | $articles = Article::where('user_id', 1)->orderBy('title', 'desc')->take(4)->get();
780 | $tags = Tag::all();
781 | return view('welcome', ['articles' => $articles, 'tags' => $tags]);
782 | }
783 |
784 |
785 | ----------------
786 |
787 | // code 4.34
788 | //resources/views/ welcome.blade.php
789 |
790 | @foreach($articles as $article)
791 |
792 |
793 | {{ $article->title }}
794 |
795 |
796 | @endforeach
797 |
798 | …
799 |
812 |
813 |
814 | -------------------
815 |
816 | // code 4.35
817 | // app/Article.php
818 | public function user() {
819 | return $this->belongsTo('App\User');
820 | }
821 |
822 |
823 | -----------------
824 |
825 |
826 |
827 |
828 |
--------------------------------------------------------------------------------
/chapter-nine:
--------------------------------------------------------------------------------
1 | //code 9.1
2 | Route::bind('books', function ($id){
3 | return App\Book::where('id', $id)-->first();
4 | });
5 |
6 |
7 |
8 | //code 9.2
9 | public function store(Request $request)
10 | {
11 | if (Auth::check()) {
12 | // The user is logged in
13 | }
14 | }
15 |
16 |
17 |
18 |
19 | //code 9.3
20 | use Illuminate\Http\Request;
21 | use App\Http\Requests;
22 | use App\Http\Controllers\Controller;
23 | use Illuminate\Auth\Guard as Auth;
24 | class BooksController extends Controller
25 | {
26 | /**
27 | * Display a listing of the resource
28 | *
29 | * @return Response
30 | */
31 | protected $auth;
32 | public function __construct(Auth $auth) {
33 | $this-->auth = $auth;
34 | }
35 | public function store(Request $request)
36 | {
37 | $this->auth->attempt();
38 | }
39 | }
40 |
41 |
42 | //code 9.4
43 | namespace Illuminate\Auth;
44 | use RuntimeException;
45 | use Illuminate\Support\Str;
46 | use Illuminate\Contracts\Events\Dispatcher;
47 | use Illuminate\Contracts\Auth\UserProvider;
48 | use Symfony\Component\HttpFoundation\Request;
49 | use Symfony\Component\HttpFoundation\Response;
50 | use Illuminate\Contracts\Auth\Guard as GuardContract;
51 | use Illuminate\Contracts\Cookie\QueueingFactory as CookieJar;
52 | use Illuminate\Contracts\Auth\Authenticatable as UserContract;
53 | use Symfony\Component\HttpFoundation\Session\SessionInterface;
54 | class Guard implements GuardContract {....}
55 | //code is incomplete for brevity
56 |
57 |
58 |
59 | //code 9.6
60 | namespace Illuminate\Contracts\Auth;
61 | interface Guard
62 | {
63 | /**
64 | * Attempt to authenticate a user using the
65 | given credentials.
66 | *
67 | * @param array $credentials
68 | * @param bool $remember
69 | * @param bool $login
70 | * @return bool
71 | */
72 | public function attempt(array $credentials = [],
73 | $remember = false, $login = true);
74 | .....
75 | }
76 | //this code is incomplete for brevity
77 |
78 |
79 |
80 | //code 9.7
81 | Route::get('allusers', 'UserController@getAllUsers');
82 |
83 |
84 | //code 9.8
85 | users = $users;
132 |
133 | }
134 | //method injunction
135 | public function getAllUsers(DBUserRepository $users){
136 | return $this->users->all();
137 | }
138 | //other methods and code continue
139 | }
140 |
141 |
142 |
143 | //code 9.11
144 | /**
145 | * Some comments about class Baz
146 | */
147 |
148 | class Baz {};
149 |
150 | /**
151 | * Some comments about class Bax
152 | */
153 | class Bax
154 | {
155 | public $baz;
156 | function __construct(Baz $baz)
157 | {
158 | $this->baz = $baz;
159 | }
160 | }
161 |
162 | /**
163 | * Some comments about class Bar
164 | */
165 | class Bar
166 | {
167 | public $bax;
168 | function __construct(Bax $bax)
169 | {
170 | $this->bax = $bax;
171 | }
172 | }
173 | Route::get('bar', function (Bar $bar) {
174 | dd($bar);
175 | });
176 |
177 |
178 |
179 |
180 | //code 9.12
181 | Route::get('bar', function (Bar $bar) {
182 | dd($bar->bax);
183 | });
184 |
185 |
186 |
187 | //code 9.13
188 | class Bax implements InterfaceBax {};
189 |
190 | class Bar
191 | {
192 | public $bax;
193 |
194 | function __construct(InterfaceBax $bax)
195 | {
196 | $this->bax = $bax;
197 | }
198 | }
199 | Route::get('bar', function (Bar $bar) {
200 | dd($bar);
201 | });
202 |
203 |
204 |
205 | //code 9.14
206 | interface InterfaceBax
207 | {
208 | // code...
209 | }
210 |
211 | class Bax implements InterfaceBax
212 | {
213 |
214 | }
215 | class Bar
216 | {
217 | public $bax;
218 |
219 | function __construct(InterfaceBax $bax)
220 | {
221 | $this->bax = $bax;
222 | }
223 | }
224 |
225 | App::bind('Bar', function(){
226 | return new Bar(new Bax);
227 | });
228 |
229 | Route::get('bar', function (Bar $bar) {
230 | dd($bar);
231 | });
232 |
233 |
234 |
235 | //code 9.15
236 | interface InterfaceBax
237 | {
238 | // code...
239 | }
240 |
241 | class Bax implements InterfaceBax
242 | {
243 |
244 | }
245 | class Bar
246 | {
247 | public $bax;
248 |
249 | function __construct(InterfaceBax $bax)
250 | {
251 | $this->bax = $bax;
252 | }
253 | }
254 |
255 | App::bind('InterfaceBax', 'Bax');
256 |
257 | Route::get('bar', function (Bar $bar) {
258 | dd($bar);
259 | });
260 |
261 |
262 |
263 | //code 9.16
264 | interface InterfaceBax
265 | {
266 | // code...
267 | }
268 |
269 | class Bax implements InterfaceBax
270 | {
271 |
272 | }
273 | class Bar
274 | {
275 | public $bax;
276 |
277 | function __construct(InterfaceBax $bax)
278 | {
279 | $this->bax = $bax;
280 | }
281 | }
282 |
283 | App::bind('InterfaceBax', 'Bax');
284 |
285 | Route::get('bar', function () {
286 | $bar = App::make('InterfaceBax');
287 | dd($bar);
288 | });
289 |
290 |
291 |
292 | //code 9.17
293 | Route::get('bar', function () {
294 | $bar = app()->make('InterfaceBax');
295 | dd($bar);
296 | });
297 |
298 |
299 | //code 9.18
300 | Route::get('bar', function () {
301 | $bar = app()['InterfaceBax'];
302 | dd($bar);
303 | });
304 |
305 |
306 |
307 |
--------------------------------------------------------------------------------
/chapter-one:
--------------------------------------------------------------------------------
1 | //code 1.1
2 | //Laravel Route Example
3 | Route::get('/', function () {
4 | return view('welcome');
5 | });
6 |
7 |
8 | -----------------------
9 |
10 |
11 | //How to use Abstraction using higher and lower modules
12 | interface PaymentInterface {
13 | public function notify();
14 | }
15 |
16 |
17 | class PaymentGateway implements PaymentInterface {
18 |
19 | public function notify() {
20 |
21 | return "You have paid through Stripe";
22 |
23 | }
24 |
25 | }
26 |
27 |
28 | class PaymentNotification {
29 |
30 | protected $notify;
31 |
32 | public function __construct(PaymentInterface $notify) {
33 |
34 | $this->notify = $notify;
35 |
36 | }
37 |
38 | public function notifyClient() {
39 |
40 | return "We have recieved your payment. {$this->notify->notify()}";
41 |
42 | }
43 |
44 |
45 |
46 | }
47 |
48 | $notify = new PaymentNotification(new PaymentGateway);
49 |
50 | echo $notify->notifyClient();
51 |
52 |
53 | -------------------------
54 |
55 | //code 1.16
56 | //config/app.php
57 | 'providers' => [
58 |
59 | /*
60 | * Laravel Framework Service Providers...
61 | */
62 | Illuminate\Auth\AuthServiceProvider::class,
63 | Illuminate\Broadcasting\BroadcastServiceProvider::class,
64 | Illuminate\Bus\BusServiceProvider::class,
65 | Illuminate\Cache\CacheServiceProvider::class,
66 | …
67 | App\Providers\EventServiceProvider::class,
68 | App\Providers\RouteServiceProvider::class,
69 |
70 | ],
71 |
72 |
73 | ------------------------
74 |
75 |
76 |
--------------------------------------------------------------------------------
/chapter-seven:
--------------------------------------------------------------------------------
1 | //code 7.1
2 | $ php artisan list
3 |
4 |
5 | //code 7.2
6 | $ php artisan help migrate
7 |
8 |
9 |
10 |
11 | //code 7.3
12 | Description:
13 | Run the database migrations
14 |
15 | Usage:
16 | migrate [options]
17 |
18 | Options:
19 | --database[=DATABASE] The database connection to use
20 | --force Force the operation to run when in production
21 | --path[=PATH] The path to the migrations files to be executed
22 | --realpath Indicate any provided migration file paths are pre-resolved absolute paths
23 | --pretend Dump the SQL queries that would be run
24 | --seed Indicates if the seed task should be re-run
25 | --step Force the migrations to be run so they can be rolled back individually
26 | -h, --help Display this help message
27 | -q, --quiet Do not output any message
28 | -V, --version Display this application version
29 | --ansi Force ANSI output
30 | --no-ansi Disable ANSI output
31 | -n, --no-interaction Do not ask any interactive question
32 | --env[=ENV] The environment the command should run under
33 | -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
34 |
35 |
36 |
37 |
38 |
39 | //code 7.4
40 | $ php artisan migrate -V
41 |
42 |
43 |
44 |
45 | //code 7.5
46 | composer create-project --prefer-dist laravel/laravel laravelstarttofinish
47 |
48 |
49 | //code 7.6
50 | composer create-project --prefer-dist laravel/laravel laravelstarttofinish "5.8.*"
51 |
52 |
53 |
54 |
55 | //code 7.7
56 | php artisan make:auth
57 |
58 |
59 | // code 7.8
60 | php artisan migrate
61 |
62 |
63 | //code 7.9
64 | // it creates model and table simultaneously
65 | php artisan make:model Profile -m
66 |
67 |
68 | //code 7.10
69 | php artisan migrate:rollback
70 |
71 |
72 | //code 7.11
73 | php artisan make:controller ProfileController --resource
74 |
75 |
76 | //code 7.12
77 | php artisan make:controller ProfileController --resource –model=Profile
78 |
79 |
80 | // code 7.14
81 | php artisan make:migration create_article_tag_table --create=article_tag
82 |
83 |
84 | //code 7.15
85 | php artisan db:seed
86 |
87 |
88 | //code 7.16
89 | // to update seeds
90 | php artisan migrate:refresh --seed
91 |
92 |
93 |
94 | //code 7.17
95 | php artisan serve
96 |
97 |
98 |
99 | // code 7.18
100 | php artisan tinker
101 |
102 |
103 | //code 7.19
104 | $ php artisan tinker
105 |
106 |
107 | //code 7.20
108 | $list = new Listtodo;
109 | $list->name = 'First Job';
110 | $list->description = 'Go to market';
111 | $list->save();
112 |
113 |
114 | //code 7.21
115 | $list = Listtodo::create(
116 | array('name' => 'First Job',
117 | 'description' => 'Go to Market')
118 | );
119 |
120 |
121 | //code 7.22
122 | echo Listtodo::all()->count();
123 |
124 |
125 | //code 7.23
126 | $lists = Listtodo::select('name', 'description')->first();
127 |
128 |
129 | //7.24
130 | $lists = Listtodo::orderBy('name')->get();
131 |
132 |
133 | //code 7.25
134 | $lists = Listtodo::orderBy('name', 'DESC')->get();
135 |
136 | //code 7.26
137 | $lists = Listtodo::where('isComplete', '=', 1)->get();
138 |
139 |
140 | //code 7.27
141 | $lists = Listtodo::take(5)->orderBy('created_at', 'desc')->get();
142 |
143 |
144 | //code 7.28
145 | lists = Listtodo::take(5)->skip(5)->orderBy('created_at', 'desc')->get();
146 |
147 |
148 | //code 7.29
149 | $list = Listtodo::all()->random(1);
150 | $list = Listtodo::orderBy(DB::raw('RAND()'))->first();
151 |
152 |
153 | //code 7.30
154 | $list = Listtodo::find(1);
155 | $list->name = 'Going to market and buying fish';
156 | $list->save();
157 |
158 |
159 | //code 7.31
160 | $list = Listtodo::updateOrCreate(
161 | array('name' => 'Going to market and buying fish'),
162 |
163 |
164 | //code 7.32
165 | $list = Listtodo::find(2);
166 | $list->delete();
167 | Listtodo::destroy(2);
168 |
169 |
170 | //code 7.33
171 | $lists = DB::table('liststodos')->get();
172 | foreach ($lists as $list) {
173 | echo $list->name;
174 | }
175 |
176 |
177 | //code 7.34
178 | $list = DB::table('liststodos')->find(6);
179 |
180 |
181 |
182 | //code 7.35
183 | $lists = DB::table('liststodos')->select('name')->get();
184 |
185 |
186 |
187 | //code 7.36
188 | $lists = DB::select('SELECT * from todolists');
189 |
190 |
191 | //code 7.37
192 | DB::insert('insert into todolists (name, description) values (?, ?)',
193 | array('Second job', 'Finishing the last chapter');
194 |
195 |
196 | //code 7.38
197 | DB::delete('delete from todolists where completed = 1');
198 |
199 |
200 | //code 7.39
201 | $lists = DB::statement('drop table todolists');
202 |
203 |
204 |
205 |
--------------------------------------------------------------------------------
/chapter-six:
--------------------------------------------------------------------------------
1 | //code 6.1
2 | Route::post('user/profile', function () {
3 | // Validate the request...
4 | return back()->withInput();
5 | });
6 |
7 |
8 | //code 6.2
9 | //app/Http//Controller/ArticleController.php
10 | public function index()
11 | {
12 | //
13 | if(Auth::user()->is_admin == 1){
14 | $articles = Article::orderBy('published_at', 'asc')->get();
15 | return view('articles.index', compact('articles'));
16 | }
17 | else {
18 | return redirect('home');
19 | }
20 | }
21 |
22 |
23 |
24 |
25 |
26 | //code 6.3
27 | return redirect()->route('login');
28 |
29 |
30 |
31 |
32 |
33 | //code 6.4
34 | // For a route with the following URI: article/{id}
35 | return redirect()->route('article', ['id' => 1]);
36 |
37 |
38 |
39 | //code 6.5
40 | return redirect()->action('ArticleController@index');
41 |
42 |
43 |
44 | //code 6.6
45 | return redirect()->action(
46 | 'ArticleController@show', ['id' => 1]
47 | );
48 |
49 |
50 |
51 |
52 | //code 6.7
53 | public function update(Request $request, $id)
54 | {
55 | //
56 | if(Auth::user()->is_admin == 1){
57 |
58 | if($file = $request->file('image')){
59 |
60 | $name = $file->getClientOriginalName();
61 |
62 | $post = Article::findOrFail($id);
63 | $post->title = $request->input('title');
64 | $post->body = $request->input('body');
65 | $post->published_at = $request->input('published_at');
66 | $post->image = $name;
67 | $post->save();
68 |
69 | $file->move('images/upload', $name);
70 | }
71 | else {
72 | // code...
73 | $post = Article::findOrFail($id);
74 | $post->title = $request->input('title');
75 | $post->body = $request->input('body');
76 | $post->published_at = $request->input('published_at');
77 | $post->save();
78 |
79 | }
80 |
81 | if($post){
82 | return redirect('articles')->with('status', 'Article Updated!');
83 | }
84 | }
85 | }
86 |
87 |
88 |
89 | //code 6.8
90 | //resources/views/articles/index.blade.php
91 | @if (session('status'))
92 |
93 | {{ session('status') }}
94 |
95 | @endif
96 |
97 |
98 |
99 |
100 | //code 6.9
101 | public function store(Request $request)
102 | {
103 | if($file = $request->file('image')){
104 | $name = $file->getClientOriginalName();
105 | $post = new Article;
106 | $post->title = $request->input('title');
107 | $post->body = $request->input('body');
108 | $post->published_at = $request->input('date');
109 | $post->image = $name;
110 |
111 | $post->save();
112 |
113 | $file->move('images/upload', $name);
114 |
115 | }
116 |
117 | if($post){
118 | return redirect('articles')->with('status', 'Article Created!');
119 | }
120 | }
121 |
122 |
123 | //code 6.10
124 | /**
125 | * Update the specified resource in storage.
126 | *
127 | * @param \Illuminate\Http\Request $request
128 | * @param int $id
129 | * @return \Illuminate\Http\Response
130 | */
131 | public function update(Request $request, $id)
132 | {
133 | //
134 | if(Auth::user()->is_admin == 1){
135 |
136 | if($file = $request->file('image')){
137 |
138 | $name = $file->getClientOriginalName();
139 |
140 | $post = Article::findOrFail($id);
141 | $post->title = $request->input('title');
142 | $post->body = $request->input('body');
143 | $post->published_at = $request->input('published_at');
144 | $post->image = $name;
145 | $post->save();
146 |
147 | $file->move('images/upload', $name);
148 | }
149 | else {
150 | // code...
151 | $post = Article::findOrFail($id);
152 | $post->title = $request->input('title');
153 | $post->body = $request->input('body');
154 | $post->published_at = $request->input('published_at');
155 | $post->save();
156 |
157 | }
158 | if($post){
159 | return redirect('articles')->with('status', 'Article Updated!');
160 | }
161 | }
162 | }
163 |
164 |
165 |
166 |
167 | //code 6.11
168 | Route::get('/', function () {
169 | return [1, 2, 3];
170 | });
171 |
172 |
173 |
174 | //code 6.12
175 | Route::get('post/create', 'ArticlePostController@create');
176 | Route::post('post', 'ArticleController@store');
177 |
178 |
179 | //code 6.13
180 | /**
181 | * Store a new post content.
182 | *
183 | * @param Request $request
184 | * @return Response
185 | */
186 | public function store(Request $request)
187 | {
188 | $validatedData = $request->validate([
189 | 'title' => 'required|unique:posts|max:255',
190 | 'body' => 'required',
191 | ]);
192 | // The content is valid...
193 | }
194 |
195 |
196 |
197 |
198 |
199 |
200 | //code 6.14
201 | validate([
229 | 'title' => 'bail|required|unique:posts|max:255',
230 | 'body' => 'required',
231 | ]);
232 | // The content is valid...
233 | }
234 | }
235 |
236 |
237 |
238 | //code 6.15
239 |
240 |
241 |
Create Post
242 |
243 | @if ($errors->any())
244 |
245 |
246 | @foreach ($errors->all() as $error)
247 | {{ $error }}
248 | @endforeach
249 |
250 |
251 | @endif
252 |
253 |
254 |
255 |
256 |
257 | //code 6.16
258 | $request->validate([
259 | 'title' => 'bail|required|unique:posts|max:255',
260 | 'body' => 'required',
261 | 'publish_at' => 'nullable|date',
262 | ]);
263 |
264 |
265 |
266 |
267 | //code 6.17
268 | //app/HTTP/Controllers/ArticleController.php
269 | public function store(Request $request)
270 | {
271 | //
272 | $validatedData = $request->validate([
273 | 'title' => 'required|unique:posts|max:255',
274 | 'body' => 'required',
275 | ]);
276 | if($file = $request->file('image')){
277 |
278 | $name = $file->getClientOriginalName();
279 |
280 | $post = new Article;
281 | $post->title = $request->input('title');
282 | $post->body = $request->input('body');
283 | $post->published_at = $request->input('date');
284 | $post->image = $name;
285 |
286 | $post->save();
287 |
288 | $file->move('images/upload', $name);
289 |
290 | }
291 |
292 | if($post){
293 | return redirect('articles');
294 | }
295 | }
296 |
297 |
298 |
299 | //code 6.18
300 | //app/HTTP/Controllers/ArticleController.php
301 | class ArticleController extends Controller
302 | {
303 | public function store(Request $request)
304 | {
305 | $validator = Validator::make($request->all(), [
306 | 'title' => 'required|unique:posts|max:255',
307 | 'body' => 'required',
308 | ]);
309 |
310 | if ($validator->fails()) {
311 | return redirect('post/create')
312 | ->withErrors($validator)
313 | ->withInput();
314 | }
315 | //code...
316 | }
317 | }
318 |
319 |
320 |
321 |
322 |
323 |
324 |
325 | //code 6.19
326 |
327 | @csrf
328 | Another one we can use with 'laravelcollective/html' package:
329 | //code
330 | {!! Form::open(['url' => 'foo/bar']) !!}
331 | //
332 | {!! Form::close() !!}
333 |
334 |
335 |
336 | //code 6.20
337 | composer require "laravelcollective/html":"^5.4.0"
338 |
339 |
340 | //code 6.21
341 | 'providers' => [
342 | // ...
343 | Collective\Html\HtmlServiceProvider::class,
344 | // ...
345 | ],
346 |
347 |
348 |
349 | //code 6.22
350 | 'aliases' => [
351 | // ...
352 | 'Form' => Collective\Html\FormFacade::class,
353 | 'Html' => Collective\Html\HtmlFacade::class,
354 | // ...
355 | ],
356 |
357 |
358 |
359 | //code 6.23
360 | //resources/views/articles/create.blade.php
361 |
385 |
386 |
387 |
388 |
389 |
390 |
391 | //code 6.24
392 | {!! Form::open(array('route' => 'route.name')) !!}
393 | {!! Form::open(array('action' => 'Controller@method')) !!}
394 |
395 |
396 |
397 |
398 | //code 6.25
399 | //app/HTTP/Controllers/ArticleController.php
400 |
401 | public function create()
402 | {
403 | if(Auth::user()->is_admin == 1){
404 | return view('articles.create');
405 | }
406 | else {
407 | return redirect('home');
408 | }
409 | }
410 | public function store(Request $request)
411 | {
412 | if($file = $request->file('image')){
413 | $name = $file->getClientOriginalName();
414 | $post = new Article;
415 | $post->title = $request->input('title');
416 | $post->body = $request->input('body');
417 | $post->published_at = $request->input('date');
418 | $post->image = $name;
419 | $post->save();
420 | $file->move('images/upload', $name);
421 | }
422 |
423 |
424 |
425 |
426 |
427 | //code 6.26
428 | //resources/views/articles/edit.blade.php
429 |
452 |
453 |
454 |
455 | //code 6.27
456 | //app/HTTP/Controllers/ArticleController.php
457 | public function edit($id)
458 | {
459 | if(Auth::user()->is_admin == 1){
460 | $article = Article::findOrFail($id);
461 | return view('articles.edit', compact('article'));
462 | }
463 | else {
464 | return redirect('home');
465 | }
466 | }
467 | public function update(Request $request, $id)
468 | {
469 | if(Auth::user()->is_admin == 1){
470 |
471 | if($file = $request->file('image')){
472 |
473 | $name = $file->getClientOriginalName();
474 |
475 | $post = Article::findOrFail($id);
476 | $post->title = $request->input('title');
477 | $post->body = $request->input('body');
478 | $post->published_at = $request->input('published_at');
479 | $post->image = $name;
480 | $post->save();
481 | $file->move('images/upload', $name);
482 | }
483 | else {
484 | $post = Article::findOrFail($id);
485 | $post->title = $request->input('title');
486 | $post->body = $request->input('body');
487 | $post->published_at = $request->input('published_at');
488 | $post->save();
489 | }
490 | if($post){
491 | return redirect('articles');
492 | }
493 | }
494 | }
495 |
496 |
497 |
498 | //code 6.28
499 | {!! Form::password('password') !!}
500 | The same way, we could generate other inputs this way:
501 | {!! Form::email($name, $value = null, $attributes = array()) !!}
502 | {!! Form::file($name, $attributes = array()) !!}
503 | For Checkboxes and Radio Buttons we can go this way:
504 | {!! Form::checkbox('name', 'value') !!}
505 | {!! Form::radio('name', 'value') !!}
506 | We could generate a Checkbox or Radio Input that is "Checked".
507 | {!! Form::checkbox('name', 'value', true) !!}
508 | {!! Form::radio('name', 'value', true) !!}
509 | For the Drop-Down Lists we generally generate it this way:
510 | {!! Form::select('size', array('L' => 'Large', 'S' => 'Small')) !!}
511 | We can generate a Drop-Down list with selected default:
512 | {!! Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S') !!}
513 | For generating a Submit Button the process is quite simple:
514 | echo Form::submit('Click Me!');
515 |
516 |
517 |
518 |
519 | //code 6.29
520 | @extends('layouts.app')
521 |
522 | @section('content')
523 |
524 |
525 |
526 |
527 |
528 |
529 |
530 | Categories
531 |
532 | Posts
533 |
534 | Add Users
535 |
536 |
537 |
538 |
539 |
540 |
541 |
542 |
554 | @endif
555 | @if($categories != null)
556 |
557 | Select Category
558 | *
559 |
560 | @foreach($categories as $category)
561 |
562 | {{$category->name}}
563 |
564 | @endforeach
565 |
566 |
567 | @endif
568 |
569 | News Content
570 | *
571 |
578 |
579 |
580 | @if($writers == null)
581 |
583 |
584 | @endif
585 | @if($writers != null)
586 |
587 | Select Writer
588 | *
589 |
590 |
591 | @foreach($writers as $writer)
592 |
593 | {{ $writer->name }}
594 |
595 | @endforeach
596 |
597 |
598 | @endif
599 |
600 |
601 |
602 |
603 |
604 | Upload Image
605 |
606 |
607 |
608 | Tag
609 | *
610 |
611 |
612 |
613 |
614 |
616 |
617 |
618 |
619 |
620 |
621 |
622 |
623 | @endsection
624 |
625 |
626 |
627 |
628 |
629 |
630 | //code 6.30
631 | /**
632 | * Show the form for creating a new resource.
633 | *
634 | * @return \Illuminate\Http\Response
635 | */
636 | public function create()
637 | {
638 | if( Auth::user()->id == 1 ){
639 | $categories = Category::where('user_id', Auth::user()->id)->get();
640 | $writers = Writer::where('user_id', Auth::user()->id)->get();
641 | return view('articlelead.create', compact('categories', 'writers'));
642 | }
643 | return view('auth.login');
644 |
645 |
646 | }
647 | /**
648 | * Store a newly created resource in storage.
649 | *
650 | * @param \Illuminate\Http\Request $request
651 | * @return \Illuminate\Http\Response
652 | */
653 | public function store(Request $request){
654 | if(Auth::user()->id == 1){
655 | if($file = $request->file('image')){
656 | $name = $file->getClientOriginalName();
657 | //using the Article model to create posts
658 | $post = ArticleLead::create([
659 | 'title' => $request->input('title'),
660 | 'body' => $request->input('body'),
661 | 'user_id' => Auth::user()->id,
662 | 'category_id' => $request->input('category_id'),
663 | 'writer_id' => $request->input('writer_id'),
664 | 'tag' => $request->input('tag'),
665 | 'image' => $name
666 | ]);
667 | $file->move('images/articlesleadnews', $name);
668 | }
669 | if($post){
670 | return redirect()->route('article.show', ['post'=> $post->id])
671 | ->with('success', 'post created successfully');
672 | }
673 | }
674 | return back()->withInput()->with('errors', 'Error creating new post');
675 | }
676 |
677 |
678 |
679 | //code 6.31
680 | @extends('layouts.app')
681 |
682 | @section('content')
683 |