Laravel

Laravel

Laravel is an open-source PHP web framework, following the MVC pattern.
Michael Bryan

Michael Bryan

1686284019

Laravel & React.js CRUD App Tutorial | Build a Basic CRUD App with Laravel and React.js

In this tutorial , We'll learn how to build a basic CRUD app with Laravel 8 RESTful APIs and React.js. Handle HTTP requests using Axios in Reactjs. Laravel 8 CRUD API implementation in Reactjs CRUD App.

The application we are going to build is a simple game interface for trivia quizzes. It allows you to register the players, generate new questions from a free API and mark the answers of the players as either right or wrong.

Table of Contents

1. Install Laravel Project

2. Configure Database Details

3. Create Migration, Model, and Controller

4. Define Routes in api.php

5. Building React CRUD Application Frontend


1. Install Laravel Project

First, open Terminal and run the following command to create a fresh Laravel project:

composer create-project --prefer-dist laravel/laravel crud-react-laravel

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new crud-react-laravel

2. Configure Database Details:

After, Installation Go to the project root directory, open .env file, and set database detail as follow:

DB_CONNECTION=mysql 
DB_HOST=127.0.0.1 
DB_PORT=3306 
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>

3. Create Migration, Model, and Controller

Create a Product model, migration, and controller. Run the following command for that:

php artisan make:model Category -mcr

-mcr this argument will create Model, Migration, and Controller in Single Command.

Now, Open migration file of product from database/migration and replace code in up () function:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->text('description');
        $table->text('image');
        $table->timestamps();
    });
}

Migrate the database using the following command:

php artisan migrate

Now, Open Category.php model from app / Models  and update code into Product.php Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model {

   use HasFactory;

   protected $fillable = ['title', 'description', 'image'];
}

?>

Next, Open ProductController.php and add code in index, store, show, update, and delete functions as a following:

