Friday, March 20, 2020

Laravel ajax from submit by serializeArray

AJAX ` $(".submit").click(function(e) {
    e.preventDefault();

var formSelector = $(this).data("form");
    var form = $("#" + formSelector);
    var url = form.attr('action');
    var product = form.serializeArray();

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': csrf
        }
    });
 
    $.ajax({
        type: "POST",
        url: url,
        data: product,
        success: function(returndata){
            //debugger;
            location.reload();
        }
    });`
routes.php Route::group(['prefix' => 'admin'], function(){ Route::post('categories/add', BackendPagesController@addCategory'); });
BackendPagesController.php ` public function addCategory(Request $request){
    $name = $request->input('category-name');
    $categoryUrl = $request->input('category-url');
    $parentCategory = $request->input('kategorie');
    $categoryImageUrl = $request->input('category-image-url');

    if($parentCategory == "keine"){
        $parentCategory = 0;
    }

    $position = Categories::max('order_by');

    $category = new Categories;

    $category->name = $name;
    $category->url_alias = $categoryUrl;
    $category->parent_id = $parentCategory;
    $category->image_url = $categoryImageUrl;
    $category->meta_title = $request['meta-category-title'] ?? '';
    $category->meta_description = $request['meta-category-description'] ?? '';
    $category->order_by = $parentCategory;

    $category->save();

    if($category->id){                
        return $category->id;                   
    }else{                    
        return "wurde nicht eingetragen";
    }
        
}



Thursday, March 19, 2020

Laravel cron job

Running a cron job 3 times (1 pm, 2 pm and 3 pm) in Laravel


Open cronjob config with vim & add script bellow

m h dom mon dow command

  • 13,14,15 * * * php /var/www/project/artisan schedule:run >> /dev/null 2>&1

File upload using Laravel and Vue.js (The Right Way)

Ways to upload a file

Most articles showing how to upload a file using JavaScript actually teach how to encode the file contents in Base64 so it can be included in the JSON request. It works, but it's not as efficient as other methods. In this post I'll show how to upload a file using the multipart/FormData method using Vue.js together with axios.

Base64 inside JSON

Advantages:
  • No need to manually encode/decode your data in JSON (if using any frontend framework or client library)
  • File's content is just another field in the JSON object
Disadvantages:
  • Need to encode the file in Base64
  • Uses more CPU, more memory, and more network bandwidth (Base64 uses 33% more space than binary)
  • Little support from backend frameworks

Multipart

Advantages:
  • No need to encode the file in Base64
  • Uses less CPU, less memory, and less network bandwidth
  • Full support from backend frameworks
Disadvantages:
  • Need to manually encode/decode your data in JSON
  • File's content is separate from the JSON object

Getting the file

In one way or another, your page will have a file input element that lets the user choose a file. Vue will complain if you try to use v-model on it because file inputs are readonly, so we usually add an event handler for the change event.

     type="file" @change="selectFile">

Sending the file

File input elements have a files property that is an array of instances of the File class. It has some metadata about the selected file and methods to read its contents. Besides that, it can be used directly as a value in a FormData object. The FormData class allows one to use JavaScript to build the same request that a plain HTML form would create. You can use a FormData object as the request's body when using axios, jQuery or even plain XMLHttpRequest objects.
The following:
const data = new FormData();
data.append('photo', this.photo);
data.append('description', this.description);
data.append('productId', this.productId);
axios.post("/api/photo", data);
Is roughly the same as:
method="POST" enctype="multipart/form-data" action="/api/photo"> type="file" name="photo"/> type="text" name="description"/> type="text" name="productId">
If you have complex data as arrays or nested objects, you will have to convert them to JSON manually:
const data = new FormData();
data.append('photo', this.photo);
const json = JSON.stringify({
    description: this.description,
    productId: this.productId,
});
data.append('data', json);
axios.post("/api/photo", data);

Receiving the file

At the Laravel side, there is full support to handle file uploads transparently using the Request class. Uploaded files are fields like any other, presented by the framework as instances of the Illuminate\Http\UploadedFile class. From there on you can read the file's contents or store it somewhere else.
public function savePhoto(Request $request)
{
    // Validate (size is in KB)
    $request->validate([
        'photo' => 'required|file|image|size:1024|dimensions:max_width=500,max_height=500',
    ]);

    // Read file contents...
    $contents = file_get_contents($request->photo->path());

    // ...or just move it somewhere else (eg: local `storage` directory or S3)
    $newPath = $request->photo->store('photos', 's3');
}
If you had complex data that you manually converted to JSON, you need to decode it before use:
public function savePhoto(Request $request)
{
    $request['data'] = json_decode($request['data']);

    // Validate
    $request->validate([
        'data.description' => 'required|filled|size:100',
        'data.productId' => 'required|int|exists:App\Product,id'
    ]);

    // ...the rest is the same...
}

Link : https://dev.to/diogoko/file-upload-using-laravel-and-vue-js-the-right-way-1775

Tuesday, March 10, 2020

Laravel & Vue CRUD Single Page Application (SPA) Tutorial

In this tutorial, using Laravel and Vue.Js, we are going to create a single page application. We will learn who to create, read, update and delete using Vue.Js frontend and Laravel API backend.
Table of Contents
  1. Install Laravel and NPM Dependencies
  2. Create Migration, Model and Controller
  3. Define Laravel Routes
  4. Create Vue App
  5. Create Vue Components
  6. Define Vue Routes
  7. Import All to app.js
  8. The Output

Step 1 : Install Laravel and NPM Dependencies

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.
After installing Laravel, run this command to install frontend dependencies:
npm install
We need to install vue-router and vue-axios. vue-axios will be used for calling Laravel API. Let’s install these:
npm install vue-router vue-axios --save
After installing all dependencies run this command:
npm run watch
This npm run watch command will listen for file changes and will compile assets instantly. You can also run this command npm run dev. It won’t listen for file changes.

Step 2 : Create Migration, Model and Controller

We are going to create Book model, migration and controller. We will add, read, update, delete book. Run this artisan command to create these 3 at once:
php artisan make:model Book -mcr
Now open create_books_table.php migration file from database>migrations and replace up() function with this:
create_books_table.php
public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('author');
        $table->timestamps();
    });
}
Migrate the database using the following command:
php artisan migrate
Open Book.php model from app folder and paste this code:
Book.php


namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $fillable = ['name', 'author'];
}
We need to define the index, add, edit, delete methods in BookController file. Open BookController.php from app>Http>Controllers folder and paste this code:
BookController.php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Resources\BookCollection;
use App\Book;

class BookController extends Controller
{
    // all books
    public function index()
    {
        $books = Book::all()->toArray();
        return array_reverse($books);
    }

    // add book
    public function add(Request $request)
    {
        $book = new Book([
            'name' => $request->input('name'),
            'author' => $request->input('author')
        ]);
        $book->save();

        return response()->json('The book successfully added');
    }

    // edit book
    public function edit($id)
    {
        $book = Book::find($id);
        return response()->json($book);
    }

    // update book
    public function update($id, Request $request)
    {
        $book = Book::find($id);
        $book->update($request->all());

        return response()->json('The book successfully updated');
    }

    // delete book
    public function delete($id)
    {
        $book = Book::find($id);
        $book->delete();

        return response()->json('The book successfully deleted');
    }
}

Step 3 : Define Laravel Routes

Our model, migration and controller are ready to use. Let’s define the web and API routes. Open web.php from routes folder and register this route:
web.php


Route::get('{any}', function () {
    return view('app');
})->where('any', '.*');
Open api.php and define CRUD routes like these:
api.php


use Illuminate\Http\Request;

Route::middleware('auth:api')->get('user', function (Request $request) {
    return $request->user();
});

Route::get('books', 'BookController@index');
Route::group(['prefix' => 'book'], function () {
    Route::post('add', 'BookController@add');
    Route::get('edit/{id}', 'BookController@edit');
    Route::post('update/{id}', 'BookController@update');
    Route::delete('delete/{id}', 'BookController@delete');
});

Step 4 : Create Vue app

To declaratively render data to the DOM using Vue.js we need to declare Vue app. Navigate to resources>views folder and create a file called app.blade.php. Then paste this code:
app.blade.php

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" value="{{ csrf_token() }}"/>
    <title>Laravel & Vue CRUD Single Page Application (SPA) Tutorial - MyNotePaper</title>
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet" type="text/css">
    <link href="{{ mix('css/app.css') }}" type="text/css" rel="stylesheet"/>
    <style>
        .bg-light {
            background-color: #eae9e9 !important;
        }
    </style>
</head>
<body>
<div id="app">
</div>
<script src="{{ mix('js/app.js') }}" type="text/javascript"></script>
</body>
</html>

Step 5 : Create Vue Components

We are going to add 4 Vue components.
  • App.vue
  • AllBooks.vue
  • AddBook.vue
  • EditBook.vue
App.vue is the main Vue file. We will define router- view in the file. So all route pages will be shown in the App.vue file
Go to resources>js folder and create a file called App.vue and paste this code:
App.vue
<template>
    <div class="container">
        <div class="text-center" style="margin: 20px 0px 20px 0px;">
            <a href="https://www.mynotepaper.com/" target="_blank"><img src="https://i.imgur.com/hHZjfUq.png"></a><br>
            <span class="text-secondary">Laravel & Vue CRUD Single Page Application (SPA) Tutorial</span>
        </div>

        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <div class="collapse navbar-collapse">
                <div class="navbar-nav">
                    <router-link to="/" class="nav-item nav-link">Home</router-link>
                    <router-link to="/add" class="nav-item nav-link">Add Book</router-link>
                </div>
            </div>
        </nav>
        <br/>
        <router-view></router-view>
    </div>
</template>

<script>
    export default {}
</script>
In the resources>js create a folder called components and go to the folder. We are going to create the rest 3 Vue components here. We So, let’s create.
AllBooks.vue
<template>
    <div>
        <h3 class="text-center">All Books</h3><br/>

        <table class="table table-bordered">
            <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Author</th>
                <th>Created At</th>
                <th>Updated At</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="book in books" :key="book.id">
                <td>{{ book.id }}</td>
                <td>{{ book.name }}</td>
                <td>{{ book.author }}</td>
                <td>{{ book.created_at }}</td>
                <td>{{ book.updated_at }}</td>
                <td>
                    <div class="btn-group" role="group">
                        <router-link :to="{name: 'edit', params: { id: book.id }}" class="btn btn-primary">Edit
                        </router-link>
                        <button class="btn btn-danger" @click="deleteBook(book.id)">Delete</button>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                books: []
            }
        },
        created() {
            this.axios
                .get('http://localhost:8000/api/books')
                .then(response => {
                    this.books = response.data;
                });
        },
        methods: {
            deleteBook(id) {
                this.axios
                    .delete(`http://localhost:8000/api/book/delete/${id}`)
                    .then(response => {
                        let i = this.books.map(item => item.id).indexOf(id); // find index of your object
                        this.books.splice(i, 1)
                    });
            }
        }
    }
