Laravel with VueJS 500 (Internal Server Error) - laravel

I have the issue when I fetch states with VueJs.
getStates(){
axios.get("/api/employees/"+ this.form.country_id + "/states")
.then(res => {
this.states = res.data
}).catch(error => {
console.error(error.response.data)
})
}
This api.php .
<?php
use App\Http\Controllers\Api\EmployeeDataController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::get('/employees/countries', [EmployeeDataController::class, 'countries']);
Route::get('/employees/{country}/states', [EmployeeDataController::class, 'states']);
Route::get('/employees/departments', [EmployeeDataController::class, 'departments']);
Route::get('/employees/{state}/cities', [EmployeeDataController::class, 'cities']);
This is EmployeeDataController contains:
public function states(Country $country)
{
return response()->json($country->states);
}
This is country model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
use HasFactory;
protected $fillable = ['country_code', 'name'];
public function states()
{
return $this->hasMany(States::class);
}
}
This is create.vue blade which I store datas.
<div class="row mb-3">
<label for="country" class="col-md-4 col-form-label text-md-end">Country</label>
<div class="col-md-6">
<select v-model="form.country_id" #change="getStates()" name="country" class="form-control" aria-label="Default select example">
<option v-for="country in countries" :key="country.id" :value="country.id">{{country.name}}</option>
</select>
</div>
</div>
This create form that when I tapped select country, automatically state must fill with state data which I want to fetch.
But I have face to 500 internal server error
I hope to explain my issue.

Related

Undefined Variable $Member when trying to save data in my database phpmyadmin

This is the controller code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Member;
class membercontroller extends Controller {
function addmemb(Request $req) {
$member = new $Member;
$member->name = $req->name;
$member->age = $req->age;
$member->email = $req->email;
$member->save();
}
}
View Code:
<h1>Enter The Member Info </h1>
<form action= "addmembers" method="POST">
#Csrf
<input type="text" name="name" placeholder="Enter Your Name."> <br><br>
<input type="text" name="age" placeholder="Enter Your Age."> <br><br>
<input type="text" name="email" placeholder="Enter Your Email."> <br><br>
<button type="submit">Add Member</button> <br><br>
</form>
Route::view('addmembers', 'addmembers');
Route::post('addmembers', [membercontroller::class, 'addmemb']);
These are the Routes for the view and functions. Can anyone point out my mistake? It's saying Undefined Variable.
Whenever I try to save data in my database it shows an error which says $Member is undefined. Please point out what should I do to make this run?
$Member is not a Variable! its a model so you have to use it like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Member;
class membercontroller extends Controller
{
function addmemb(Request $req){
$member = new Member; ////////
$member->name = $req->name;
$member->age = $req->age;
$member->email = $req->email;
$member->save();
}
}

Laravel Import Excel into DB: ErrorException Undefined array key "name"

