Laravel User Post using AJAX

Getting Started

Note: I'm using hosted jQuery and font-awesome so you need internet connection for them to work. First, we're going to create a new project and I'm gonna name it post and add it to localhost with the name post.dev. If you have no idea on how to do this, please refer to my tutorial Installing Laravel - PHP Framework.

Setting up our Database

1. Open your phpMyAdmin and create a new database. In my case, I've created a database named social. 2. In our project, open .env file and update the ff lines depending on your setting.
  1. DB_DATABASE=social
  2. DB_USERNAME=root
  3. DB_PASSWORD=

Creating our Controller

1. In command prompt, navigate to your project and type:
  1. php artisan make:controller PostController
This will create our controller in the form of PostController.php located in app/Http/Controllers folder. 2. Open PostController.php and edit it with the ff codes:
  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6. use DB;
  7. use Auth;
  8. use App\Post;
  9.  
  10. class PostController extends Controller
  11. {
  12. public function getPost(){
  13. $posts = DB::table('posts')
  14. ->join('users', 'users.id', '=', 'posts.userid')
  15. ->select('posts.id as postid', 'posts.*', 'users.id as userid', 'users.*')
  16. ->orderBy('posts.created_at', 'desc')
  17. ->get();
  18.  
  19. return view('postlist', compact('posts'));
  20. }
  21.  
  22. public function post(Request $request){
  23. if ($request->ajax()){
  24. $user = Auth::user();
  25. $post = new Post;
  26.  
  27. $post->userid = $user->id;
  28. $post->post = $request->input('post');
  29.  
  30. $post->save();
  31.  
  32. return response($post);
  33. }
  34. }
  35. }

Creating our Models

This is will be our table including the build in user table of Laravel. 1. In command prompt, navigate to our project and type:
  1. php artisan make:model Post -m
This will create our model Post.php located in app folder. It will also create the migration for us due to the -m that we added in creating the model located in database/migrations folder. It will be something like create_posts_table.php. 2. Open this created migration and edit it with the ff:
  1. <?php
  2.  
  3. use Illuminate\Support\Facades\Schema;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Database\Migrations\Migration;
  6.  
  7. class CreatePostsTable extends Migration
  8. {
  9. /**
  10.   * Run the migrations.
  11.   *
  12.   * @return void
  13.   */
  14. public function up()
  15. {
  16. Schema::create('posts', function (Blueprint $table) {
  17. $table->increments('id');
  18. $table->integer('userid');
  19. $table->text('post');
  20. $table->timestamps();
  21. });
  22. }
  23.  
  24. /**
  25.   * Reverse the migrations.
  26.   *
  27.   * @return void
  28.   */
  29. public function down()
  30. {
  31. Schema::dropIfExists('posts');
  32. }
  33. }

Making our Migration/Migrating

In command prompt, navigate to your project and type:
  1. php artisan migrate