</script>
AddBook.vue
<template>
    <div>
        <h3 class="text-center">Add Book</h3>
        <div class="row">
            <div class="col-md-6">
                <form @submit.prevent="addBook">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" class="form-control" v-model="book.name">
                    </div>
                    <div class="form-group">
                        <label>Author</label>
                        <input type="text" class="form-control" v-model="book.author">
                    </div>
                    <button type="submit" class="btn btn-primary">Add Book</button>
                </form>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                book: {}
            }
        },
        methods: {
            addBook() {

                this.axios
                    .post('http://localhost:8000/api/book/add', this.book)
                    .then(response => (
                        this.$router.push({name: 'home'})
                        // console.log(response.data)
                    ))
                    .catch(error => console.log(error))
                    .finally(() => this.loading = false)
            }
        }
    }
</script>
EditBook.vue
<template>
    <div>
        <h3 class="text-center">Edit Book</h3>
        <div class="row">
            <div class="col-md-6">
                <form @submit.prevent="updateBook">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" class="form-control" v-model="book.name">
                    </div>
                    <div class="form-group">
                        <label>Author</label>
                        <input type="text" class="form-control" v-model="book.author">
                    </div>
                    <button type="submit" class="btn btn-primary">Update Book</button>
                </form>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                book: {}
            }
        },
        created() {
            this.axios
                .get(`http://localhost:8000/api/book/edit/${this.$route.params.id}`)
                .then((response) => {
                    this.book = response.data;
                    // console.log(response.data);
                });
        },
        methods: {
            updateBook() {
                this.axios
                    .post(`http://localhost:8000/api/book/update/${this.$route.params.id}`, this.book)
                    .then((response) => {
                        this.$router.push({name: 'home'});
                    });
            }
        }
    }
</script>
In the three files, we have used Axios to call Laravel API.

Step 6 : Define Vue Routes

In the resources>js folder, create a file named routes.js and paste this code:
routes.js
import AllBooks from './components/AllBooks.vue';
import AddBook from './components/AddBook.vue';
import EditBook from './components/EditBook.vue';

export const routes = [
    {
        name: 'home',
        path: '/',
        component: AllBooks
    },
    {
        name: 'add',
        path: '/add',
        component: AddBook
    },
    {
        name: 'edit',
        path: '/edit/:id',
        component: EditBook
    }
];

Step 7 : Import All to app.js

We are about to finish. This is the last step. Open/create app.js from resources>js folder and paste this code:
app.js

require('./bootstrap');
window.Vue = require('vue');

import App from './App.vue';
import VueRouter from 'vue-router';
import VueAxios from 'vue-axios';
import axios from 'axios';
import {routes} from './routes';

Vue.use(VueRouter);
Vue.use(VueAxios, axios);

const router = new VueRouter({
    mode: 'history',
    routes: routes
});

const app = new Vue({
    el: '#app',
    router: router,
    render: h => h(App),
});




https://www.mynotepaper.com/laravel-vue-crud-single-page-application-tutorial