Difficulty with belongsto Laravel 5.6

Asked

Viewed 1,430 times

0

Good night. I’m doing a project with Laravel and I’m having difficulty in the relationship Could you help me?

I have two entities in my bank that are Student and Situation.

Student has these attributes: id, name, serie, email. Situation has these attributes: id, situation_name.

The relationship is 1 to N. And the primary key of the table Situation goes to table Foreign student.

I’m doing this on Laravel 5.6 and in the student registration I’m not getting popular a select pulling his situation that would be these three: Enrolled, Scholarship, Delinquent.

I saw in Laravel’s doc that in this case it would be necessary to use the belongsto, but I didn’t quite understand. I’ll post the two models, the controller and the view.

--- STUDENT MODEL ---

<?php

namespace App\Models\Escola;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;


class Aluno extends Model
{
    protected $fillable = [
        'nome', 'serie', 'email', 

    ];     

    use SoftDeletes;

    protected $dates = ['deleted_at'];

}

--- SITUATION MODEL ---

<?php

namespace App\Models\Escola;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Situacao extends Model
{
     protected $fillable = [
        'nome_situacao'
    ];
    protected $table = 'situacoes';


    use SoftDeletes;

    protected $dates = ['deleted_at'];

}

-- THAT’S THE CONTROLLER

<?php

namespace App\Http\Controllers\Escola;

use Validator; 
use App\Models\Escola\Aluno;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class AlunoController extends Controller{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $alunos = Aluno::latest()->paginate(10);

        return view('escola.alunos.index',compact(
            'alunos', 'nome', 'serie', 'email'))
            ->with('i', (request()->input('page', 1 ) -1) * 5);
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */


    public function store(Request $request)
    {
        request()->validate([
            'nome' => 'required',
            'serie' => 'required',
            'email' => 'required',


        ]);

        Aluno::create($request->all());

        return redirect()->route('alunos.index')
                    ->with('success', 'Aluno cadastrado com sucesso!');

    } 

}

-- MY VIEW --

@extends('adminlte::page')

@section('title', 'Cadastro')

@section('content_header')
    <center>
    <br>
    <h3 style="margin-top: -30px;">Gerenciador de Alunos</h3>
    </center>
@stop

@section('content')
<br>
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-right">
            <!-- Button trigger modal -->
            <button type="button" class="btn btn-success" data-toggle="modal" data-target=" .bd-example-modal-lg">Incluir Aluno</button>
            </div>

            <!-- Modal -->
            <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
            <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
              <div class="modal-dialog modal-lg">
                <div class="modal-content">

                <form action="{{ route('alunos.store') }}" method="POST">
                    @csrf
                    <div class="container box box-success">
                <br>
                <div class="row">
                    <div class="col-md-4">
                        <strong>Nome do Novo Aluno:</strong>
                            <input type="text" name="nome" class="form-control" placeholder="Digite o nome..." required="ON">
                    </div>

                <div class="col-md-4">
                        <strong>Serie do Novo Aluno:</strong>
                            <input type="email" name="serie" 
      class="form-control" placeholder="Digite o nome..." required="ON">
                    </div>

                    <div class="col-md-4">
                        <strong>Email do Novo Aluno:</strong>
                            <input type="email" name="email" class="form-control" placeholder="Digite o email..." required="ON">
                    </div>

<div class="row">
                        <div class="col-md-4">
                            <strong>Selecione a Situação</strong>
                            <select name="situacao_id" class="form-control" required="ON">
                            <option value="">Clique aqui</option>

                            @foreach ($classsituacao_array as $situacoes_id)
                                <option value="{{$situacoes_id->id}}" > {{$situacoes_id->nome_situacao}}</option>
                            @endforeach 
                            </select>    

                        </div>
<div class="row">
                        <div class="col-md-4">
                        </div> 

                        <div class="col-md-4">
                        <center><button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button></center>
                        </div>

                        <div class="col-md-4">
                            <button type="submit" class="btn btn-sic btn-success btn-block btn-flat ">

                            Enviar</button>
                        </div>
                    </div>
                    <br>
                </form>
                </div>   
              </div>
            </div>
            </div> 
        </div>
    </div>
            <!--Mensagem de sucesso ao cadastrar-->

        @if ($message = Session::get('success'))

            <div class="alert alert-success">
                <p>{{ $message }}</p>
            </div>

       @endif

    <head>

        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">

        <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
        <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
        <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>

        <script type="text/javascript" class="init">

            $(document).ready(function() {
            $('#tobarril').DataTable({
                    "language": {
                    "lengthMenu": "Visualizando _MENU_  itens por página",
                    "zeroRecords": "Item não encontrado",
                    "info": "Visualizando página _PAGE_ de _PAGES_",
                    "infoEmpty": "Nenhum item a ser exibido",
                    "infoFiltered": "(Filtrado from _MAX_ total records)"
                        }
                    } 
                );
            } );
        </script>

    </head>

    <br>
    <div class="container box box-success">
    </div>
    <br>
        <table id="tobarril" class="table table-bordered"> 

        <thead>
        <tr>
            <th><center>Nome</center></th>
            <th><center>Serie</center></th>
            <th><center>Email</center></th>
            <th><center>Situacao</center></th>
            <th width="150px"><center>Ação</center></th>
        </tr>
        </thead>
        @foreach ($alunos as $aluno)
        <tbody>
        <tr>
            <td><center>{{ $aluno->id }}</center></td>
            <td><center>{{ $aluno->nome }}</center></td>
            <th><center>{{ $aluno->serie }}</center></th>
            <th><center>{{ $aluno->email }}</center></th>
            <th><center>{{ $aluno->situacao }}</center></th>



 <center>
                <form action="{{ route('alunos.destroy',$aluno->id) }}" method="POST">



                    <a class="btn btn-primary" href="{{ route('alunos.edit',$aluno->id) }}">Editar</a>


                    @csrf
                    @method('DELETE')


                    <button type="submit" class="btn btn-danger">Deletar</button>
                </form>
            </center>
            </td>
        </tr>
        </tbody>
        @endforeach
    </table>


   {!! $alunos->links() !!}



@endsection

What I am doing is returning the id of the situation in the view, but I wanted to inform the record of the situation (Enrolled, Scholarship, Delinquent). I managed to do this using Providers, but it is not the right way popular select, because if for example I take the stock situation out of the view it sum from select, when it should be in the bank. That is, that way he populates the select according to what I keep in the Situation Crud view.

Somebody give that strength?

  • The student may have more than one situation?

  • Yes, he may have: Enrolled, Scholarship, Delinquent.

1 answer

0

If the student can have several situations then "hasMany student (has many) situation", and "belongsTo(belongs to) student", remembering that it is necessary to perform the mapping of both sides so that it works in the expected way.

The following is an example of model relations (classes):

Pupil Class

public Function situation(){

Return $this->hasMany(Location::class);

}

Class Situation

public Function student(){

Return $this->belongsTo(Student::class);

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.