article

Monday, May 2, 2022

Laravel 9 Auth User Post using Jquery AJAX

Laravel 9 Auth User Post using Jquery AJAX

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory. 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Creating Controller

php artisan make:controller PostController
C:\xampp\htdocs\laravel9\blog>php artisan make:controller PostController
change it with the following codes:
blog\app\Http\Controllers\PostController.php
//blog\app\Http\Controllers\PostController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Auth;
use App\Models\Post; //add Post Model

class PostController extends Controller
{
    public function getPost(){
    	$posts = DB::table('posts')
    			->join('users', 'users.id', '=', 'posts.userid')
    			->select('posts.id as postid', 'posts.*', 'users.id as userid', 'users.*')
    			->orderBy('posts.created_at', 'desc')
    			->get();
 
		return view('postlist', compact('posts'));
    }
 
    public function post(Request $request){
    	if ($request->ajax()){
    		$user = Auth::user();
	    	$post = new Post;
 
	    	$post->userid = $user->id;
	    	$post->post = $request->input('post');
 
	  		$post->save();
 
    		return response($post);
    	}
    }
}
Creating Model
php artisan make:model Post -m
C:\xampp\htdocs\laravel9\blog>php artisan make:model Post -m

This will create our model file located : blog\app\Models\Post.php

we put -m when we create our model.
this will automatically make the migration for our model and you will see that in yourproject/database/migrations
blog\database\migrations\create_posts_table.php
edit code blog\database\migrations\create_posts_table.php
//blog\database\migrations\create_posts_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('userid');
            $table->text('post');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table

Creating our User Auth
composer require laravel/ui
php artisan ui vue --auth

C:\xampp\htdocs\laravel9\blog>composer require laravel/ui
C:\xampp\htdocs\laravel9\blog>php artisan ui vue --auth

Creating Routes
blog\routes\web.php
<?php

use Illuminate\Support\Facades\Route;

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

Auth::routes();

Route::get('/show', 'App\Http\Controllers\PostController@getPost');
Route::post('/post', 'App\Http\Controllers\PostController@post');
Route::get('/home', 'App\Http\Controllers\HomeController@index');
Creating Views
blog\resources\views\home.blade.php
//blog\resources\views\home.blade.php
@extends('layouts.app')

@section('content')
<div class="container">
    <h1 class="page-header text-center">Laravel 9 Auth User Post using Jquery AJAX</h1>
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-body">
                    <form id="postForm">
                        <textarea class="form-control" name="post" id="post" placeholder="What's on your mind?"></textarea>
                        <button type="button" id="postBtn" class="btn btn-primary" style="margin-top:5px;"><i class="fa fa-pencil-square-o"></i> POST</button>
                    </form>
                </div>
            </div>
            <div id="postList"></div>
        </div>
    </div>
</div>
@endsection
 
@section('script')
    <script type="text/javascript">
        $(document).ready(function(){

            showPost();
 
            $('#postBtn').click(function(){
                var post = $('#post').val(); 
                if(post==''){
                    alert('Please write a Post first!');
                    $('#post').focus();
                }
                else{
                    $.ajax({
                        type: 'POST',
                        url: '/post',
                        data: 'post=' + post +'&_token=' +"{{ csrf_token() }}",
                        type: "post",
                        success: function(){
                            alert("Success");
                            showPost();
                            $('#postForm')[0].reset();
                        },
                    });
                }
            });
 
        });
 
        function showPost(){
            $.ajax({
                url: '/show',
                success: function(data){
                    $('#postList').html(data); 
                },
            });
        }
    </script>
@endsection
blog\resources\views\postlist.blade.php
//blog\resources\views\postlist.blade.php
@extends('layouts.app')

@section('content')

@foreach($posts as $post)
<div class="container">
    <div class="row justify-content-center">
        <div class="col-12">

	<div class="panel panel-default">
		<div class="panel-body">
			<p style="font-size:16px;"><b>{{ $post->name }}</b> added a post.</p>
			<p style="font-size:11px; margin-top:-10px;">{{ date('M d, Y h:i A', strtotime($post->created_at)) }}</p>
			<h3 style="padding-top:30px; padding-bottom:30px;">{{ $post->post }}</h3>
		</div>
		<div class="panel-footer">
			<div class="row">
				<div class="col-md-2">
					<button class="btn btn-primary btn-sm"><i class="fa fa-thumbs-up"></i> <span>Like</span></button>
				</div>
				<div class="col-md-10" style="margin-left:-40px;">
					<button type="button" class="btn btn-primary btn-sm comment" value="{{ $post->postid }}"><i class="fa fa-comments"></i> Comment</button>
				</div>
			</div>
		</div>
	</div>
	<div class="" id="comment_{{ $post->postid }}">
	</div>
		</div>
	</div>
</div>
@endforeach

@endsection
blog\resources\views\layouts\app.blade.php
//blog\resources\views\layouts\app.blade.php
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ms-auto">
                        <!-- Authentication Links -->
                        @guest
                            @if (Route::has('login'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                                </li>
                            @endif

                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }}
                                </a>

                                
                                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
    @yield('script')
</body>
</html>
Run C:\xampp\htdocs\laravel9\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post