If you have an error like this: [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t oo long; max key length is 767 bytes (SQL: alter table `users` add unique ` users_email_unique`(`email`)) You can solve this by opening AppServiceProvider.php located in app/Providers folder. Add this line:
  1. use Illuminate\Support\Facades\Schema;
In boot add this line:
  1. Schema::defaultStringLength(191);
migration error

Creating our User Auth

In command prompt, navigate to your project and type:
  1. php artisan make:auth
This will create our User Authentication pages located in views folder.

Creating our Routes

In routes folder, open web.php and edit it with the ff codes:
  1. <?php
  2. Route::get('/', function () {
  3. return view('welcome');
  4. });
  5.  
  6. Auth::routes();
  7.  
  8. Route::get('/home', 'HomeController@index')->name('home');
  9.  
  10. Route::post('/post', 'PostController@post');
  11.  
  12. Route::get('/show', 'PostController@getPost');

Creating our Views

In resources/views folder, create/update the ff files: home.blade.php
  1. @extends('layouts.app')
  2.  
  3. @section('content')
  4. <div class="container">
  5. <h1 class="page-header text-center">Laravel User Post using AJAX</h1>
  6. @if (session('status'))
  7. <div class="alert alert-success">
  8. {{ session('status') }}
  9. </div>
  10. @endif
  11. <div class="row">
  12. <div class="col-md-8 col-md-offset-2">
  13. <div class="panel panel-default">
  14. <div class="panel-body">
  15. <form id="postForm">
  16. <textarea class="form-control" name="post" id="post" placeholder="What's on your mind?"></textarea>
  17. <button type="button" id="postBtn" class="btn btn-primary" style="margin-top:5px;"><i class="fa fa-pencil-square-o"></i> POST</button>
  18. </form>
  19. </div>
  20. </div>
  21. <div id="postList"></div>
  22. </div>
  23. </div>
  24. </div>
  25. @endsection
  26.  
  27. @section('script')
  28. <script type="text/javascript">
  29. $(document).ready(function(){
  30. $.ajaxSetup({
  31. headers: {
  32. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  33. }
  34. });
  35.  
  36. showPost();
  37.  
  38. $('#postBtn').click(function(){
  39. var post = $('#post').val();
  40. if(post==''){
  41. alert('Please write a Post first!');
  42. $('#post').focus();
  43. }
  44. else{
  45. var postForm = $('#postForm').serialize();
  46. $.ajax({
  47. type: 'POST',
  48. url: '/post',
  49. data: postForm,
  50. dataType: 'json',
  51. success: function(){
  52. showPost();
  53. $('#postForm')[0].reset();
  54. },
  55. });
  56. }
  57. });
  58.  
  59. });
  60.  
  61. function showPost(){
  62. $.ajax({
  63. url: '/show',
  64. success: function(data){
  65. $('#postList').html(data);
  66. },
  67. });
  68. }
  69. </script>
  70. @endsection
postlist.blade.php
  1. @foreach($posts as $post)
  2. <div class="panel panel-default">
  3. <div class="panel-body">
  4. <p style="font-size:16px;"><b>{{ $post->name }}</b> added a post.</p>
  5. <p style="font-size:11px; margin-top:-10px;">{{ date('M d, Y h:i A', strtotime($post->created_at)) }}</p>
  6. <h3 style="padding-top:30px; padding-bottom:30px;">{{ $post->post }}</h3>
  7. </div>
  8. <div class="panel-footer">
  9. <div class="row">
  10. <div class="col-md-2">
  11. <button class="btn btn-primary btn-sm"><i class="fa fa-thumbs-up"></i> <span>Like</span></button>
  12. </div>
  13. <div class="col-md-10" style="margin-left:-40px;">
  14. <button type="button" class="btn btn-primary btn-sm comment" value="{{ $post->postid }}"><i class="fa fa-comments"></i> Comment</button>
  15. </div>
  16. </div>
  17. </div>
  18. </div>
  19. <div class="" id="comment_{{ $post->postid }}">
  20. </div>
  21. @endforeach
In views/layouts folder, update the ff: app.blade.php
  1. <!DOCTYPE html>
  2. <html lang="{{ app()->getLocale() }}">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7.  
  8. <!-- CSRF Token -->
  9. <meta name="csrf-token" content="{{ csrf_token() }}">
  10.  
  11. <title>{{ config('app.name', 'Laravel User Post using AJAX') }}</title>
  12.  
  13. <!-- Styles -->
  14. <link href="{{ asset('css/app.css') }}" rel="stylesheet">
  15. <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  16. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  17. </head>
  18. <body>
  19. <div id="app">
  20. <nav class="navbar navbar-default navbar-static-top">
  21. <div class="container">
  22. <div class="navbar-header">
  23.  
  24. <!-- Collapsed Hamburger -->
  25. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
  26. <span class="sr-only">Toggle Navigation</span>
  27. <span class="icon-bar"></span>
  28. <span class="icon-bar"></span>
  29. <span class="icon-bar"></span>
  30. </button>
  31.  
  32. <!-- Branding Image -->
  33. <a class="navbar-brand" href="{{ url('/') }}">
  34. {{ config('app.name', 'Laravel') }}
  35. </a>
  36. </div>
  37.  
  38. <div class="collapse navbar-collapse" id="app-navbar-collapse">
  39. <!-- Left Side Of Navbar -->
  40. <ul class="nav navbar-nav">
  41. &nbsp;
  42. </ul>
  43.  
  44. <!-- Right Side Of Navbar -->
  45. <ul class="nav navbar-nav navbar-right">
  46. <!-- Authentication Links -->
  47. @guest
  48. <li><a href="{{ route('login') }}">Login</a></li>
  49. <li><a href="{{ route('register') }}">Register</a></li>
  50. @else
  51. <li class="dropdown">
  52. <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true">
  53. {{ Auth::user()->name }} <span class="caret"></span>
  54. </a>
  55.  
  56. <ul class="dropdown-menu">
  57. <li>
  58. <a href="{{ route('logout') }}"
  59. onclick="event.preventDefault();
  60. document.getElementById('logout-form').submit();">
  61. Logout
  62. </a>
  63.  
  64. <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
  65. {{ csrf_field() }}
  66. </form>
  67. </li>
  68. </ul>
  69. </li>
  70. @endguest
  71. </ul>
  72. </div>
  73. </div>
  74. </nav>
  75.  
  76. @yield('content')
  77. </div>
  78.  
  79. <!-- Scripts -->
  80. <script src="{{ asset('js/app.js') }}"></script>
  81. @yield('script')
  82. </body>
  83. </html>

Running our Server

In your web browser, type the name that you added in localhost for your project in my case, post.dev. That ends this tutorial. Happy Coding :)

Add new comment