<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Product::select('id','title','description','image')->get();
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'title'=>'required',
            'description'=>'required',
            'image'=>'required|image'
        ]);

        try{
            $imageName = Str::random().'.'.$request->image->getClientOriginalExtension();
            Storage::disk('public')->putFileAs('product/image', $request->image,$imageName);
            Product::create($request->post()+['image'=>$imageName]);

            return response()->json([
                'message'=>'Product Created Successfully!!'
            ]);
        }catch(\Exception $e){
            \Log::error($e->getMessage());
            return response()->json([
                'message'=>'Something goes wrong while creating a product!!'
            ],500);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product)
    {
        return response()->json([
            'product'=>$product
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Product $product)
    {
        $request->validate([
            'title'=>'required',
            'description'=>'required',
            'image'=>'nullable'
        ]);

        try{

            $product->fill($request->post())->update();

            if($request->hasFile('image')){

                // remove old image
                if($product->image){
                    $exists = Storage::disk('public')->exists("product/image/{$product->image}");
                    if($exists){
                        Storage::disk('public')->delete("product/image/{$product->image}");
                    }
                }

                $imageName = Str::random().'.'.$request->image->getClientOriginalExtension();
                Storage::disk('public')->putFileAs('product/image', $request->image,$imageName);
                $product->image = $imageName;
                $product->save();
            }

            return response()->json([
                'message'=>'Product Updated Successfully!!'
            ]);

        }catch(\Exception $e){
            \Log::error($e->getMessage());
            return response()->json([
                'message'=>'Something goes wrong while updating a product!!'
            ],500);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        try {

            if($product->image){
                $exists = Storage::disk('public')->exists("product/image/{$product->image}");
                if($exists){
                    Storage::disk('public')->delete("product/image/{$product->image}");
                }
            }

            $product->delete();

            return response()->json([
                'message'=>'Product Deleted Successfully!!'
            ]);
            
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            return response()->json([
                'message'=>'Something goes wrong while deleting a product!!'
            ]);
        }
    }
}

4. Define Routes in api.php

Now define routes in the api.php routes file. Go to the routes folder and open the api.php file and update the following routes:

use App\Http\Controllers\ProductController;

Route::resource('products',ProductController::class);

Before starting the application you need to run this command to access all uploaded images ignore this command if you don't upload in a public disk.

php artisan storage:link

The public the disk is intended for files that are going to be publicly accessible. By default, the public disk uses the local driver and stores these files in storage/app/public. To make them accessible from the web, you should create a symbolic link from public/storage to storage/app/public.

Start the application by running php artisan serve and you’d see that your API is available for use with Postman or any other REST client you prefer.

Read Also: How to Install React in Laravel 8

5. Building React CRUD Application Frontend

Let’s get started with building out our frontend with React, one of the most popular JavaScript frontend libraries in use today.

In a separate folder, run the following commands to install create-react-app and create a react app called expenses-manager, cd into the folder, and then install Axios (an HTTP client for sending XMLHttpRequests), react-bootstrap and bootstrap as well as sweetalert2 for presenting us with lovely looking alert boxes.

npm install -g create-react-app 
create-react-app crud-react 
cd crud-react 
npm install axios react-bootstrap bootstrap 
npm install react-router-dom sweetalert2 --save

After the installation is completed, open up your src/app.js and import the following bootstrap core file to the top of the code:

import 'bootstrap/dist/css/bootstrap.css';

The next step is to create the components we need in our application, open up your src folder and create a new folder in it named components, in the components folder create another folder named product, create the following files in product folder:

  • create.component.js
  • edit.component.js
  • list.component.js

In the create.component.js file, add the following code:

import React, { useState } from "react";
import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button'
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import axios from 'axios'
import Swal from 'sweetalert2';
import { useNavigate } from 'react-router-dom'

export default function CreateProduct() {
  const navigate = useNavigate();

  const [title, setTitle] = useState("")
  const [description, setDescription] = useState("")
  const [image, setImage] = useState()
  const [validationError,setValidationError] = useState({})

  const changeHandler = (event) => {
		setImage(event.target.files[0]);
	};

  const createProduct = async (e) => {
    e.preventDefault();

    const formData = new FormData()

    formData.append('title', title)
    formData.append('description', description)
    formData.append('image', image)

    await axios.post(`http://localhost:8000/api/products`, formData).then(({data})=>{
      Swal.fire({
        icon:"success",
        text:data.message
      })
      navigate("/")
    }).catch(({response})=>{
      if(response.status===422){
        setValidationError(response.data.errors)
      }else{
        Swal.fire({
          text:response.data.message,
          icon:"error"
        })
      }
    })
  }

  return (
    <div className="container">
      <div className="row justify-content-center">
        <div className="col-12 col-sm-12 col-md-6">
          <div className="card">
            <div className="card-body">
              <h4 className="card-title">Create Product</h4>
              <hr />
              <div className="form-wrapper">
                {
                  Object.keys(validationError).length > 0 && (
                    <div className="row">
                      <div className="col-12">
                        <div className="alert alert-danger">
                          <ul className="mb-0">
                            {
                              Object.entries(validationError).map(([key, value])=>(
                                <li key={key}>{value}</li>   
                              ))
                            }
                          </ul>
                        </div>
                      </div>
                    </div>
                  )
                }
                <Form onSubmit={createProduct}>
                  <Row> 
                      <Col>
                        <Form.Group controlId="Name">
                            <Form.Label>Title</Form.Label>
                            <Form.Control type="text" value={title} onChange={(event)=>{
                              setTitle(event.target.value)
                            }}/>
                        </Form.Group>
                      </Col>  
                  </Row>
                  <Row className="my-3">
                      <Col>
                        <Form.Group controlId="Description">
                            <Form.Label>Description</Form.Label>
                            <Form.Control as="textarea" rows={3} value={description} onChange={(event)=>{
                              setDescription(event.target.value)
                            }}/>
                        </Form.Group>
                      </Col>
                  </Row>
                  <Row>
                    <Col>
                      <Form.Group controlId="Image" className="mb-3">
                        <Form.Label>Image</Form.Label>
                        <Form.Control type="file" onChange={changeHandler} />
                      </Form.Group>
                    </Col>
                  </Row>
                  <Button variant="primary" className="mt-2" size="lg" block="block" type="submit">
                    Save
                  </Button>
                </Form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

Also, go to the edit.component.js and add the following:

import React, { useEffect, useState } from "react";
import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import { useNavigate, useParams } from 'react-router-dom'
import axios from 'axios';
import Swal from 'sweetalert2';

export default function EditUser() {
  const navigate = useNavigate();

  const { id } = useParams()

  const [title, setTitle] = useState("")
  const [description, setDescription] = useState("")
  const [image, setImage] = useState(null)
  const [validationError,setValidationError] = useState({})

  useEffect(()=>{
    fetchProduct()
  },[])

  const fetchProduct = async () => {
    await axios.get(`http://localhost:8000/api/products/${id}`).then(({data})=>{
      const { title, description } = data.product
      setTitle(title)
      setDescription(description)
    }).catch(({response:{data}})=>{
      Swal.fire({
        text:data.message,
        icon:"error"
      })
    })
  }

  const changeHandler = (event) => {
		setImage(event.target.files[0]);
	};

  const updateProduct = async (e) => {
    e.preventDefault();

    const formData = new FormData()
    formData.append('_method', 'PATCH');
    formData.append('title', title)
    formData.append('description', description)
    if(image!==null){
      formData.append('image', image)
    }

    await axios.post(`http://localhost:8000/api/products/${id}`, formData).then(({data})=>{
      Swal.fire({
        icon:"success",
        text:data.message
      })
      navigate("/")
    }).catch(({response})=>{
      if(response.status===422){
        setValidationError(response.data.errors)
      }else{
        Swal.fire({
          text:response.data.message,
          icon:"error"
        })
      }
    })
  }

  return (
    <div className="container">
      <div className="row justify-content-center">
        <div className="col-12 col-sm-12 col-md-6">
          <div className="card">
            <div className="card-body">
              <h4 className="card-title">Update Product</h4>
              <hr />
              <div className="form-wrapper">
                {
                  Object.keys(validationError).length > 0 && (
                    <div className="row">
                      <div className="col-12">
                        <div className="alert alert-danger">
                          <ul className="mb-0">
                            {
                              Object.entries(validationError).map(([key, value])=>(
                                <li key={key}>{value}</li>   
                              ))
                            }
                          </ul>
                        </div>
                      </div>
                    </div>
                  )
                }
                <Form onSubmit={updateProduct}>
                  <Row> 
                      <Col>
                        <Form.Group controlId="Name">
                            <Form.Label>Title</Form.Label>
                            <Form.Control type="text" value={title} onChange={(event)=>{
                              setTitle(event.target.value)
                            }}/>
                        </Form.Group>
                      </Col>  
                  </Row>
                  <Row className="my-3">
                      <Col>
                        <Form.Group controlId="Description">
                            <Form.Label>Description</Form.Label>
                            <Form.Control as="textarea" rows={3} value={description} onChange={(event)=>{
                              setDescription(event.target.value)
                            }}/>
                        </Form.Group>
                      </Col>
                  </Row>
                  <Row>
                    <Col>
                      <Form.Group controlId="Image" className="mb-3">
                        <Form.Label>Image</Form.Label>
                        <Form.Control type="file" onChange={changeHandler} />
                      </Form.Group>
                    </Col>
                  </Row>
                  <Button variant="primary" className="mt-2" size="lg" block="block" type="submit">
                    Update
                  </Button>
                </Form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

Finally, go to the list.component.js file and add the following:

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import Button from 'react-bootstrap/Button'
import axios from 'axios';
import Swal from 'sweetalert2'

export default function List() {

    const [products, setProducts] = useState([])

    useEffect(()=>{
        fetchProducts() 
    },[])

    const fetchProducts = async () => {
        await axios.get(`http://localhost:8000/api/products`).then(({data})=>{
            setProducts(data)
        })
    }

    const deleteProduct = async (id) => {
        const isConfirm = await Swal.fire({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
          }).then((result) => {
            return result.isConfirmed
          });

          if(!isConfirm){
            return;
          }

          await axios.delete(`http://localhost:8000/api/products/${id}`).then(({data})=>{
            Swal.fire({
                icon:"success",
                text:data.message
            })
            fetchProducts()
          }).catch(({response:{data}})=>{
            Swal.fire({
                text:data.message,
                icon:"error"
            })
          })
    }

    return (
      <div className="container">
          <div className="row">
            <div className='col-12'>
                <Link className='btn btn-primary mb-2 float-end' to={"/product/create"}>
                    Create Product
                </Link>
            </div>
            <div className="col-12">
                <div className="card card-body">
                    <div className="table-responsive">
                        <table className="table table-bordered mb-0 text-center">
                            <thead>
                                <tr>
                                    <th>Title</th>
                                    <th>Description</th>
                                    <th>Image</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {
                                    products.length > 0 && (
                                        products.map((row, key)=>(
                                            <tr key={key}>
                                                <td>{row.title}</td>
                                                <td>{row.description}</td>
                                                <td>
                                                    <img width="50px" src={`http://localhost:8000/storage/product/image/${row.image}`} />
                                                </td>
                                                <td>
                                                    <Link to={`/product/edit/${row.id}`} className='btn btn-success me-2'>
                                                        Edit
                                                    </Link>
                                                    <Button variant="danger" onClick={()=>deleteProduct(row.id)}>
                                                        Delete
                                                    </Button>
                                                </td>
                                            </tr>
                                        ))
                                    )
                                }
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
          </div>
      </div>
    )
}

React Router is the standard routing library for React. React Router keeps your UI in sync with the URL. It has a simple API with powerful features like lazy code loading, dynamic route matching, and location transition handling built right in. Make the URL your first thought, not an after-thought.

Using React Router

Let’s add some routing to our app open up the app.js file in your src directory and modify it as follows:

import * as React from "react";
import Navbar from "react-bootstrap/Navbar";
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import "bootstrap/dist/css/bootstrap.css";

import { BrowserRouter as Router , Routes, Route, Link } from "react-router-dom";

import EditProduct from "./components/product/edit.component";
import ProductList from "./components/product/list.component";
import CreateProduct from "./components/product/create.component";

function App() {
  return (<Router>
    <Navbar bg="primary">
      <Container>
        <Link to={"/"} className="navbar-brand text-white">
          Basic Crud App
        </Link>
      </Container>
    </Navbar>

    <Container className="mt-5">
      <Row>
        <Col md={12}>
          <Routes>
            <Route path="/product/create" element={<CreateProduct />} />
            <Route path="/product/edit/:id" element={<EditProduct />} />
            <Route exact path='/' element={<ProductList />} />
          </Routes>
        </Col>
      </Row>
    </Container>
  </Router>);
}

export default App;

Finally, It's time to run our React Crud Application.

Run npm run start to preview your application.

Here’s what the finished app will look like:


 

Happy Coding !!!

#laravel #react #reactjs #javascript 

Laravel & React.js CRUD App Tutorial | Build a Basic CRUD App with Laravel and React.js
Meggie  Flatley

Meggie Flatley

1686283977

Find the Nearest EV Charging Station with Laravel and Vue.js App

EV Charge Map (ev-charge-map)

Tutorial series on how to build this

If you'd like a step by step guide on how to build this just CLICK THE IMAGE BELOW

GO TO JOHN WEEKS DEV TUTORIAL VIDEOS

Come and check out my YOUTUBE channel for lots more tutorials -> https://www.youtube.com/@johnweeksdev

LIKE, SUBSCRIBE, and SMASH THE NOTIFICATION BELL!!!

Demonstration Video

https://user-images.githubusercontent.com/108229029/179423135-feeb78d5-0991-4875-8dae-440afdc82d28.mp4

Frontend setup

Note

For this frontend to work you'll need the backend/api section -> https://github.com/John-Weeks-Dev/ev-charge-map-api

You'll need to install the Quasar CLI tool -> https://quasar.dev/start/pick-quasar-flavour

Clone the repository

git clone https://github.com/John-Weeks-Dev/ev-charge-map.git

Go to https://console.cloud.google.com/ and generate an API KEY.

You'll need to enable the Maps API, Places API, Directions API, and Distance Matrix API.

Now go to https://openchargemap.org and generate an API KEY.

Now add the new API KEYS in to quasar.config.js

Screenshot 2022-07-18 at 01 53 02

Now do

cd ev-charge-map

npm i

yarn quasar dev --watch

You should be good to go!

Application images/pages

Map Section

Screenshot 2022-07-18 at 01 20 30 Screenshot 2022-07-18 at 01 19 04 Screenshot 2022-07-18 at 01 19 18

Screenshot 2022-07-18 at 01 21 34 Screenshot 2022-07-18 at 01 21 44 Screenshot 2022-07-18 at 01 22 02 Screenshot 2022-07-18 at 01 22 21

Route/Journey Section

Screenshot 2022-07-18 at 01 24 27 Screenshot 2022-07-18 at 01 25 08 Screenshot 2022-07-18 at 01 25 52 Screenshot 2022-07-18 at 01 27 01

Auth Login / Registration Section

Screenshot 2022-07-18 at 01 27 37 Screenshot 2022-07-18 at 01 28 40 Screenshot 2022-07-18 at 01 29 08 Screenshot 2022-07-18 at 01 29 22

Account Section

Screenshot 2022-07-18 at 01 31 04 Screenshot 2022-07-18 at 01 30 50 Screenshot 2022-07-18 at 01 30 38

.gitignore

.DS_Store
.thumbs.db
node_modules

# Quasar core related directories
.quasar
/dist

# Cordova related directories and files
/src-cordova/node_modules
/src-cordova/platforms
/src-cordova/plugins
/src-cordova/www

# Capacitor related directories and files
/src-capacitor/www
/src-capacitor/node_modules

# BEX related directories and files
/src-bex/www
/src-bex/js/core

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln

.editorconfig

root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

.eslintignore

/dist
/src-bex/www
/src-capacitor
/src-cordova
/.quasar
/node_modules
.eslintrc.js
babel.config.js

.eslintrc.js

module.exports = {
  // https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy
  // This option interrupts the configuration hierarchy at this file
  // Remove this if you have an higher level ESLint config file (it usually happens into a monorepos)
  root: true,

  parserOptions: {
    parser: '@babel/eslint-parser',
    ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
    sourceType: 'module' // Allows for the use of imports
  },

  env: {
    browser: true,
    'vue/setup-compiler-macros': true
  },

  // Rules order is important, please avoid shuffling them
  extends: [
    // Base ESLint recommended rules
    // 'eslint:recommended',

    // Uncomment any of the lines below to choose desired strictness,
    // but leave only one uncommented!
    // See https://eslint.vuejs.org/rules/#available-rules
    'plugin:vue/vue3-essential', // Priority A: Essential (Error Prevention)
    // 'plugin:vue/vue3-strongly-recommended', // Priority B: Strongly Recommended (Improving Readability)
    // 'plugin:vue/vue3-recommended', // Priority C: Recommended (Minimizing Arbitrary Choices and Cognitive Overhead)

    'standard'
    
  ],

  plugins: [
    // https://eslint.vuejs.org/user-guide/#why-doesn-t-it-work-on-vue-files
    // required to lint *.vue files
    'vue',
    
  ],

  globals: {
    ga: 'readonly', // Google Analytics
    cordova: 'readonly',
    __statics: 'readonly',
    __QUASAR_SSR__: 'readonly',
    __QUASAR_SSR_SERVER__: 'readonly',
    __QUASAR_SSR_CLIENT__: 'readonly',
    __QUASAR_SSR_PWA__: 'readonly',
    process: 'readonly',
    Capacitor: 'readonly',
    chrome: 'readonly'
  },

  // add your custom rules here
  rules: {
    
    // allow async-await
    'generator-star-spacing': 'off',
    // allow paren-less arrow functions
    'arrow-parens': 'off',
    'one-var': 'off',
    'no-void': 'off',
    'multiline-ternary': 'off',

    'import/first': 'off',
    'import/named': 'error',
    'import/namespace': 'error',
    'import/default': 'error',
    'import/export': 'error',
    'import/extensions': 'off',
    'import/no-unresolved': 'off',
    'import/no-extraneous-dependencies': 'off',
    
    'prefer-promise-reject-errors': 'off',

    // allow debugger during development only
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
  }
}

Download details:

Author: myshine112
Source: https://github.com/myshine112/ev-charge-map

#vue #vuejs #laravel 

Find the Nearest EV Charging Station with Laravel and Vue.js App
Michael Bryan

Michael Bryan

1686211182

Install Bootstrap 5 in Laravel 9 With Vite

In this tutorial, learn how to easily install Bootstrap 5 in your Laravel 9 project using Vite. You'll get a step-by-step guide on how to set up Vite and integrate it with your Laravel project to leverage the power of Bootstrap 5 for your front-end development needs. Enhance your Laravel app with Bootstrap 5 today!

To install Bootstrap 5 in Laravel 9 with Vite we follow these steps.

  • Step 1: Install Laravel Project
  • Step 2: Install Laravel UI For Bootstrap 5
  • Step 3: Setup Auth Scaffolding with Bootstrap 5
  • Step 4: Install NPM Dependencies
  • Step 5: Import vite.config.js Bootstrap 5 Path
  • Step 6: Update bootstrap.js
  • Step 7: Import Bootstrap 5 SCSS in JS Folder
  • Step 8: Replace mix() with @vite Blade directive
  • Step 9: Running Vite Command to build Asset File
  • Step 10: Start the Local server

Step 1: Install Laravel Project

Installing a fresh new laravel application, so head over to the terminal, type the command, and create a new laravel app.

composer create-project --prefer-dist laravel/laravel:^9.0 laravel9-bootstrap5-vite

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new laravel9-bootstrap5-vite

Step 2: Install Laravel UI For Bootstrap 5

Next, you need to run the below command in your terminal

composer require laravel/ui

Step 3: Setup Auth Scaffolding with Bootstrap 5

php artisan ui bootstrap --auth

Step 4: Install NPM Dependencies

Run the following command to install frontend dependencies:

npm install

Step 5: Import vite.config.js Bootstrap 5 Path

First, you need to change vite.config.js and add the bootstrap 5 path & remove resources/css/app.css

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import path from 'path'

export default defineConfig({
    plugins: [
        laravel([
            'resources/js/app.js',
        ]),
    ],
    resolve: {
        alias: {
            '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'),
        }
    },
});

Step 6: Update bootstrap.js

We need to use import instead of require.

import loadash from 'lodash'
window._ = loadash


import * as Popper from '@popperjs/core'
window.Popper = Popper

import 'bootstrap'


/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

import axios from 'axios'
window.axios = axios

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo';

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     forceTLS: true
// });

Step 7: Import Bootstrap 5 SCSS in JS Folder

Now you need to import bootstrap 5 SCSS path in you resources/js/app.js or resources/js/bootstrap.js

resources/js/app.js

import './bootstrap';

import '../sass/app.scss'

Step 8: Replace mix() with @vite Blade directive

When using Vite, you will need to use the @vite Blade directive instead of the mix() helper. remove mix helper and add @vite directive.

<link rel="stylesheet" href="{{ mix('css/app.css') }}">
<script src="{{ mix('js/app.js') }}" defer></script>

use @vite directive

@vite(['resources/js/app.js'])

views/layouts/app.blade

<!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>

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

    @vite(['resources/js/app.js'])

</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>
</body>
</html>

Step 9: Running Vite Command to build Asset File

You need to npm run build command to create asset bootstrap 5.

npm run build

Step 10: Start the Local server

Now open a new terminal and execute the following command from your terminal to run the development server.

php artisan serve

and navigate to the following link http://localhost:8000/

Happy Coding !!!

#bootstrap #laravel #vite 

Install Bootstrap 5 in Laravel 9 With Vite
Dylan North

Dylan North

1686206794

How to Create a Laravel CRUD Web Application From Scratch

In this tutorial, we will be learning how to create a Laravel CRUD (Create, Read, Update, Delete) web application step by step from scratch. This laravel 9 crud operation step-by-step tutorial from scratch will implement a simple post crud operation app in laravel app with validation and image upload. Using this crud app, you can learn how to insert, read, update and delete data from the database in laravel 9 project.

To create a Laravel CRUD web application from scratch we follow these steps

  • Step 1 : Download Laravel 9 App
  • Step 2 : Setup Database with App
  • Step 3 : Create Company Model & Migration For CRUD App
  • Step 4 : Create Company Controller By Artisan Command
  • Step 5 : Create Routes
  • Step 6 : Create Blade Views File
  • Step 7 : Run Development Server

Step 1 : Download Laravel 9 App

First of all, download or install laravel 9 new setup. So, open the terminal and type the following command to install the new laravel 9 app into your machine:

composer create-project --prefer-dist laravel/laravel:^9.0 laravel-9-crud

Step 2 : Setup Database with App

Setup database with your downloaded/installed laravel app. So, you need to find the .env file and setup database details as follows:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

Step 3 : Create Company Model & Migration For CRUD App

Open again your command prompt. And run the following command on it. To create model and migration file for form:

php artisan make:model Company -m

After that, open company migration  file inside laravel-9-crud/database/migrations/ directory. And then update the function up() with the following code:

public function up()
{
    Schema::create('companies', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email');
        $table->string('address');
        $table->timestamps();
    });
}

app/Models/Company.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'email', 'address'];
}

Then, open again command prompt and run the following command to create tables in the database:

php artisan migrate

Step 4 : Create Company Controller By Artisan Command

Create a controller by using the following command on the command prompt to create a controller file:

php artisan make:controller CompanyController

After that, visit app/Http/controllers and open the CompanyController.php file. And update the following code into it:

<?php

namespace App\Http\Controllers;
use App\Models\Company;
use Illuminate\Http\Request;

class CompanyController extends Controller
{
    /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function index()
    {
        $companies = Company::orderBy('id','desc')->paginate(5);
        return view('companies.index', compact('companies'));
    }

    /**
    * Show the form for creating a new resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function create()
    {
        return view('companies.create');
    }

    /**
    * Store a newly created resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return \Illuminate\Http\Response
    */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',
            'address' => 'required',
        ]);
        
        Company::create($request->post());

        return redirect()->route('companies.index')->with('success','Company has been created successfully.');
    }

    /**
    * Display the specified resource.
    *
    * @param  \App\company  $company
    * @return \Illuminate\Http\Response
    */
    public function show(Company $company)
    {
        return view('companies.show',compact('company'));
    }

    /**
    * Show the form for editing the specified resource.
    *
    * @param  \App\Company  $company
    * @return \Illuminate\Http\Response
    */
    public function edit(Company $company)
    {
        return view('companies.edit',compact('company'));
    }

    /**
    * Update the specified resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \App\company  $company
    * @return \Illuminate\Http\Response
    */
    public function update(Request $request, Company $company)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',
            'address' => 'required',
        ]);
        
        $company->fill($request->post())->save();

        return redirect()->route('companies.index')->with('success','Company Has Been updated successfully');
    }

    /**
    * Remove the specified resource from storage.
    *
    * @param  \App\Company  $company
    * @return \Illuminate\Http\Response
    */
    public function destroy(Company $company)
    {
        $company->delete();
        return redirect()->route('companies.index')->with('success','Company has been deleted successfully');
    }
}

