Laravel 8 Crud

file .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=proj_name

Model+table migration:

php artisan make:model Student -m

inserendo il flag -m realiziamo anche la migration dello stesso. si trova in Database/Migration

class CreateStudentsTable extends Migration {
    public function up() {
        Schema::create('students', function (Blueprint $table) {
            //$table->id();
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->string('phone');
            $table->text('detail');
            // $table->string('password');
            $table->timestamps();
        });
    }
    public function down() {
        Schema::dropIfExists('students');
    }
}
# applica il cambiamento
php artisan migrate

model App/Models/Student.php

class Student extends Model {
    use HasFactory;
    // consente di modificare questi campi
    protected $fillable = ['name', 'email', 'phone', 'password'];
    // $guarded all’opposto, consente di modificare tutti i campi tranne quella dichiarata
}

controller:

php artisan make:controller StudentController --resource
 
# dopo ogni creazione ricrea l'autoload
composer dump-autoload

aggiungendo il flag --resource generiamo automaticamente i metodi necessari

file: App/Http/Controller/StudentController.php:

use App\Student;
class StudentController extends Controller {
    public function index() {
        // or Students::where('votes', '>', 100)->paginate(15);
        $students = DB::table('students')
            ->paginate(15)
        // $page = (request()->input('page', 1) - 1) * 5
        return view('index', ['students'=>$students, 'page' => $page ]);
    }
    public function create() {
        return view('create');
    }
    public function store(Request $request) {
        $storeData = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|max:255',
            'phone' => 'required|numeric',
            'password' => 'required|max:255',
        ]);
        $student = Student::create($storeData);
        return redirect('/students')->with('completed', 'Student has been saved!');
    }
    public function show($id) {
        $student = Student::findOrFail($id);
        return view('show', ['student'=>$student]);
    }
    public function edit(int $id) {
        $student = Student::findOrFail($id);
        return view('edit', ['student'=>$student]);
    }
    public function update(Request $request, int $id) {
        $updateData = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|max:255',
            'phone' => 'required|numeric',
            'password' => 'required|max:255',
        ]);
        Student::whereId($id)->update($updateData);
        return redirect('/students')->with('completed', 'Student has been updated');
    }
    public function destroy(int $id) {
        $student = Student::findOrFail($id);
        $student->delete();
 
        return redirect('/students')->with('completed', 'Student has been deleted');
    }
}

route: Routes/web.php

Route::resource('students', 'App\Http\Controllers\StudentController');
php artisan route:list 

in Resource/Views: layout.blade

    <!DOCTYPE html>
    <html>
       <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
          <title>your app</title>
          <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
       </head>
       <body>
          <div class="container">
             @yield('content')
          </div>
 
          <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
          <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
          <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" type="text/js"></script>
       </body>
    </html>

resource/views/create.blade.php

@extends('layout')
@section('content')
<style>
    .container { max-width: 450px; }
    .push-top { margin-top: 50px; }
