How to create a primary key alerts when the data input together with CodeIgniter?
example if I insert 001 but in the database already exists 001 subsequently appeared alert
In your Model you can run an SQL query to see if the primary key is already present. If it is, then you can simply return an error code to the Controller, which should handle things from there (by sending an error message to the View).
Model
function checkPrimaryKey($primary_key){
$sql = "SELECT * FROM table_name WHERE primary_key = '$primary_key'";
/* Replace table_name And primary_key With Actual Table Name And Column Name */
$query=$this->db->query($sql);
if($query->num_rows() == 1){
return -1; //Key already exists
}
else{
return 0; //Key does not exist
}
}
Controller
function checkPrimaryKey($primary_key){
$this->load->model('Model_name');
if($this->Model_name->checkPrimaryKey($primary_key)==-1){
//Appropriate Error Message
}
else {
//Call Some Model Function to Insert The Data And/Or Display Appropriate Success Message
}
}
Related
Trying to implement a polymorphic many-to-many relationship, similar to the one in the documentation.
In my case, for label instead of tag. And using different table names
apples / oranges / ...
id - integer
name - string
label_types
id - integer
name - string
labels
label_type_id - integer -- foreign ID for LabelType
labeling_type - string
labeling_id - integer - ID of the model this labelType is used for
// Apple / Orange / ...
public function labels(LabelType $type = null)
{
// need to provide table name, as expected default table name is labelings
return $this->morphToMany(Label::class, 'labeling', 'labels');
}
// Label
public function apples()
{
return $this->morphedByMany(Apple::class, 'labeling', 'labels');
}
public function oranges()
{
return $this->morphedByMany(Orange::class, 'labeling', 'labels');
}
This results in an error.
$apple->labels;
Illuminate\Database\QueryException with message 'SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'labels'
select
`labels`.*,
`labels`.`label_id` as `pivot_label_id`,
`labels`.`label_type` as `pivot_label_type`
from
`labels`
inner join `labels` on `labels`.`id` = `labels`.`label_id`
where
`labels`.`label_id` = 1
and `labels`.`label_type` = 'App\Models\Apple'
In the example above I have added the table name to morphToMany().
Same error when using labelings as table name and adding to Label model: protected $table = 'labelings';
How do I get this to work? I do want to use label_types as it better fits with the rest of my application.
I looked at other polymorphic questions on Stackoverflow, but could not find an answer.
I have related tables events and tickets which are related
class Event {
public function tickets(){
return $this->hasMany(Ticket::class);
}
}
class Ticket {
public function events(){
return $this->belongsTo(Event::class);
}
}
I have a store function getting data from and route URL
$ticket=new Ticket;
$ticket->userName= $request->input('userName');
$ticket->userEmail= $request->input('userEmail');
$ticket->phoneNumber= $request->input('phoneNumber');
$ticket->regular_quantity= $request->input('regular_quantity');
$ticket->vip_quantity= $request->input('vip_quantity');
$ticket->event_id=$request->route('id');
I have a variable max_attendees which I want to query the maximum attendees which is a column in events table where event id is
$ticket->event_id=$request->route('id');
query
$maximum_attendants=\App\Models\Event::with('Max_attendies')->where('id','=='$event_id');
events table
I have tried this but giving me syntax error, unexpected 'event_id' (T_STRING), expecting ')'
You're missing the , in your where clause:
where('id','==', $event_id)
If you are counting attendance from your 'tickets' table, you can use relation to count,
$event = Event::find($id);
$event->tickets()->count();
i have 4 table
inst
id
subject
report
id
subject
object
id
type
container
id
obj_id
i want with obj_id of container table, achieve the The corresponding object record.
then if type of object = 1, fetch data from inst table or type = 2, fetch data from report table
based on your information,
you can do like #Mahfuz Shishir answer
or
create new appends attribute inside Object Model
protected $appends = ['data'];
public function getDataAttribute()
{
if($this->attributes['type'] == 1) {
return Inst::where('inst_column', $this->attributes['object_column_to_match']); //this just sample
} else {
return Report::where('inst_column', $this->attributes['object_column_to_match']); //this just sample
}
}
The relation looks like.
In your Object.php Model
public function containers()
{
return $this->hasMany('App\Container', 'foreign_id');
}
And in your Container.php Model
public function object()
{
return $this->belongsTo('App\Object', 'foreign_id');
}
You provide little information. Implement rest of the controller code in your own sense. Or put some code that you have tried.
This is really weird to me. when I want to display data from rows, some data return error.
I can only view data with ids (1-7, 10, 13-17,22 and so), data with id (8,9,11,12,18,19,20,21..) return error.
if i go to http://manajemenpasien.com/PasienPoli/17, i get the page i expected. but when going to this http://manajemenpasien.com/PasienPoli/19, i get this error:
ErrorException in Collection.php line 1564:
Property [nama] does not exist on this collection instance. (View: D:\myProjects\manajemenPasien\resources\views\PasienPoli\show.blade.php)
[nama] is a field name in table pasiens
this is what I have in PasienPoliController:
public function show($id)
{
$pasienpoli = PasienPoli::find($id);
$pasien = Pasien::find($id)->PasienPoli;
return view('pasienpoli.show', compact('pasienpoli','pasien'));
}
PasienPoli Model:
public function pasien()
{
return $this->belongsTo('App\Pasien');
}
Pasien Model:
public function pasienpoli()
{
return $this->hasMany('App\PasienPoli');
}
show.blade.php:
<h2>{{$pasienpoli->pasien->nama}}</h2>
Table structure of pasien_polis:
id - int(10) - auto_increment
polyclinic_id - int(11)
pasien_id - int(11)
penyakit - varchar(50)
Table structure of pasiens:
id - int(10) - auto_increment
nama - varchar(50)
what is wrong with this?
Most likely those ids do not exist in your database. Check your databse or dd the collection in your view to find out what's going on.
Modify your code to this:
public function show($id)
{
if(($pasienpoli = PasienPoli::find($id)) == NULL)
return view('pasienpoli.notfound', []);
$pasien = Pasien::find($id)->PasienPoli;
return view('pasienpoli.show', compact('pasienpoli','pasien'));
}
if the id does not exists you can return another view or what you want.
I'm trying to check if the excel file a user has uploaded has the correct columns/first row/attributes before reading into its other rows. I'm using Laravel 4 with MaatWebsite's Laravel Excel.
I have created a function which allows users to update the employee table of the system's database by importing an excel file.
Now the correct excel file, has, let's say, 3 columns: firstname, lastname, and username. If the excel file has all these attributes/columns, I will now read each of the following rows and validate each row, which isn't really a part of my problem as of now.
But if any of the 3 attribute/column is not present in the excel file, I'd ignore the request and return an error.
I tried using this, which gets lastname attribute:
$sample = Excel::selectSheetsByIndex(0)->load($readFile, function($reader){})->get(array("lastname"));
But even though lastname hasn't been found, $sample is still not null so I won't be able to check if lastname is present or not.
How can I check if the attributes/columns are present/not?
UPDATE:
The answer that I selected would work perfectly if the first row after the attributes row has all the needed attributes. For example: If it has values for firstname, lastname, and username.
But if in cases where first name value (or any attritbute value for that matter) of the first non-attribute row (attribute row referring to the column names) is missing, then the provided script would return false, even if the excel file has all the firstname, lastname, and username attributes.
So I modified the script to this:
First, I read the excel file. I also declared a Boolean variable to mark if the excel file is valid or not.
$excelChecker = Excel::selectSheetsByIndex(0)->load('path/to/file', function($reader){})->get()->toArray();
$excelIsValid = false;
Then I loop through all the results and check if at least once, all the values required (firstname, lastname, and username) have been set or are present.
foreach($excelChecker as $ex){
if(isset($ex["lastname"]) && isset($ex["firstname"]) && isset($ex["username"])){
$excelIsValid = true;
}
}
Explanation:
If $excelIsValid is still false at the end of the loop, then not once did the file had all the attributes required. This either means the file is empty, has the wrong attribute names, or does not have any valid row. In short, the file is invalid and should not be in the system.
I prepared this sample script:
Route::get('/', function() {
$isError = false;
Excel::load('file.xls', function($reader) use (&$isError) {
$firstrow = $reader->first()->toArray();
if (isset($firstrow['firstname']) && isset($firstrow['lastname']) && isset($firstrow['username'])) {
$rows = $reader->all();
foreach ($rows as $row) {
echo $row->firstname.' '.$row->lastname.' '.$row->username."<br />";
}
}
else {
$isError = true;
}
});
if ($isError) {
return View::make('error');
}
});
The script loads file and check if there are columns you want. It doesn't check if there are more columns - of course if you want you can add exta check - count($firstow) == 3. If there is error it sets $isError to true and in route it displays a template.
In Laravel Excel 3.1 you can use
public function import()
{
$column= (new HeadingRowImport)->toArray('users.xlsx');
if (isset($column['firstname']) && isset($column['lastname']) && isset($column['username'])) {
//dd('columns found');
//your code
}else{
//dd('columns not found');
//if not found show error or something
}
}
You can do anything inside of that if else or you can use your logic