I am trying to use the Maatwebsite\Excel package to let users import a csv or excel file and it get imported into the DB.
I am new to laravel, so I am not quite sure how to troubleshoot this issue.
I keep getting the error:
ErrorException Undefined array key "FIRST"
http://127.0.0.1:8000/import-form
CSV Sample Data
FIRST,LAST,EMAIL,PHONE,DEPARTMENT,LOCATION
test name 1,teast last 1,test#mail.com,123-123-1231,test department,test location
Routes:
Route::post('/import-form', [ImportPatientController::class, 'importForm'])->name('import.file');
ImportPatientController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\ImportPatientModel;
use Excel;
use App\Imports\PatientImport;
use App\Http\Controllers\Controller;
class ImportPatientController extends Controller
{
public function importUploadForm()
{
return view('import-form');
}
public function importForm(Request $request)
{
Excel::import(new PatientImport,$request->file2);
return "Record are imported successfully!";
}
}
PatientImport.php (Imports Folder)
<?php
namespace App\Imports;
use App\Models\ImportPatientModel;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class PatientImport implements ToModel, WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new ImportPatientModel([
'firstName'=>$row['FIRST'],
'lastName' => $row['LAST'],
'email' => $row['EMAIL'],
'phone' => $row['PHONE'],
'department' => $row['DEPARTMENT'],
'location' => $row['LOCATION'],
]);
}
}
ImportPatientModel.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class ImportPatientModel extends Model
{
use HasFactory;
protected $table = "imported_patients";
protected $fillable = ['firstName', 'lastName', 'email', 'phone', 'department', 'location'];
}
import-form.blade.php
<form action="" method="post" enctype="multipart/form-data" action="{{route('import.file')}}">
<img class="flowhealthlogoform" src="{{ url('images/flowhealthlogo.png')}}" />
<h1> BACKUP LIS </h1>
<!-- CROSS Site Request Forgery Protection -->
#csrf
<div class="form-group">
<label>Upload Excel Sheet</label>
<input type="file" class="form-control {{ $errors->has('file') ? 'error' : '' }}" name="file2" id="file">
<!-- Error -->
#if ($errors->has('file'))
<div class="error">
{{ $errors->first('file') }}
</div>
#endif
</div>
<input type="submit" name="send" value="Submit" class="btn btn-dark btn-block">
</form>```
Array keys in PHP are case sensitive.
I think if you change $row['FIRST'] to $row['first'] the issue will be solved!

How to fetch field "nama" from Category Table in Product Table (Laravel 8)

I really need a solution for this problem. I'm using Laravel 8.
I am trying to fetch nama (name) field from the kategoris (category) table and show it in the produks (product) table.
View Blade with JS code in the end
#extends('back.index')
#section('content')
<main>
<div class="container-fluid">
<h1 class="mt-4">Produk</h1>
<ol class="breadcrumb mb-4">
<li class="breadcrumb-item"><a href={{ route('home') }}>Dashboard</a></li>
<li class="breadcrumb-item active">Produk</li>
</ol>
<div class="card mb-4">
<div class="card-body">
DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the
<a target="_blank" href="https://datatables.net/">official DataTables documentation</a>
.
</div>
</div>
<div class="card mb-4">
<div class="card-header">
<i class="fas fa-table mr-1"></i>
DataTable Example
#auth
Tambah Produk
#endauth
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="produks-table" width="100%" cellspacing="0">
<thead>
<tr>
<th>Kode</th>
<th>Nama</th>
<th>Kategori</th>
<th>Updated At</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Kode</th>
<th>Nama</th>
<th>Kategori</th>
<th>Updated At</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</main>
#endsection
#push('scripts')
<script>
$(function() {
$('#produks-table').DataTable({
processing: true,
serverSide: true,
ajax: 'produk/json',
columns: [
{ data: 'kode', name: 'kode' },
{ data: 'nama', name: 'nama',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='/kategoris/"+oData.id+"'>"+oData.nama+"</a>");
}
},
{ data: 'kategori', name: 'kategori.nama'},
{ data: 'updated_at', name: 'updated_at'},
]
});
});
</script>
#endpush
I already look for solutions for several days, but I still get this error message.
Product Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Produk extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Produk()
{
return $this->belongsTo(Kategori::class, 'kategori_id');
}
}
Category Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Kategori extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Kategori()
{
return $this->hasMany(Produk::class);
}
}
Product Controller
namespace App\Http\Controllers;
use App\Models\Produk;
use Illuminate\Http\Request;
use RealRashid\SweetAlert\Facades\Alert;
use Yajra\Datatables\DataTables;
class ProdukController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function json()
{
return Datatables::of(Produk::with('Kategori')->get())->make(true);
}
public function index()
{
return view('back.produk.show');
}
}
I was wrong while naming model functions.
Category Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Kategori extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Produk() //Here
{
return $this->hasMany(Produk::class);
}
}
Product Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Produk extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Kategori() //Here
{
return $this->belongsTo(Kategori::class, 'kategori_id');
}
}

Get objects of related tables from a collection laravel

I want to pass the result of a searching action but I am facing a problem because it is returning an array and from that all the relationships of the table are not working
result view. For this I can only access the data on my table not the related data through relationships
#extends('layouts.app')
#section('content')
#foreach ($result as $object)
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>Details for the animal</h3>
</div>
<div class="card-body">
<div class="col-12">
<p><strong>Id: </strong>{{ $object->id }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
#endsection
Here is my controller
<?php
namespace App\Http\Controllers;
use App\Animal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class SearchController extends Controller
{
public function index()
{
Animal::all();
return view('search.index');
}
public function postSearch(Request $request)
{
$serial_number = $request->input('search');
$this->getResult($serial_number);
return redirect()->route('result',$serial_number);
}
public function getResult($serial_number){
$result = DB::table('slaughters')->where(function ($query) use ($serial_number) {
$query->where('id','LIKE',"%$serial_number%");
})->latest()->get();
return view('search.result', ['result'=>$result]);
}
}
And my routes
Route::get('/search','SearchController#index')->name('search');
Route::post('/get','SearchController#postSearch');
Route::get('/search/{result}','SearchController#getResult')->name('result');
I would like to access data from the table related to this one too. What am to do
Slaughter model
class Slaughter extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}
public function animal(){
return $this->belongsTo(Animal::class);
}
You must create model Slaughter and define relations.
And then you can get result:
public function getResult($serial_number)
{
$result = Slaughter::with(['name_of_relation_1', 'name_of_relation_2'])->latest()->get();
return view('search.result', ['result'=>$result]);
}
In your Controller:
use App\Slaughter;
public function getResult($serial_number) {
$result = Slaughter::where('id', 'like', "%{$serial_number}%")
->with('user', 'animal')
->latest()
->get();
return view('search.result', compact('result'));
}
In your view you can then access the relationships like so:
{{ $object->user }}
{{ $object->animal }}

Laravel | Save and display two relations

I'm close to finish my CMS but I have one minor problem.
I can create several teams, works perfectly fine.
I can create several games, works also perfectly fine.
Now I want to create matches between those teams, which means I have two pivot tables.
One called game_match and the other called match_team.
game_match consist of game_idand match_id
match_teamconsist of match_id, team1_idand team2_id
My match/create.blade.php has two dropdown fields for each team.
Saving a single relation to the database works fine for me as I've done this a couple of times, but I can't figure out how to save two relations.
This is what I got so far:
Inside match/create.blade.php
<div class="field m-t-20 is-inline-block">
<p class="control">
<label for="home" class="label"><b>{{ trans_choice('messages.home', 1) }}</b></label>
<input type="hidden" name="home" id="home" :value="homeSelected">
<div class="select">
<select v-model="homeSelected">
#foreach($teams as $team)
<option value="{{ $team->id }}">{{ $team->name }}</option>
#endforeach
</select>
</div>
</p>
</div>
<div class="field m-t-20 is-inline-block">
<p class="control">
<label for="opponent" class="label"><b>{{ trans_choice('messages.opponent', 1) }}</b></label>
<input type="hidden" name="opponent" id="opponent" :value="opponentSelected">
<div class="select">
<select v-model="opponentSelected">
#foreach($teams as $team)
<option value="{{ $team->id }}">{{ $team->name }}</option>
#endforeach
</select>
</div>
</p>
</div>
#section('scripts')
<script>
var app = new Vue({
el: '#app',
data: {
homeSelected: "",
opponentSelected: "",
gameSelected: ""
}
});
</script>
#endsection
MatchController.php
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|max:255',
'matchday' => 'required',
]);
$match = new Match();
$match->title = $request->title;
$match->matchday = $request->matchday;
if ($match->save()) {
$match->games()->sync($request->game);
$match->teams()->sync( [
['team1_id' => $request->home, 'team2_id' => $request->opponent],
]);
Session::flash('success', trans('messages.created', ['item' => $match->title]));
return redirect()->route('matches.show', $match->id);
} else {
Session::flash('error', trans('messages.error'));
return redirect()->route('matches.create')->withInput();
}
}
match.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Match extends Model
{
use SoftDeletes; // <-- Use This Instead Of SoftDeletingTrait
protected $fillable = [
'title'
];
protected $dates = ['deleted_at'];
public function setHomeTeam () {}
public function teams () {
return $this->belongsToMany('App\Team', 'match_team', 'match_id', 'team1_id');
}
public function games () {
return $this->belongsToMany('App\Game', 'game_match');
}
public function getHomeTeam() {
return $this->belongsToMany('App\Team', 'match_team', 'match_id', 'team1_id');
}
public function getOpponentTeam() {
return $this->belongsToMany('App\Team', 'match_team', 'match_id', 'team2_id');
}
}
Can someone help me?
You should better use firstOrCreate(), updateOrCreate or attach() methods.

Resources