Step 5 : Create Routes

Then create routes for laravel crud app. So, open the web.php file from the routes directory of laravel CRUD app. And update the following routes into the web.php file:

use App\Http\Controllers\CompanyController;
 
Route::resource('companies', CompanyController::class);

Step 6 : Create Blade Views File

Create the directory and some blade view, see the following:

  • Make Directory Name Companies
  • index.blade.php
  • create.blade.php
  • edit.blade.php

Create directory name companies inside the resources/views directory.

Note that, create index.blade.php, create.blade.php, and edit.blade.php inside the companies directory. And update the following code into the following files:

index.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel 9 CRUD Tutorial Example</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
</head>
<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Laravel 9 CRUD Example Tutorial</h2>
                </div>
                <div class="pull-right mb-2">
                    <a class="btn btn-success" href="{{ route('companies.create') }}"> Create Company</a>
                </div>
            </div>
        </div>
        @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <p>{{ $message }}</p>
            </div>
        @endif
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>S.No</th>
                    <th>Company Name</th>
                    <th>Company Email</th>
                    <th>Company Address</th>
                    <th width="280px">Action</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($companies as $company)
                    <tr>
                        <td>{{ $company->id }}</td>
                        <td>{{ $company->name }}</td>
                        <td>{{ $company->email }}</td>
                        <td>{{ $company->address }}</td>
                        <td>
                            <form action="{{ route('companies.destroy',$company->id) }}" method="Post">
                                <a class="btn btn-primary" href="{{ route('companies.edit',$company->id) }}">Edit</a>
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="btn btn-danger">Delete</button>
                            </form>
                        </td>
                    </tr>
                    @endforeach
            </tbody>
        </table>
        {!! $companies->links() !!}
    </div>
</body>
</html>

create.blade.php:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Add Company Form - Laravel 9 CRUD</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left mb-2">
                    <h2>Add Company</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-primary" href="{{ route('companies.index') }}"> Back</a>
                </div>
            </div>
        </div>
        @if(session('status'))
        <div class="alert alert-success mb-1 mt-1">
            {{ session('status') }}
        </div>
        @endif
        <form action="{{ route('companies.store') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Name:</strong>
                        <input type="text" name="name" class="form-control" placeholder="Company Name">
                        @error('name')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Email:</strong>
                        <input type="email" name="email" class="form-control" placeholder="Company Email">
                        @error('email')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Address:</strong>
                        <input type="text" name="address" class="form-control" placeholder="Company Address">
                        @error('address')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <button type="submit" class="btn btn-primary ml-3">Submit</button>
            </div>
        </form>
    </div>
</body>

</html>

edit.blade.php:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Edit Company Form - Laravel 9 CRUD Tutorial</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-2">
        <div class="row">
            <div class="col-lg-12 margin-tb">
                <div class="pull-left">
                    <h2>Edit Company</h2>
                </div>
                <div class="pull-right">
                    <a class="btn btn-primary" href="{{ route('companies.index') }}" enctype="multipart/form-data">
                        Back</a>
                </div>
            </div>
        </div>
        @if(session('status'))
        <div class="alert alert-success mb-1 mt-1">
            {{ session('status') }}
        </div>
        @endif
        <form action="{{ route('companies.update',$company->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')
            <div class="row">
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Name:</strong>
                        <input type="text" name="name" value="{{ $company->name }}" class="form-control"
                            placeholder="Company name">
                        @error('name')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Email:</strong>
                        <input type="email" name="email" class="form-control" placeholder="Company Email"
                            value="{{ $company->email }}">
                        @error('email')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="col-xs-12 col-sm-12 col-md-12">
                    <div class="form-group">
                        <strong>Company Address:</strong>
                        <input type="text" name="address" value="{{ $company->address }}" class="form-control"
                            placeholder="Company Address">
                        @error('address')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <button type="submit" class="btn btn-primary ml-3">Submit</button>
            </div>
        </form>
    </div>
</body>

</html>

If you submit the add or edit form blank. So the error message will be displayed with the help of the code given below:

@error('name')
    <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
@enderror

Step 7 : Run Development Server

In the last step, open a command prompt and run the following command to start the development server:

php artisan serve

Then open your browser and hit the following URL on it:

http://127.0.0.1:8000/companies

Happy Coding!!!

#laravel #php 

How to Create a Laravel CRUD Web Application From Scratch
Kapil Khanal

Kapil Khanal

1686039811

APIs for Beginners - Full Course

APIs for Beginners - How to use an API (Full Course / Tutorial)

What is an API? Learn all about APIs (Application Programming Interfaces) in this full tutorial for beginners. You will learn what APIs do, why APIs exist, and the many benefits of APIs. APIs are used all the time in programming and web development so it is important to understand how to use them.

You will also get hands-on experience with a few popular web APIs. As long as you know the absolute basics of coding and the web, you'll have no problem following along.

This course has been updated from a previous version: https://morioh.com/p/422b616d71a2 

⭐️ Contents ⭐️
Unit 1 - What is an API
⌨️ Video 1 - Welcome (0:00:00)
⌨️ Video 2 - Defining Interface (0:04:50)
⌨️ Video 3 - Defining API (0:08:49)
⌨️ Video 4 - Remote APIs (0:13:59)
⌨️ Video 5 - How the web works (0:18:17)
⌨️ Video 6 - RESTful API Constraint Scavenger Hunt (0:23:21)

Unit 2 - Exploring APIs
⌨️ Video 1 - Exploring an API online (0:29:06)
⌨️ Video 2 - Using an API from the command line  (0:45:01)
⌨️ Video 3 - You go Curl (0:56:20)
⌨️ Video 4 - Using tools to explore APIs (1:14:21)
⌨️ Video 5 - More tools for your API exploring toolbox (1:36:20)
⌨️ Video 6 - Using Helper Libraries (1:48:34)

Unit 3 - All Together Now
⌨️ Video 1 - Introducing the Project (2:15:30)
⌨️ Video 2 - Serverless (2:23:30)
⌨️ Video 3 - Writing a Server Side API (2:37:08)
⌨️ Video 4 - Fetching Results on the Client from our Server (2:56:54)
⌨️ Video 5 - Wrap Up (3:05:29)

#api #javascript #python #php #laravel #react #vue #java #cplusplus #csharp #tailwindcss #nextjs #node #programming #developer #morioh #programmer #coding #softwaredeveloper #computerscience #webdev #webdeveloper #webdevelopment

APIs for Beginners - Full Course

A Beginner's Guide to Laravel APIs

In this tutorial, we will delve deeper into the world of Laravel APIs. We'll explore their capabilities, benefits, and how to leverage Laravel's features to build powerful and secure APIs. Laravel APIs are a great way to build web applications that are scalable, secure, and easy to use.

Introduction to Laravel APIs – Security, Features, and More

Laravel is the most popular PHP framework, with its elegant syntax, extensive feature set, and developer-friendly environment. And it's gained significant traction in recent years.

The Laravel ecosystem is constantly being updated with new features. Laravel 10 is exciting!

Among its many strengths is the robust support for APIs (Application Programming Interfaces). This enables seamless communication and integration between different software applications.

In this article, we will delve deeper into the world of Laravel APIs. We'll explore their capabilities, benefits, and how to leverage Laravel's features to build powerful and secure APIs.

What is an API?

To understand Laravel's API capabilities, you'll want to make sure you know what APIs are really all about and why they're so important.

APIs serve as a connector or a bridge that lets one application communicate with the other and exchange data with each other.

There are rules and protocols that govern how these applications interact. The API provider sets some rules and the Developer (API consumer) sets their own rules.

How Do APIs Work?

Paystack, for example, has what they call a Paystack gateway. It provides this as an API (that is, the interface to interact with. Remember the acronym for API?) that developers can integrate into their website.

When a user tries to make a purchase on the website, the website tells the gateway to handle the payment and the Paystack gateway process the payment. It then tells the site that the user has paid, and the site will allow the users to complete and receive their purchase.

Why are APIs Important?

The vital role APIs play is that they let developers leverage the functionalities of a different application without having to build those features themselves.

APIs also make it possible for two independent applications to interact and exchange data. You can think of it as two applications chatting 😀. Irrespective of the software system they operate on, APIs let them communicate.

The entire web today operates through various chains of communication. They power everything from social media login mechanisms to payment gateways, geolocation services, and much more.

APIs offer some advantages, such as:

  1. Modularity: APIs promote modularity by allowing applications to be built in separate components that can be developed, tested, and maintained independently.
  2. Reusability: APIs enable code and functionality to be reused, saving development time and effort.
  3. Scalability: APIs allow applications to scale by handling increased traffic and distributing tasks across multiple systems.
  4. Integration: APIs facilitate integration with external services, enabling developers to leverage the power of other applications and services.
  5. Flexibility: APIs provide the flexibility to adapt and evolve applications by adding new features and integrating them with emerging technologies.

Now that you hopefully understand the significance of APIs, let's explore how Laravel simplifies the process of building APIs with its elegant syntax and powerful features.

APIs in Laravel

Laravel has expressive syntax, powerful tools, and comprehensive support for building robust APIs.

It's routing system makes it easier for developers to expose their application's functionalities and data to other applications. You can enable interactions and still preserve security.

Laravel's powerful routing system lets developers easily define routes that are exclusive to APIS, permitting them to handle incoming requests and give proper responses with data.

These routes are configured to reply using request methods called HTTP methods that specify the action to be performed. These Methods (GET, POST, PUT, and DELETE) let developers create RESTful APIs that follow the principles of resource-based routing.

In order to handle these API requests, Laravel's controllers contain the logic for processing these requests. Controllers serve as intermediaries between the routes and the underlying application.

Controllers allow developers to organize and structure their API logic effectively. Laravel's controllers can fetch data from databases, perform business logic operations, and return responses in a specified format, such as JSON or XML.

Authentication and Security Concerns

Ensuring the security of your APIs is very important as it helps protect sensitive data and limit user access based on their level of authorization.

Laravel provides various systems for authentication through tokens or API keys. Authenticating API requests ensures that only authorized users utilize certain API endpoints and Laravel's robust mechanisms makes this easy.

Laravel's middleware adds another layer of security. It serves as a series of filters that intercept requests and responses. These interceptions are ways of performing various validations, checks, and transformations.

You can use middleware to enforce rate limiting, validate incoming data, or modify the response format.

Common API Features

Laravel simplifies the implementation of common API features, making it easier for developers to build robust and scalable APIs. Let's explore some of these features:

Rate Limiting

API rate limiting allows you to control the number of requests that can be made to your API within a specific time frame.

This helps you prevent abuse and ensure fair usage of your API resources. Laravel provides built-in rate limiting capabilities, enabling you to define rate limits based on IP addresses, authenticated users, or other criteria.

Caching

Caching is a technique that can significantly improve the performance of your API by storing the responses to frequently requested data.

Laravel offers powerful caching mechanisms that allow you to cache API responses, reducing the load on your server and enhancing the overall user experience.

With Laravel's caching capabilities, you can store the responses to API requests in memory or on disk.

API Versioning

API versioning is a crucial aspect of API development, as it allows you to manage changes to your API over time while ensuring backward compatibility for existing consumers.

Laravel offers tools and conventions for versioning your APIs, enabling you to introduce changes and enhancements without breaking the existing functionality for your API consumers.

By incorporating versioning into your API development workflow, you can effectively manage and control the evolution of your API, provide stability to existing consumers, and introduce new features or improvements in a controlled manner.

How to Extend Laravel's API Support

There are some third-party packages available within the Laravel ecosystem that allow you to extend and enhance Laravel's API capabilities.

These packages provide additional functionality, such as advanced authentication mechanisms, request validation, API documentation generation, and more.

One such popular package is Laravel Passport, which simplifies the implementation of OAuth2 authentication for your API.

OAuth2 is a heavily adopted authentication protocol that enables secure authorization and authentication between applications.

Laravel Passport seamlessly integrates with Laravel's authentication system, making it a breeze to add OAuth2 authentication to your API and integrate with external applications that rely on OAuth2.

Another notable package is DingoAPI, which provides a robust set of tools for building RESTful APIs in Laravel.

DingoAPI offers features like request and response transformation, API versioning, rate limiting, and error handling that complements Laravel's existing capabilities.

It provides additional flexibility and control over your API development process.

By leveraging these third-party packages, you can extend Laravel's API support according to your specific project requirements, saving development time and effort while benefiting from the expertise and contributions of the Laravel community.

Conclusion

Laravel's API support makes it an exceptional choice for developing robust and secure APIs in PHP.

You can leverage Laravel's powerful routing system, expressive controllers, and built-in authentication mechanisms to create APIs that seamlessly integrate with other applications and services.

Whether you are building a web application that requires integration with external services or developing a standalone API for others to consume.  

Laravel provides the necessary tools, conventions, and ecosystem support to create robust, secure, and highly functional APIs.

Embrace Laravel's API capabilities, and unlock the potential to build powerful and interconnected web applications.

Source: https://www.freecodecamp.org

#laravel #php 

A Beginner's Guide to Laravel APIs

Cómo enviar una notificación en Laravel

Se requieren notificaciones en casi todas las aplicaciones, especialmente en la categoría de comercio electrónico, redes sociales o cualquier producto digital destacado. En este tutorial, aprenderemos cómo enviar una notificación en Laravel. Para enviar una notificación en Laravel, realizamos los siguientes pasos.

Paso 1: Instalación de Laravel

Si no tiene una instalación de Laravel 8 en su local, simplemente ejecute el siguiente comando a continuación:

composer create-project --prefer-dist laravel/laravel laravel-email-notification

Paso 2: Configuración de la base de datos

Si su proyecto Laravel es nuevo, entonces necesita actualizar las credenciales de su base de datos. Simplemente abra el archivo .env en su proyecto Laravel 9.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here

Paso 3: Configuración de la migración

Aquí necesitamos generar primero la tabla de notificaciones antes de ejecutar las migraciones. Ejecute amablemente el siguiente comando:

php artisan notifications:table
php artisan migrate

Luego, una vez hecho esto, creemos una sembradora para nuestro usuario. Ejecute el siguiente comando:

php artisan make:seeder CreateUsersSeeder

Una vez que nuestra sembradora se genera amablemente en el directorio base de datos/sembradoras . Abra el CreateUsersSeeder.phpy verá el siguiente código:

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name' => 'Juan',
            'email' => 'email@gmail.com',
            'password' => bcrypt('password')
        ]);
    }
}

Luego ejecute el siguiente comando:

php artisan db:seed --class=CreateUsersSeeder

Paso 4: Hacer la notificación por correo electrónico de Laravel

Ahora, generemos nuestro ejemplo de notificación por correo electrónico de Laravel, lo nombraremos como EmailNotification. Ejecute el siguiente comando para hacer esto.

php artisan make:notification EmailNotification

Una vez hecho esto, navegue App/Notificationy ábralo EmailNotification.phpy luego edítelo. Vea el siguiente ejemplo:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class EmailNotification extends Notification
{
    use Queueable;

    /**
     * @var array $project
     */
    protected $project;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($project)
    {
        $this->project = $project;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail','database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting($this->project['greeting'])
                    ->line($this->project['body'])
                    ->action($this->project['actionText'], $this->project['actionURL'])
                    ->line($this->project['thanks']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'project_id' => $this-How to Send a Notification in Laravel with Example>project['id']
        ];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Paso 5: Configuración de rutas

En mi ejemplo, crearé manualmente mis rutas crudas. Simplemente abra el archivo "routes/web.php" y agregue las siguientes rutas.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::get('/send', '\App\Http\Controllers\HomeController@send')->name('home.send');

Paso 6: Configuración del controlador

En esta sección, agregaremos nuestra notificación de correo electrónico en nuestro HomeControllercomo configuramos en nuestras rutas. Vea a continuación el código completo de nuestro controlador:

<?php

namespace App\Http\Controllers;

use Notification;
use App\Models\User;
use Illuminate\Http\Request;
use App\Notifications\EmailNotification;

class HomeController extends Controller
{
    public function send() 
    {
    	$user = User::first();
  
        $project = [
            'greeting' => 'Hi '.$user->name.',',
            'body' => 'This is the project assigned to you.',
            'thanks' => 'Thank you this is from codeanddeploy.com',
            'actionText' => 'View Project',
            'actionURL' => url('/'),
            'id' => 57
        ];
  
        Notification::send($user, new EmailNotification($project));
   
        dd('Notification sent!');
    }
}

Ahora nuestro código está listo para enviar notificaciones a nuestros usuarios. Puede probarlo ahora ejecutando el comando de servicio:

php artisan serve

Luego ejecute la siguiente URL en su navegador para enviar una notificación por correo electrónico a su usuario.

http://127.0.0.1:8000/send

#laravel  #php  

Comment envoyer une notification dans Laravel

Les notifications sont requises dans presque toutes les applications, en particulier celles qui appartiennent à la catégorie du commerce électronique, des médias sociaux ou de tout produit numérique réputé. Dans ce didacticiel, nous allons apprendre à envoyer une notification dans Laravel. Pour envoyer une notification dans Laravel, nous procédons comme suit.

Étape 1 : Installation de Laravel

Si vous n'avez pas d'installation de Laravel 8 dans votre local, exécutez simplement la commande suivante ci-dessous :

composer create-project --prefer-dist laravel/laravel laravel-email-notification

Étape 2 : configuration de la base de données

Si votre projet Laravel est frais, vous devez mettre à jour les informations d'identification de votre base de données. Ouvrez simplement le fichier .env dans votre projet Laravel 9.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here

Étape 3 : Configuration de la migration

Ici, nous devons d'abord générer la table des notifications avant d'exécuter les migrations. Veuillez exécuter la commande suivante :

php artisan notifications:table
php artisan migrate

Ensuite, une fois cela fait, créons un seeder pour notre utilisateur. Exécutez la commande suivante :

php artisan make:seeder CreateUsersSeeder

Une fois que notre seeder est généré, rendez-vous dans le répertoire database/seeders . Ouvrez le CreateUsersSeeder.phpet vous verrez le code suivant :

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name' => 'Juan',
            'email' => 'email@gmail.com',
            'password' => bcrypt('password')
        ]);
    }
}

Exécutez ensuite la commande suivante :

php artisan db:seed --class=CreateUsersSeeder

Étape 4 : Création d'une notification par e-mail Laravel

Maintenant, générons notre exemple de notification par e-mail Laravel, nous l'appellerons EmailNotification. Exécutez la commande suivante pour ce faire.

php artisan make:notification EmailNotification

Une fois cela fait, naviguez dans App/Notifications et ouvrez-le EmailNotification.phppuis modifiez-le. Voir l'exemple ci-dessous :

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class EmailNotification extends Notification
{
    use Queueable;

    /**
     * @var array $project
     */
    protected $project;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($project)
    {
        $this->project = $project;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail','database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting($this->project['greeting'])
                    ->line($this->project['body'])
                    ->action($this->project['actionText'], $this->project['actionURL'])
                    ->line($this->project['thanks']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'project_id' => $this-How to Send a Notification in Laravel with Example>project['id']
        ];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Étape 5 : Configuration des itinéraires

Dans mon exemple, je vais créer manuellement mes crud routes. Ouvrez simplement le fichier "routes/web.php" et ajoutez les routes suivantes.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::get('/send', '\App\Http\Controllers\HomeController@send')->name('home.send');

Étape 6 : Configuration du contrôleur

Dans cette section, nous ajouterons notre notification par e-mail dans notre HomeControllercomme nous l'avons défini dans nos itinéraires. Voir ci-dessous le code complet de notre contrôleur :

<?php

namespace App\Http\Controllers;

use Notification;
use App\Models\User;
use Illuminate\Http\Request;
use App\Notifications\EmailNotification;

class HomeController extends Controller
{
    public function send() 
    {
    	$user = User::first();
  
        $project = [
            'greeting' => 'Hi '.$user->name.',',
            'body' => 'This is the project assigned to you.',
            'thanks' => 'Thank you this is from codeanddeploy.com',
            'actionText' => 'View Project',
            'actionURL' => url('/'),
            'id' => 57
        ];
  
        Notification::send($user, new EmailNotification($project));
   
        dd('Notification sent!');
    }
}

Notre code est maintenant prêt à envoyer des notifications à nos utilisateurs. Vous pouvez le tester maintenant en exécutant la commande serve :

php artisan serve

Exécutez ensuite l'URL ci-dessous dans votre navigateur pour envoyer une notification par e-mail à votre utilisateur.

http://127.0.0.1:8000/send

#laravel  #php  

中條 美冬

中條 美冬

1685907000

Laravelで通知を送信する方法

ほぼすべてのアプリケーション、特に電子商取引、ソーシャル メディア、または注目のデジタル製品のカテゴリに該当するアプリケーションでは、通知が必要です。このチュートリアルでは、Laravel で通知を送信する方法を学びます。Laravel で通知を送信するには、次の手順を実行します。

ステップ 1: Laravel のインストール

ローカルに Laravel 8 がインストールされていない場合は、以下のコマンドを実行してください。

composer create-project --prefer-dist laravel/laravel laravel-email-notification

ステップ 2: データベースの構成

Laravel プロジェクトが新しい場合は、データベースの認証情報を更新する必要があります。Laravel 9 プロジェクトで .env ファイルを開くだけです。

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here

ステップ 3: 移行のセットアップ

ここでは、移行を実行する前に、まず通知テーブルを生成する必要があります。次のコマンドを実行してください。

php artisan notifications:table
php artisan migrate

それが完了したら、ユーザー用のシーダーを作成しましょう。次のコマンドを実行します。

php artisan make:seeder CreateUsersSeeder

シーダーがデータベース/シーダーディレクトリに生成されると、を開くCreateUsersSeeder.phpと、次のコードが表示されます。

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name' => 'Juan',
            'email' => 'email@gmail.com',
            'password' => bcrypt('password')
        ]);
    }
}

次に、次のコマンドを実行します。

php artisan db:seed --class=CreateUsersSeeder

Laravelシーダーの詳細については、こちらをご覧ください。

ステップ4: Laravel電子メール通知を作成する

ここで、Laravel 電子メール通知の例を生成しましょう。これに という名前を付けますEmailNotification。これを行うには、次のコマンドを実行します。

php artisan make:notification EmailNotification