</style>
<div class="card push-top">
  <div class="card-header">
    Add User
  </div>
 
  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('students.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Name</label>
              <input type="text" class="form-control" name="name"/>
          </div>
          <div class="form-group">
              <label for="email">Email</label>
              <input type="email" class="form-control" name="email"/>
          </div>
          <div class="form-group">
              <label for="phone">Phone</label>
              <input type="tel" class="form-control" name="phone"/>
          </div>
          <div class="form-group">
              <label for="password">Password</label>
              <input type="text" class="form-control" name="password"/>
          </div>
          <button type="submit" class="btn btn-block btn-danger">Create User</button>
      </form>
  </div>
</div>
@endsection

resource/views/index

 
@extends('layout')
@section('content')
<div class="pull-right">
<a class="btn btn-success" href="{{ route('students.create') }}"> Create New Student</a>
</div>
    <style>
        .push-top { margin-top: 50px; }
    </style>
    <div class="push-top">
        @if(session()->get('success'))
            <div class="alert alert-success">
                {{ session()->get('success') }}
            </div><br />
        @endif
 
        @if($errors->any())
            {!! implode('', $errors->all('<div style="color:red">:message</div>')) !!}
        @endif
 
        <table class="table">
            <thead>
            <tr class="table-warning">
                <td>ID</td>
                <td>Name</td>
                <td>Email</td>
                <td>Phone</td>
                <td>Password</td>
                <td class="text-center">Action</td>
            </tr>
            </thead>
            <tbody>
            @foreach($students as $student )
                <tr>
                    <td>{{$student ->id}}</td>
                    <td>{{$student ->name}}</td>
                    <td>{{$student ->email}}</td>
                    <td>{{$student ->phone}}</td>
                    <td>{{$student ->password}}</td>
                    <td class="text-center">
                        <a href="{{ route('students.edit', $student->id)}}" class="btn btn-primary btn-sm"">Edit</a>
                        <form action="{{ route('students.destroy', $student->id)}}" method="post" style="display: inline-block">
                            @csrf
                            @method('DELETE')
                            <button class="btn btn-danger btn-sm"" type="submit">Delete</button>
                        </form>
                        <a class="btn btn-info" href="{{ route('students.show',$student->id) }}">Show</a>
                        <a class="btn btn-primary" href="{{ route('students.edit',$student->id) }}">Edit</a>
                    </td>
                </tr>
            @endforeach
            </tbody>
        </table>
 
        <!-- pagination links styled in tailwind, it's possible to customize the boot conf to use bootstrap -->
        {{ $students->links() }}
 
        </div>
@endsection

resource/views/edit.blade.php

@extends('layout')
 
@section('content')
 
<style>
    .container {
      max-width: 450px;
    }
    .push-top {
      margin-top: 50px;
    }
</style>
 
<div class="card push-top">
  <div class="card-header">
    Edit & Update
  </div>
 
  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('students.update', $student->id) }}">
          <div class="form-group">
              @csrf
              @method('PATCH')
              <label for="name">Name</label>
              <input type="text" class="form-control" name="name" value="{{ $student->name }}"/>
          </div>
          <div class="form-group">
              <label for="email">Email</label>
              <input type="email" class="form-control" name="email" value="{{ $student->email }}"/>
          </div>
          <div class="form-group">
              <label for="phone">Phone</label>
              <input type="tel" class="form-control" name="phone" value="{{ $student->phone }}"/>
          </div>
          <div class="form-group">
              <label for="password">Password</label>
              <input type="text" class="form-control" name="password" value="{{ $student->password }}"/>
          </div>
          <button type="submit" class="btn btn-block btn-danger">Update User</button>
      </form>
  </div>
</div>
@endsection

file show.blade.php

@extends('students.layout')
@section('content')
    <div class="row">
    <div class="col-lg-12 margin-tb">
    <div class="pull-left">
    <h2> Show xxx</h2>
    </div>
    <div class="pull-right">
    <a class="btn btn-primary" href="{{ route('students.index') }}"> Back</a>
    </div>
    </div>
    </div>
    <div class="row">
    <div class="col-xs-12 col-sm-12 col-md-12">
    <div class="form-group">
        <strong>Name:</strong>
        {{ $student->name }}
    </div>
    </div>
    <div class="col-xs-12 col-sm-12 col-md-12">
    <div class="form-group">
        <strong>Details:</strong>
        {{ $student->detail }}
    </div>
    </div>
    </div>
@endsection

per creare automaticamente dati di test

php artisan make:factory StudentFactory --model=Student

file database\factories\StudentFactory.php

namespace Database\Factories;
use App\Models\Student;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class StudentFactory extends Factory {
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Student::class;
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition() {
        return [
            'name' => $this->faker->name,
            'slug' => Str::slug($this->faker->name),
            'detail' => $this->faker->text,
        ];
    }
}
php artisan tinker
Student::factory()->count(500)->create()

Tags:
PHP Laravel

Blog Disclaimer:

Le opinioni espresse nel mio blog sono solo questo: mie opinioni.

In nessun modo rappresento le opinioni dei miei clienti in questa sede.


Notice: Undefined variable: browserName in /var/www/taziomirandola.it/lib/Visitors.php on line 86

Notice: Undefined variable: browserName in /var/www/taziomirandola.it/lib/Visitors.php on line 96

Deprecated: strripos(): Non-string needles will be interpreted as strings in the future. Use an explicit chr() call to preserve the current behavior in /var/www/taziomirandola.it/lib/Visitors.php on line 96

Notice: Undefined index: HTTP_ACCEPT_LANGUAGE in /var/www/taziomirandola.it/lib/Visitors.php on line 39

Fatal error: Uncaught TypeError: Argument 1 passed to safe_text() must be of the type string, null given, called in /var/www/taziomirandola.it/lib/Visitors.php on line 39 and defined in /var/www/taziomirandola.it/lib/Visitors.php:162 Stack trace: #0 /var/www/taziomirandola.it/lib/Visitors.php(39): safe_text() #1 /var/www/taziomirandola.it/lib/Visitors.php(124): Visitors::getData() #2 [internal function]: Visitors::log() #3 {main} thrown in /var/www/taziomirandola.it/lib/Visitors.php on line 162