CodeIgniter Laravel PHP Example HTML Javascript jQuery MORE Videos New

How to Laravel 8 Insert by form submit


Step 1 web.php

web.php

Route::get('/insert','StudInsertController@index')->name('student form');
Route::post('/create','StudInsertController@store')->name('student form create');

Step 2 StudInsertController.php

StudInsertController.php

<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\StudInsert;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class StudInsertController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('student.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = [
			'first_name' => 'required|string|min:3|max:255',
			'city_name' => 'required|string|min:3|max:255',
			'email' => 'required|string|email|max:255|unique:student_details'
		];
		$validator = Validator::make($request->all(),$rules);
		if ($validator->fails()) {
			return redirect('insert')
			->withInput()
			->withErrors($validator);
		}
		else{
            $data = $request->input();
			try{
				$student = new StudInsert;
                $student->first_name = $data['first_name'];
                $student->last_name = $data['last_name'];
				$student->city_name = $data['city_name'];
				$student->email = $data['email'];
				$student->save();
				return redirect('insert')->with('status',"Insert successfully");
			}
			catch(Exception $e){
				return redirect('insert')->with('failed',"operation failed");
			}
		}
    }
}

Step 3 StudInsert.php (model)

StudInsert.php

<?php

namespace App\Models;

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

class StudInsert extends Model
{
    protected $table = 'student_details';
	public $timestamps = true;
	protected $fillable = [
		'first_name', 'last_name','city_name', 'email',
	];
}

Step 4 layouts/app.blade.php(views): This is common file

app.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">

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

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

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

	<!-- Fonts -->
	<link rel="dns-prefetch" href="//fonts.gstatic.com">
	<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
	<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">

	<!-- Styles -->
	{{-- <link href="{{ asset('css/app.css') }}" rel="stylesheet"> --}}
	<link href="{{ asset('css/bootstrap/bootstrap.min.css') }}" rel="stylesheet">
	<link href="{{ asset('css/select2/select2.min.css') }}" rel="stylesheet">
	<link href="{{ asset('css/main.css')}}" rel="stylesheet">
	
	<script type="text/javascript" src="{{ asset('js/jquery/jquery.min.js') }}"></script>
	<script src="{{ asset('js/bootstrap/popper.min.js') }}"></script>
	<script src="{{ asset('js/bootstrap/bootstrap.min.js') }}"></script>
	<script src="{{ asset('js/select2/select2.min.js') }}"></script>
	<script src="{{ asset('js/common.js') }}"></script>
	<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
	<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
	
</head>
<body>
	<div id="app">
		<div class="main">
			@yield('content')
		</div>
	</div>		
</body>
</html>

student/add.blade.php (views)

@extends('layouts.app')

@section('content')
<div class="container">
	<h1 class="page-title">StudentsTutorial Add Form</h1>
	<div class="" style="margin-bottom:10px;margin-top:15px;">
	</div>
	<div class="row justify-content-center">
		<div class="col-md-12">
			<div class="card">
				
				<div class="card-header">Add</div>
				<div class="card-body">
					@if (session('status'))
						<div class="alert alert-success" role="alert">
							<button type="button" class="close" data-dismiss="alert">×</button>
							{{ session('status') }}
						</div>
					@elseif(session('failed'))
						<div class="alert alert-danger" role="alert">
							<button type="button" class="close" data-dismiss="alert">×</button>
							{{ session('failed') }}
						</div>
					@endif
					<form method="POST" action="{{ url('create') }}" class="needs-validation" novalidate>
						@csrf
						<div class="form-group">
							<label>First Name:</label>
							<input type="text" name="first_name" id="first_name" class=" form-control col-sm-6 @error('first_name') is-invalid @enderror" placeholder="First Name" value="{{ old('first_name') }}" required />
							@error('first_name')
								<div class="invalid-feedback">
									{{ $message }}
								</div>
							@enderror
						  
						</div>
						<div class="form-group">
							<label>Last Name:</label>
							<input type="text" name="last_name" id="last_name" class=" form-control col-sm-6 @error('last_name') is-invalid @enderror" placeholder="Last Name" value="{{ old('last_name') }}" required />
							@error('last_name')
								<div class="invalid-feedback">
									{{ $message }}
								</div>
							@enderror
						  
						</div>
						<div class="form-group">
							<label>Email:</label>
							<input type="email" name="email" id="email_id" class="form-control col-sm-6 @error('email') is-invalid @enderror" placeholder="Email Id" value="{{ old('email') }}" required / >
							@error('email')
								<div class="invalid-feedback">
									{{ $message }}
								</div>
							@enderror
						</div>
						<div class="form-group">
							<label>City:</label>
							<select name="city_name" id="city_name" class=" form-control col-sm-6 @error('city') is-invalid @enderror" required>
								<option value="delhi">Delhi</option>
								<option value="mumbai">Mumbai</option>
								<option value="kolkata">Kolkata</option>
								<option value="chennai">Chennai</option>
							</select>
						</div>
						<button type="submit" class="btn btn-primary">Save</button>
					  </form>				   
				</div>
			</div>
		</div>
	</div>
</div>
@endsection

Step 5 table schema

use php artisan make:migration create_student_details_table --create=student_details to create migration file and 
paste the below code inside up() method
Schema::create('student_details', function (Blueprint $table) {
	$table->id();
	$table->string('first_name');
	$table->string('last_name')->nullable();
	$table->string('city_name')->nullable();
	$table->string('email')->unique();
	$table->timestamps();
});

Now run the php artisan migrate command to create table in database.