完了したら、App/Notificationに移動して開いEmailNotification.phpて編集します。以下の例を参照してください。

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class EmailNotification extends Notification
{
    use Queueable;

    /**
     * @var array $project
     */
    protected $project;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($project)
    {
        $this->project = $project;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail','database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting($this->project['greeting'])
                    ->line($this->project['body'])
                    ->action($this->project['actionText'], $this->project['actionURL'])
                    ->line($this->project['thanks']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'project_id' => $this-How to Send a Notification in Laravel with Example>project['id']
        ];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

ステップ 5: ルートの設定

この例では、手動で crud ルートを作成します。「routes/web.php」ファイルを開いて次のルートを追加するだけです。

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::get('/send', '\App\Http\Controllers\HomeController@send')->name('home.send');

ステップ 6: コントローラーのセットアップ

このセクションでは、ルートに設定したとおりに電子メール通知を追加しますHomeController。コントローラーの完全なコードを以下に示します。

<?php

namespace App\Http\Controllers;

use Notification;
use App\Models\User;
use Illuminate\Http\Request;
use App\Notifications\EmailNotification;

class HomeController extends Controller
{
    public function send() 
    {
    	$user = User::first();
  
        $project = [
            'greeting' => 'Hi '.$user->name.',',
            'body' => 'This is the project assigned to you.',
            'thanks' => 'Thank you this is from codeanddeploy.com',
            'actionText' => 'View Project',
            'actionURL' => url('/'),
            'id' => 57
        ];
  
        Notification::send($user, new EmailNotification($project));
   
        dd('Notification sent!');
    }
}

これで、コードがユーザーに通知を送信する準備が整いました。これで、serve コマンドを実行してテストできます。

php artisan serve

次に、ブラウザで以下の URL を実行して、ユーザーに電子メール通知を送信します。

http://127.0.0.1:8000/send

#laravel  #php  

Как отправить уведомление в Laravel

Уведомления требуются почти в каждом приложении, особенно в том, что относится к категории электронной коммерции, социальных сетей или любого известного цифрового продукта. В этом уроке мы узнаем, как отправить уведомление в Laravel. Чтобы отправить уведомление в Laravel, мы делаем следующие шаги.

Шаг 1: Установка Laravel

Если у вас нет установленной версии Laravel 8, просто выполните следующую команду:

composer create-project --prefer-dist laravel/laravel laravel-email-notification

Шаг 2: Настройка базы данных

Если ваш проект Laravel свежий, вам необходимо обновить учетные данные базы данных. Просто откройте файл .env в своем проекте Laravel 9.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here

Шаг 3: Настройка миграции

Здесь нам нужно сначала сгенерировать таблицу уведомлений перед запуском миграции. Пожалуйста, выполните следующую команду:

php artisan notifications:table
php artisan migrate

Затем, когда закончите, давайте создадим сидер для нашего пользователя. Выполните следующую команду:

php artisan make:seeder CreateUsersSeeder

Как только наш сидер сгенерирован, любезно поместите его в каталог database/seeders . Откройте файл CreateUsersSeeder.phpи вы увидите следующий код:

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name' => 'Juan',
            'email' => 'email@gmail.com',
            'password' => bcrypt('password')
        ]);
    }
}

Затем выполните следующую команду:

php artisan db:seed --class=CreateUsersSeeder

Шаг 4: Создание уведомления по электронной почте Laravel

Теперь давайте создадим наш пример уведомления по электронной почте Laravel, назовем его как EmailNotification. Для этого выполните следующую команду.

php artisan make:notification EmailNotification

После этого перейдите к App/Notifications и откройте, EmailNotification.phpа затем отредактируйте его. См. приведенный ниже пример:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class EmailNotification extends Notification
{
    use Queueable;

    /**
     * @var array $project
     */
    protected $project;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($project)
    {
        $this->project = $project;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail','database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting($this->project['greeting'])
                    ->line($this->project['body'])
                    ->action($this->project['actionText'], $this->project['actionURL'])
                    ->line($this->project['thanks']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'project_id' => $this-How to Send a Notification in Laravel with Example>project['id']
        ];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Шаг 5: Настройка маршрутов

В моем примере я создам вручную свои сырые маршруты. Просто откройте файл «routes/web.php» и добавьте следующие маршруты.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::get('/send', '\App\Http\Controllers\HomeController@send')->name('home.send');

Шаг 6: Настройка контроллера

В этом разделе мы добавим наше уведомление по электронной почте в наши HomeControllerмаршруты, которые мы установили. См. ниже полный код нашего контроллера:

<?php

namespace App\Http\Controllers;

use Notification;
use App\Models\User;
use Illuminate\Http\Request;
use App\Notifications\EmailNotification;

class HomeController extends Controller
{
    public function send() 
    {
    	$user = User::first();
  
        $project = [
            'greeting' => 'Hi '.$user->name.',',
            'body' => 'This is the project assigned to you.',
            'thanks' => 'Thank you this is from codeanddeploy.com',
            'actionText' => 'View Project',
            'actionURL' => url('/'),
            'id' => 57
        ];
  
        Notification::send($user, new EmailNotification($project));
   
        dd('Notification sent!');
    }
}

Теперь наш код готов к отправке уведомлений нашим пользователям. Вы можете проверить это сейчас, выполнив команду serve:

php artisan serve

Затем запустите приведенный ниже URL-адрес в своем браузере, чтобы отправить уведомление по электронной почте вашему пользователю.

http://127.0.0.1:8000/send

#laravel #php 

Como enviar uma notificação no Laravel

Benachrichtigungen sind in fast jeder Anwendung erforderlich, insbesondere in den Kategorien E-Commerce, soziale Medien oder bekannte digitale Produkte. In diesem Tutorial erfahren Sie, wie Sie eine Benachrichtigung in Laravel senden. Um eine Benachrichtigung in Laravel zu senden, führen wir die folgenden Schritte aus.

Schritt 1: Laravel-Installation

Wenn Sie lokal keine Laravel 8-Installation haben, führen Sie einfach den folgenden Befehl aus:

composer create-project --prefer-dist laravel/laravel laravel-email-notification

Schritt 2: Datenbankkonfiguration

Wenn Ihr Laravel-Projekt frisch ist, müssen Sie Ihre Datenbankanmeldeinformationen aktualisieren. Öffnen Sie einfach die .env-Datei in Ihrem Laravel 9-Projekt.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here

Schritt 3: Migrationseinrichtung

Hier müssen wir zuerst die Benachrichtigungstabelle generieren , bevor wir die Migrationen ausführen. Bitte führen Sie den folgenden Befehl aus:

php artisan notifications:table
php artisan migrate

Sobald wir fertig sind, erstellen wir einen Seeder für unseren Benutzer. Führen Sie den folgenden Befehl aus:

php artisan make:seeder CreateUsersSeeder

Sobald unser Seeder generiert ist, fügen Sie ihn bitte in das Verzeichnis „database/seeders“ ein . Öffnen Sie das CreateUsersSeeder.phpund Sie sehen den folgenden Code:

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name' => 'Juan',
            'email' => 'email@gmail.com',
            'password' => bcrypt('password')
        ]);
    }
}

Führen Sie dann den folgenden Befehl aus:

php artisan db:seed --class=CreateUsersSeeder

Erfahren Sie hier mehr über die Sämaschine Laravel.

Schritt 4: Erstellen einer Laravel-E-Mail-Benachrichtigung

Lassen Sie uns nun unser Laravel-E-Mail-Benachrichtigungsbeispiel generieren, das wir als benennen werden EmailNotification. Führen Sie dazu den folgenden Befehl aus.

php artisan make:notification EmailNotification

