Skip to content

Instantly share code, notes, and snippets.

@prasanth22
Last active December 6, 2020 14:45
Show Gist options
  • Save prasanth22/eb6c3d56c6db5bb9bf0a627513e51a84 to your computer and use it in GitHub Desktop.
Save prasanth22/eb6c3d56c6db5bb9bf0a627513e51a84 to your computer and use it in GitHub Desktop.

Laravel

routes:
In laravel routes are seen in routes/web.php file

Route::get('/', function () {
    return view('welcome');
});

requests: http://127.0.0.1:9000/?name=prasanth

Route::get('/', function () {
    return view('welcome', [
        'name' => request('name')
    ]);
});

in view use {{ $name }} to print name. in blade template {{ }} will remove html tags around instead if we use {!! !!} will not remove tags

compiled blade files can be seen under storage folder

route parameters:

Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});
Route::get('posts/{post}', function ($post) {

    $posts = [
        'first-post' => 'lknlkja ajshfaj sjhfa ansfkj',
        'sdjflja' => 'skdnfa;ljsdf,kjh;kjna hkjjlkll'
    ];
    
    if(! array_key_exists($post, $posts)){
        abort(404);
    }

    return view('post', [
        'post' => $posts[$post]
    ]);
});

Validations:

/**
 * Validate the request
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email|unique:users'…

Laravel & Ajax:

  • step one: add the following routes
//For Ajax Demo 
Route::get('/ajaxDemo', 'FrontendController@ajaxDemo')
->name('ajaxDemo'); 
Route::post('/ajaxDemo', 'FrontendController@ajaxDemo')
->name('postAjaxDemo');
  • step two: add the following ajax in code in script
$("#ajaxDemoForm").on('submit', function(e){             
  e.preventDefault();     
 //serializing form data       
 var formData = $(this).serialize();     
 var ajaxUrl = $(this).attr('action'); 
 //Getting the url  
 $.ajax({   
  url: ajaxUrl,  
  data : formData,  
  method : "POST",  
  success : function(data) {   
   $(".message").addClass('alert alert-success');   
   $(".message").html(data.result);  
  }, 
  error : function(data) {   
   $(".message").addClass('alert alert-danger');   
   $(".message").html(data.result);  
  } 
 });
});
  • step three: add following method to the controller
/**
* Ajax Demo 
*
* @return json response or view
* @author 
**/
public function ajaxDemo (Request $request)
{
	if($request->method() == "POST")
	{
		/**
    		 * Do all the processing on the data and return success or failure 
    		 */    		
    		return response()->json(array("result" => "success"));
    	}
    	else
    	{
    		return view('ajaxDemo');
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment