laravel ÇëÇó²ÎÊý
laravelÊÇÒ»¸öÊ¢ÐеÄphp¿ò¼Ü£¬ËüÔÚ´¦Öóͷ£httpÇëÇóʱÌṩÁ˼«´óµÄÎÞаÐÔºÍÀû±ãÐÔ¡£ÔÚlaravelÖУ¬ÇëÇó²ÎÊýÊÇÖ¸´Ó¿Í»§¶Ë·¢Ë͵½Ð§ÀÍÆ÷¶ËµÄÊý¾Ý£¬ËüÃÇ°üÀ¨ÁËÓû§ÊäÈëµÄÐÅÏ¢£¬Èç±íµ¥ÖеÄÊý¾ÝºÍÅÌÎÊ×Ö·û´®ÖеÄÊý¾Ý¡£±¾ÎĽ«ÏÈÈÝlaravelÖÐÇëÇó²ÎÊýµÄ´¦Öóͷ£·½·¨£¬°üÀ¨»ñÈ¡ÇëÇó²ÎÊý¡¢´¦Öóͷ£ÑéÖ¤¡¢ÉèÖÃĬÈÏÖµÒÔ¼°Ò»Ð©³£¼ûµÄÓÃÀý¡£
Ò»¡¢»ñÈ¡ÇëÇó²ÎÊý
ÔÚLaravelÖУ¬¿ÉÒÔʹÓá°Request¡±Àà»ñÈ¡ÇëÇó²ÎÊý¡£ÒÔÏÂÊÇһЩ³£ÓõĻñÈ¡ÇëÇó²ÎÊýµÄÒªÁ죺
1.»ñÈ¡ÅÌÎÊ×Ö·û´®²ÎÊý£ºÊ¹ÓÃinputÒªÁì»òqueryÒªÁì»ñÈ¡¡£
$name = $request->input('name'); $name = $request->query('name');
µÇ¼ºó¸´ÖÆ
2.»ñÈ¡±íµ¥²ÎÊý£ºÊ¹ÓÃinputÒªÁì»ògetÒªÁì»ñÈ¡¡£ÈôÊÇʹÓÃPOSTÇëÇ󣬿ÉÒÔʹÓÃinputÒªÁì»òpostÒªÁì»ñÈ¡¡£
$name = $request->input('name'); $name = $request->get('name'); $name = $request->post('name');
µÇ¼ºó¸´ÖÆ
3.»ñȡ·ÓɲÎÊý£ºÊ¹ÓÃrouteÒªÁì»ñÈ¡¡£
$user_id = $request->route('user_id');
µÇ¼ºó¸´ÖÆ
¶þ¡¢ÇëÇóÑéÖ¤
ÔÚ´¦Öóͷ£ÇëÇó²ÎÊýʱ£¬Í¨³£ÐèÒª¶Ô²ÎÊý¾ÙÐÐÑéÖ¤ÒÔÈ·±£²ÎÊýµÄÓÐÓÃÐÔ¡£LaravelÌṩÁËÄÚÖõÄÑéÖ¤Æ÷À´ÑéÖ¤ÇëÇó²ÎÊý¡£ÒÔÏÂÊÇһЩ³£¼ûµÄÑéÖ¤¹æÔò£º
1.required£º±ØÌî×ֶΡ£
2.minimum£º×îСֵ¡£
3.maximum£º×î´óÖµ¡£
4.email£ºµç×ÓÓʼþÃûÌá£
5.numeric£ºÊýÖµÀàÐÍ¡£
6.regex£ºÕýÔò±í´ïʽ¡£
7.exists£º±£´æÓÚÖ¸¶¨µÄ±íÖС£
ÒÔÏÂÊÇÒ»¸ö¼òÆÓµÄÀý×Ó£º
$validatedData = $request->validate([ 'name' => 'required', 'email' => 'required|email', 'age' => 'required|numeric|min:18', ]);
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄÀý×ÓÖУ¬½«ÑéÖ¤¡°name¡±ºÍ¡°email¡±×Ö¶ÎÊÇ·ñÌîд²¢ÇÒÊÇ·ñΪÓÐÓõĵç×ÓÓʼþµØµã£¬¡°age¡±×ֶαØÐèÊÇÊýÖµÀàÐÍÇÒ±ØÐè´óÓÚ¼´ÊÇ18¡£ÈôÊÇÑé֤ʧ°Ü£¬½«»áÅ׳öÒ»¸ö¡°ValidationException¡±Òì³£¡£
Èý¡¢ÉèÖÃĬÈÏÖµ
ÓÐʱ£¬ÇëÇó²ÎÊý¿ÉÄÜûÓÐÌîд£¬ÎªÁ˱ÜÃâ·ºÆð¹ýʧ£¬ÉèÖÃĬÈÏÖµÊÇÒ»Öֺܺõķ½·¨¡£ÔÚLaravelÖУ¬¿ÉÒÔʹÓÃgetÒªÁìת´ïµÚ¶þ¸ö²ÎÊýÀ´ÉèÖÃĬÈÏÖµ¡£ÀýÈ磺
$name = $request->get('name', 'John Doe');
µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄÀý×ÓÖУ¬ÈôÊÇûÓÐÌîд¡°name¡±×ֶΣ¬ÔòĬÈÏֵΪ¡°John Doe¡±¡£
ËÄ¡¢³£¼ûÓÃÀý
ÒÔÏÂÊÇһЩ³£¼ûµÄÓÃÀý£º
1.ÎļþÉÏ´«
LaravelÌṩÁ˺ܺõÄÎļþÉÏ´«¹¦Ð§£¬¿ÉÒÔͨ¹ý$request->file()ÒªÁì»ñÈ¡ÉÏ´«µÄÎļþ¡£ÀýÈ磺
$file = $request->file('photo'); if ($file->isValid()) { // ´¦Öóͷ£ÎļþÉÏ´« }
µÇ¼ºó¸´ÖÆ
2.´¦Öóͷ£JSONÇëÇó
ÔÚLaravelÖУ¬¿ÉÒÔͨ¹ý$request->json()ÒªÁì»ñÈ¡JSONÀàÐ͵ÄÇëÇó²ÎÊý¡£ÀýÈ磺
$data = $request->json()->all();
µÇ¼ºó¸´ÖÆ
3.»ñÈ¡ÇëÇó·½·¨
ʹÓÃ$request->method()ÒªÁì¿ÉÒÔ»ñÈ¡ÇëÇó·½·¨¡£ÀýÈ磺
if ($request->method() === 'POST') { // ´¦Öóͷ£POSTÇëÇó }
µÇ¼ºó¸´ÖÆ
4.»ñÈ¡ÇëÇóµÄURL
ʹÓÃ$request->fullUrl()ÒªÁì¿ÉÒÔ»ñÈ¡ÇëÇóµÄÍêÕûURLµØµã¡£ÀýÈ磺
$url = $request->fullUrl();
µÇ¼ºó¸´ÖÆ
Îå¡¢½áÂÛ
ÔÚLaravelÖÐ׼ȷ´¦Öóͷ£ÇëÇó²ÎÊýºÜÖ÷Òª£¬²»µ«¿ÉÒÔÌá¸ßÍøÕ¾µÄÇå¾²ÐÔ£¬»¹¿ÉÒÔÌá¸ß´úÂëµÄ¿É¶ÁÐԺͿÉά»¤ÐÔ¡£Í¨¹ý±¾ÎĵÄÏÈÈÝ£¬ÄúÓ¦¸ÃÒѾÏàʶÔõÑùÔÚLaravelÖд¦Öóͷ£ÇëÇó²ÎÊý¡¢ÑéÖ¤ÇëÇó²ÎÊý¡¢ÉèÖÃĬÈÏÖµÒÔ¼°Ò»Ð©³£¼ûµÄÓÃÀý¡£
ÒÔÉϾÍÊÇlaravel ÇëÇó²ÎÊýµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