Wenn Sie fertig sind, navigieren Sie durch App/Notificationdie s, öffnen Sie sie EmailNotification.phpund bearbeiten Sie sie. Sehen Sie sich das folgende Beispiel an:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class EmailNotification extends Notification
{
    use Queueable;

    /**
     * @var array $project
     */
    protected $project;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($project)
    {
        $this->project = $project;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail','database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting($this->project['greeting'])
                    ->line($this->project['body'])
                    ->action($this->project['actionText'], $this->project['actionURL'])
                    ->line($this->project['thanks']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'project_id' => $this-How to Send a Notification in Laravel with Example>project['id']
        ];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Schritt 5: Routen einrichten

In meinem Beispiel werde ich meine groben Routen manuell erstellen. Öffnen Sie einfach die Datei „routes/web.php“ und fügen Sie die folgenden Routen hinzu.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::get('/send', '\App\Http\Controllers\HomeController@send')->name('home.send');

Schritt 6: Controller einrichten

In diesem Abschnitt fügen wir unsere E-Mail-Benachrichtigung in HomeControllerunsere Routen ein. Nachfolgend finden Sie den vollständigen Code unseres Controllers:

<?php

namespace App\Http\Controllers;

use Notification;
use App\Models\User;
use Illuminate\Http\Request;
use App\Notifications\EmailNotification;

class HomeController extends Controller
{
    public function send() 
    {
    	$user = User::first();
  
        $project = [
            'greeting' => 'Hi '.$user->name.',',
            'body' => 'This is the project assigned to you.',
            'thanks' => 'Thank you this is from codeanddeploy.com',
            'actionText' => 'View Project',
            'actionURL' => url('/'),
            'id' => 57
        ];
  
        Notification::send($user, new EmailNotification($project));
   
        dd('Notification sent!');
    }
}

Jetzt ist unser Code bereit, Benachrichtigungen an unsere Benutzer zu senden. Sie können es jetzt testen, indem Sie den Befehl „serve“ ausführen:

php artisan serve

Führen Sie dann die unten stehende URL in Ihrem Browser aus, um eine E-Mail-Benachrichtigung an Ihren Benutzer zu senden.

http://127.0.0.1:8000/send

#laravel #php 

Como enviar uma notificação no Laravel com exemplo

As notificações são necessárias em quase todos os aplicativos, especialmente os que se enquadram na categoria de comércio eletrônico, mídia social ou qualquer produto digital conhecido. Neste tutorial, aprenderemos como enviar uma notificação no Laravel , Para enviar uma notificação no Laravel fazemos os seguintes passos.

Passo 1: Instalação do Laravel

Se você não possui uma instalação do Laravel 8 em seu local, basta executar o seguinte comando abaixo:

composer create-project --prefer-dist laravel/laravel laravel-email-notification

Etapa 2: configuração do banco de dados

Se o seu projeto Laravel for novo, você precisará atualizar suas credenciais de banco de dados. Basta abrir o arquivo .env em seu projeto Laravel 9.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here

Etapa 3: configuração da migração

Aqui precisamos gerar primeiro a tabela de notificações antes de executar as migrações. Por favor, execute o seguinte comando:

php artisan notifications:table
php artisan migrate

Feito isso, vamos criar um seeder para nosso usuário. Execute o seguinte comando:

php artisan make:seeder CreateUsersSeeder

Uma vez que nosso seeder é gerado gentilmente para o diretório database/seeders . Abra o CreateUsersSeeder.phpe você verá o seguinte código:

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name' => 'Juan',
            'email' => 'email@gmail.com',
            'password' => bcrypt('password')
        ]);
    }
}

Em seguida, execute o seguinte comando:

php artisan db:seed --class=CreateUsersSeeder

Saiba mais sobre o seeder do Laravel aqui.

Etapa 4: Fazendo a notificação por e-mail do Laravel

Agora, vamos gerar nosso exemplo de notificação de e-mail do Laravel, vamos nomeá-lo como EmailNotification. Execute o seguinte comando para fazer isso.

php artisan make:notification EmailNotification

Uma vez feito, navegue App/Notificatione abra-o EmailNotification.phpe edite-o. Veja o exemplo abaixo:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class EmailNotification extends Notification
{
    use Queueable;

    /**
     * @var array $project
     */
    protected $project;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($project)
    {
        $this->project = $project;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail','database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting($this->project['greeting'])
                    ->line($this->project['body'])
                    ->action($this->project['actionText'], $this->project['actionURL'])
                    ->line($this->project['thanks']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'project_id' => $this-How to Send a Notification in Laravel with Example>project['id']
        ];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Passo 5: Configurando Rotas

No meu exemplo, vou criar manualmente minhas rotas crud. Basta abrir o arquivo "routes/web.php" e adicionar as seguintes rotas.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::get('/send', '\App\Http\Controllers\HomeController@send')->name('home.send');

Passo 6: Configurando o Controlador

Nesta seção, adicionaremos nossa notificação por e-mail HomeControllerconforme definimos em nossas rotas. Veja abaixo o código completo do nosso controller:

<?php

namespace App\Http\Controllers;

use Notification;
use App\Models\User;
use Illuminate\Http\Request;
use App\Notifications\EmailNotification;

class HomeController extends Controller
{
    public function send() 
    {
    	$user = User::first();
  
        $project = [
            'greeting' => 'Hi '.$user->name.',',
            'body' => 'This is the project assigned to you.',
            'thanks' => 'Thank you this is from codeanddeploy.com',
            'actionText' => 'View Project',
            'actionURL' => url('/'),
            'id' => 57
        ];
  
        Notification::send($user, new EmailNotification($project));
   
        dd('Notification sent!');
    }
}

Agora nosso código está pronto para enviar notificações aos nossos usuários. Você pode testá-lo agora executando o comando serve:

php artisan serve

Em seguida, execute o URL abaixo no seu navegador para enviar uma notificação por e-mail ao seu usuário.

http://127.0.0.1:8000/send

#laravel #php 

How to Send a Notification in Laravel with Example

Notifications are required in almost every application, especially which falls in the category of e-commerce, social media, or any noted digital product. In this tutorial, we will, learn how to send a notification in Laravel , To send notification in Laravel we do the following steps.

  • Step 1: Laravel Installation
  • Step 2: Database Configuration
  • Step 3: Migration Setup
  • Step 4: Making Laravel Email Notification
  • Step 5: Setting up Routes
  • Step 6: Setting Up Controller

Step 1: Laravel Installation

If you don't have a Laravel 8 install in your local just run the following command below:

composer create-project --prefer-dist laravel/laravel laravel-email-notification

Step 2: Database Configuration

If your Laravel project is fresh then you need to update your database credentials. Just open the .env file in your Laravel 9 project.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here

Step 3: Migration Setup

Here we need to generate first the notifications table before running the migrations. Kindly run the following command:

php artisan notifications:table
php artisan migrate

Then once done let's create a seeder for our user. Run the following command:

php artisan make:seeder CreateUsersSeeder

Once our seeder is generated kindly to the database/seeders directory. Open the CreateUsersSeeder.php and you will see the following code:

<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;

class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name' => 'Juan',
            'email' => 'email@gmail.com',
            'password' => bcrypt('password')
        ]);
    }
}

Then run the following command:

php artisan db:seed --class=CreateUsersSeeder

Learn more about Laravel seeder here.

Step 4: Making Laravel Email Notification

Now, let's generate our Laravel email notification example we will name this as EmailNotification. Run the following command to do this.

php artisan make:notification EmailNotification

Once done, navigate App/Notifications and open EmailNotification.php then edit it. See the below example:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class EmailNotification extends Notification
{
    use Queueable;

    /**
     * @var array $project
     */
    protected $project;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($project)
    {
        $this->project = $project;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail','database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->greeting($this->project['greeting'])
                    ->line($this->project['body'])
                    ->action($this->project['actionText'], $this->project['actionURL'])
                    ->line($this->project['thanks']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toDatabase($notifiable)
    {
        return [
            'project_id' => $this-How to Send a Notification in Laravel with Example>project['id']
        ];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Step 5: Setting up Routes

In my example, I will create manually my crud routes. Just open the "routes/web.php" file and add the following routes.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::get('/send', '\App\Http\Controllers\HomeController@send')->name('home.send');

Step 6: Setting Up Controller

In this section, we will add our email notification in our HomeController as we set in our routes. See below the complete code of our controller:

<?php

namespace App\Http\Controllers;

use Notification;
use App\Models\User;
use Illuminate\Http\Request;
use App\Notifications\EmailNotification;

class HomeController extends Controller
{
    public function send() 
    {
    	$user = User::first();
  
        $project = [
            'greeting' => 'Hi '.$user->name.',',
            'body' => 'This is the project assigned to you.',
            'thanks' => 'Thank you this is from codeanddeploy.com',
            'actionText' => 'View Project',
            'actionURL' => url('/'),
            'id' => 57
        ];
  
        Notification::send($user, new EmailNotification($project));
   
        dd('Notification sent!');
    }
}

Now our code is ready for sending notifications to our users. You can test it now by running the serve command:

php artisan serve

Then run the URL below to your browser to send an email notification to your user.

http://127.0.0.1:8000/send

#laravel #php 

How to Send a Notification in Laravel with Example
Elian  Harber

Elian Harber

1629213614

How to Validate Allowed Email Domains in Laravel

The Email Domain Rule package for Laravel can define a subset of allowed email domains you can use within a validator.

The post Validate Allowed Email Domains in Laravel appeared first on Laravel News.

Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

#laravel 

How to Validate Allowed Email Domains in Laravel
Elian  Harber

Elian Harber

1629205920

Find out Laravel 8.51 Released

The Laravel team released 8.51 with stack traces included in failed HTTP tests, and a new blade directive to render a CSS class string dynamically.

The post Laravel 8.51 Released appeared first on Laravel News.

Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

#laravel 

Find out Laravel 8.51 Released