Lập trình website bằng LARAVEL framework PHẦN 3

22 324 0
Lập trình website bằng LARAVEL framework PHẦN 3

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Tài liệu hướng dẫn tự học lập trình website bằng ngôn ngữ PHP Laravel Framework. Hướng dẫn học lập trình LARAVEL chi tiết từ A đến Z. Giúp bạn tự học ngôn ngữ lập trình PHP và Laravel framework một cách tốt hơn.

1 GIÁO TRÌNH LARAVEL - BUỔI A – LÝ THUYẾT I –FORM REQUEST Form Request ? Là thư viện laravel giúp quản lý rules messages File Request riêng (App/http/Rquests ) Tạo sử dụng Request Tạo Request php artisan make:request nameRequest ví dụ: php artisan make:reuest LoginRequest Làm việc với file Request a cho phép sử dụng Request bên public function authorize(){ return true; } Mặc định return flase, để sử dụng bên ta chuyển thành true b Sử dụng rules tương tự Validator public function rules() { return [ //rules ]; } Ví dụ: public function rules() { return [ 'user'=>'required|min:3|max:6', 'pass'=>'required|min:3|max:6', ]; } c Thay đổi lại câu thông báo mặc định tạo thêm function messages public function messages() { return [ ‘user.required’=>’user không để trống’, ‘pass.required’=> ‘pass không để trống’ ]; } In thông báo lỗi a lấy tất thông báo lỗi Cú pháp: @if(count($errorss)) @foreach($errors->all() as $error) {{$error}} @endforeach @endif b Lấy câu thơng báo lỗi {{$errors->first('NameInput')}} Ví dụ: {{ $errors->first('email')}} Mở rộng: Để tránh người dùng nhập đường dẫn sai in thông báo không ý muốn đưa vào Route để sử lý vấn đề Route::any('{all?}','Controller@method'); Ví dụ: Route::any('{all?}','HomeController@mail'); II – RESPONSES responses - thư viện laravel, hỗ trợ chuyển hướng, in chuỗi Json, gọi responses Khai báo Responses use Illuminate\Http\Response; Responses Route::get(‘responses’,function(){ Return ‘Khóa học lập trình Laravel’ }); Responses Json Route::get(‘json’,function(){ $arr = [ ‘khóa học’ => ‘Lập trình laravel’, ‘Nơi học’ => ‘Học viện công nghệ Vietpro’ ]; Return response::json($arr); }); Response XML Route::get('xml', function () { $content = ' học viện công nghệ vietpro Lập Trình Laravel Lập Trình Androi Đồ họa photoshop '; $status = 200; $value = 'text/xml'; return response($content, $status) ->header('Content-Type', $value); }); Cookie Response a tạo Cookie $response = new Response; $response->withCookie(‘name’,’value’,time); ví dụ: use Illuminate\Http\Response; public function setCookie(){ $response->withCookie(‘khoahoc’,’laravel’,1); Return $response; } Lưu ý: thời gian tính phút b Hiển thị Cookie public function getCookie(Request $request){ return $request->cookie(‘khoahoc’); } Rediect a Điều hướng trang web chuyển tiếp Return redirect(/); b Điều hướng trở lại return back(); c Chuyển hướng tới Route Route::get('response/demo',['as'=> 'repon', function(){ return view('login'); }]); Route::get('redirect', function (){ return redirect()->route('repon'); });//truyền theo tham số return redirect()->route('repon', ['id' => 1]); d Chuyển hướng với with() return back()->with([‘message’=>’đây khóa học laravel’]); Nhận thơng báo view @if(Session('message')) {{Session('message')}} @endif d Chuyển hướng với withInput (lấy lại giá trị cũ) return back()->withInput(); return back()->withInput($request->only('pass')); Thêm value view e Chuyển hướng với withErrors $message[] = ‘đây message thông báo’; Return back()->withErrors($message); @if(count($errors)) @foreach($errors->all() as $error) {{$error}} @endforeach @endif Response download $url = ‘public/demo.txt’; return Response::download($url); Response view file ( image, pdf, ) return Response::file($pathUrl); ví dụ return Response::file('public/1.jpg'); Response macro a Tạo Macro php artisan make:provider macroProvider b Cấu trúc public function boot() { // } /** * Register the application services * * @return void */ public function register() { // } c thêm caps cho macro public function boot() { Response::macro('caps', function ($value) { return Response::make(strtoupper($value)); }); } d gọi provider VD: return Response::caps('Hoc vien cong nghe Vietpro'); B – BÀI TẬP I – BÀI TẬP THỰC HÀNH Xây dựng ứng dụng Login có trường Validate sau:  Tài khoản & Mật không để trống  Tài khoản phải Email  Mật phải từ ký tự 10  Tạo thêm liệu CSDL, kiểm tra CSDL chuyển hướng trang admin Chú ý: Sử dụng tạo request response riêng để làm II – BÀI TẬP VỀ NHÀ Sử dụng lại tập thêm chức sau:  Thêm thành viên  Sửa thành viên  Xóa thành viên Chú ý: kiểm tra tồn thành viên CSDL cho thêm sửa 11 GIÁO TRÌNH LARAVEL - BUỔI A – LÝ THUYẾT I –AUTHENTICATION Auth ? Là thư viện laravel giúp xây dựng đăng nhập đăng xuất, cách dễ dàng Sử dụng Auth xây dựng sẵn php artisan make:auth Tùy biến với Auth a Cấu hình cho Auth Cách 1: - sử dụng model user (app/user.php) - tên bảng mặc định users, để thay đổi làm sau: protected $table = ‘$table_name’; ví dụ: protected $table = ‘vp_user’; Vậy thay đổi tên bảng thành vp_user - thay đổi lại cột model + mặc định model user có: protected $fillable = [ 12 'name', 'email', 'password', ]; Cách 2: Ta vào config/auth.php Mặc định Auth // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], Ví dụ: 'users' => [ 'driver' => 'database', 'table' => vp_user, ], Mặc định return flase, để sử dụng bên ta chuyển thành true b Kiểm tra tồn (trong CSDL) Cú pháp: Auth:: attempt([ name=>value ]); Ví dụ: 13 Auth:: attempt([ ‘username’=>’vietpro’ ]); c Kiểm tra đăng nhập Auth::check(); d Kiểm tra chưa đăng nhập Auth::guest(); e Đăng xuất Auth::logout(); f In value đăng nhập Auth::user()->value_colum; Ví dụ: Auth::user()->username; II – PAGINATION 14 Pagination - Pagination thư viện laravel xây dựng sẵn tính phân trang, giúp cho người sử dụng dùng cách dễ dàng a Simple Pagination (chỉ có next Previous) $users = DB::table('users')->simplePaginate(3); b pagination $users = DB::table('users')->Paginate(3); c Hiển thị link phân trang {{ $user->links() }} d Path phân trang $users = DB::table('users')->Paginate(3)->setPath(‘name’); e Thêm biến vào link phân trang {{$user->appends([‘hoc=>’laravel’])->links()}} f Thêm fragment vào đường dẫn {{$user->fragment(‘foo’)-> links()}} 15 B – BÀI TẬP I – BÀI TẬP THỰC HÀNH Bài tập 1: Xây dựng ứng dụng login, logout Auth yêu cầu: - Tạo bảng migration vp_user ( id, username, passoword, level ) - Thêm liệu mẫu seed ( username = admin, password = 123456, level = ) - Kiểm tra trường trống Validator - Nếu người dùng đăng nhập chuyển vào trang Admin sai báo lỗi - Tạo trang logout người dùng lick vào logout chuyển trang login Bài tập 2: Kiểm soát đăng nhập middleware phân trang trang admin: Yêu cầu: - Tạo middleware người dùng chưa đăng nhập khơng vào trang admin ngược lại Thêm liệu mẫu CSDL lấy link phân trang trang Admin 16 GIÁO TRÌNH LARAVEL - BUỔI A – LÝ THUYẾT I – FILESYSTEM / CLOUD STORAGE Filesystem ? thư viện larave giúp chúng làm việc với file, xem , sửa xóa file, hỗ trợ dịch vụ "local", "ftp", "s3", "rackspace" Sử dụng Filesystem a Tạo public php artisan storage:link Chú ý: đường dẫn (storage/app/public) b tạo file ghi nội dung vào file use Storage; Storage::disk('local')->put('file.txt', 'Contents'); Ví dụ Storage::disk('local')->put(demo.txt', 'đây nội dung file demo.txt'); File lưu trữ (storage/app) c tạo folder, file ghi nội dung vào file use Storage; Storage::put('avatars/1', $fileContents); Ví dụ 17 Storage::put('avatars/1.txt', 'noi dung file 1.txt'); c Lấy nội dung File use Storage; $contents = Storage::get('file.txt); d Url File use Storage; $url = Storage::url('file.txt'); e Size File use Storage; $size = Storage::size('file.txt'); f Thêm nội dung vào đầu File use Storage; Storage::prepend('demo.txt', 'Prepended Text'); g Thêm nội dung vào cuối File use Storage; Storage::append('file.log', 'Appended Text'); 18 h Copy move file use Storage; Storage::copy('demo.txt', 'public/demo.txt'); Storage::move('demo.txt', 'public/demo.txt'); i upload file use Storage; $path = $request->photo->storeAs('images', 'filename.jpg'); k delete file use Storage; Storage::delete('file.jpg'); Storage::delete(['file1.jpg', 'file2.jpg']); II – HELPERS Array array_add() $array = array_add(['name' => 'Desk'], 'price', 100); array_forget() 19 $array = ['products' => ['desk' => ['price' => 100]]]; array_forget($array, 'products.desk'); array_get() $array = ['products' => ['desk' => ['price' => 100]]]; $value = array_get($array, 'products.desk'); Path $path = app_path(); $path = base_path(); $path = config_path(); $path = resource_path('assets/sass/app.scss'); $path = storage_path(); Strings $title = str_slug('Laravel Framework', '-'); $string = str_random(40); $value = str_limit('The PHP framework for web artisans.', 7); Url asset(‘public/’); 20 url(‘home’); III – MAIL cài đặt email (.env) MAIL_DRIVER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=587,468 MAIL_USERNAME=wvntours@gmail.com MAIL_PASSWORD=passlamatkhau01 MAIL_ENCRYPTION=tls Send mail use Mail; Mail::send('email.send',$data, function($m){ $m->from('wvntours@gmail.com','lop k33'); $m->to(‘email’,’name’)->subject('title mail'); }); Lưu ý: https://www.google.com/settings/security/lesssecureapps IV Tích hợp Class composer.json 21 "autoload": { "files":[ "class.php" ] }, Ví dụ: "autoload": { "files":[ "app/function.php" ] }, autoload laravel composer dump-autoload php composer.phar dump-autoload B – BÀI TẬP I – BÀI TẬP THỰC HÀNH 22 ... encoding="UTF-8"?> học viện công nghệ vietpro Lập Trình Laravel< /monhoc> Lập Trình Androi Đồ họa photoshop ';... viện laravel, hỗ trợ chuyển hướng, in chuỗi Json, gọi responses Khai báo Responses use IlluminateHttpResponse; Responses Route::get(‘responses’,function(){ Return ‘Khóa học lập trình Laravel ... lập trình Laravel }); Responses Json Route::get(‘json’,function(){ $arr = [ ‘khóa học’ => Lập trình laravel , ‘Nơi học’ => ‘Học viện công nghệ Vietpro’ ]; Return response::json($arr); }); Response

Ngày đăng: 27/02/2018, 13:19

Tài liệu cùng người dùng

Tài liệu liên quan