How to get id from url parameter to url function codeigniter4
public function show($id = null)
{
$data = $this->model->where('id', $id)->findAll();
if ($data) {
return $this->respond($data, 200);
} else {
return $this->failNotFound("Data Not Found to $id");
}
}
You can pass the value using post request.
and in controller function you can read like this
public function show( ) {
$id = $this->request->getVar('id');
$data = $this->model->where('id', $id)->findAll();
if ($data) {
return $this->respond($data, 200);
} else {
return $this->failNotFound("Data Not Found to $id");
}
}
I wonder how I can redirect a user after login?
Lets say that I am on the page "www.mysite.com/users/2"
Then I try to edit a blog post without being logged in and get sent to the login page, efter login I wish to return to "www.mysite.com/users/2"
I have tried this so far:
if (Auth::attempt($credentials,$remember)) {
return redirect()->back();
} else {
return redirect()->back()->withErrors([trans('api.couldnotlogin')]);
}
But return redirect()->back(); will only redirect me to "www.mysite.com/"
Update
I got it working using this:
public function showLoginForm()
{
$previous_url = Session::get('_previous.url');
$ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$ref = rtrim($ref, '/');
if ($previous_url != url('login')) {
Session::put('referrer', $ref);
if ($previous_url == $ref) {
Session::put('url.intended', $ref);
}
}
return view('auth.login');
}
public function loginUser(ApiAuthUserPassRequest $request)
{
if ($request->has('rememberme')) {
$remember = $request->input('rememberme');
} else {
$remember = false;
}
$credentials = ['email' => $request->input('email'), 'password' => $request->input('password')];
if (Auth::attempt($credentials,$remember)) {
if (Session::has('referrer')) {
return redirect()->intended(Session::pull('referrer'));
} else {
return redirect('/account');
}
} else {
return redirect()->back()->withErrors([trans('api.couldnotlogin')]);
}
}
Laravel 5.1 have trait Illuminate/Foundation/Validation/ValidatesRequests.php with method
protected function getRedirectUrl()
{
return app(UrlGenerator::class)->previous();
}
where UrlGenerator is Illuminate/Routing/UrlGenerator.php. You can try use previous() method.
I currently have a relationship between checklistItem and actions as followed:
public function action()
{
return $this->belongsTo(Action::class, 'action_id', 'id');
}
public function checklistItem()
{
return $this->hasOne(ChecklistItem::class, 'action_id', 'id');
}
I currently made a method, when saving an action, the checklistItem status should also change depending on what was chosen:
public static function saveFromRequest(Request $request)
{
if (($action = parent::saveFromRequest($request)) !== null){
if (!is_null($action->checklistItem)) {
$action->checklistItem->value->status = $action->switchStatusChecklist($action);
//Need to update or save this specific checklistItem
$action->checklistItem->save();
}
}
return $action;
}
function switchStatusChecklist($action)
{
switch($action->status) {
case 'closed':
$status = 'checked';
break;
case 'canceled':
$status = 'notapplicable';
break;
default:
$status = 'open';
break;
}
return $status;
}
Problem:
My checklistitem does not get updated.
I have this code on my controller
public function gracias()
{
$client = new Client;
$client->name = "name";
$client->lastname = "lastname";
$client->email = "email";
$client->phone = "phone";
$client->save();
Client::saved(function($client)
{
Log::info('on saved');
if ($client->isValid())
{
Log::info('SUCCESSFULL SAVING MODEL');
}else
{
Log::info('ERROR ON SAVING CLIENT');
}
});
Event::listen('client.create', function($client)
{
Log::info('event listen client.create');
});
and on Laravel.log I don't see the "Logs messages", the Model Events don't fire. What I'm doing wrong?
Thank you!!
A model event must be set before you actually save your models as #SamSquanch mentioned. The recommended way (not including observers) is to use the boot method.
In your case it would be like this:
<?php
class Client extends Eloquent {
public static function boot() {
parent::boot();
static::saved(function($client) {
Log::info('on saved');
if ($client->isValid()) {
Log::info('SUCCESSFULL SAVING MODEL');
} else {
Log::info('ERROR ON SAVING CLIENT');
}
})
}
public function gracias()
{
Event::listen('client.create', function($client) {
Log::info('event listen client.create');
});
$client = new Client;
$client->name = "name";
$client->lastname = "lastname";
$client->email = "email";
$client->phone = "phone";
$client->save();
}
}
This will trigger on all saves on the model. If you only want to trigger when a model have been successfully created, change static::saved to static::created.
You are setting the event closure AFTER you are calling save on the model. You should be calling save after you define the event closure.
public function gracias()
{
$client = new Client;
$client->name = "name";
$client->lastname = "lastname";
$client->email = "email";
$client->phone = "phone";
Client::saved(function($client) {
Log::info('on saved');
if ($client->isValid()) {
Log::info('SUCCESSFULL SAVING MODEL');
} else {
Log::info('ERROR ON SAVING CLIENT');
}
});
Event::listen('client.create', function($client) {
Log::info('event listen client.create');
});
$client->save();
}
I am not able to load models to the extended My_Router class in codeigniter. Below is my code:
class MY_Router extends CI_Router {
function MY_Router()
{
parent::CI_Router();
}
function _validate_request($segments)
{
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if (count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
show_404($this->fetch_directory().$segments[0]);
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
// Let's check if there are category segments
$category_routes = $this->category_routing($segments);
if($category_routes !== FALSE)
{
return $category_routes;
}
$user_routes = $this->user_routing($segments);
if($user_routes != FALSE)
{
return $user_routes;
}
show_404($segments[0]);
}
function category_routing($segments)
{
$this->load->model('category_model');
if($this->category_model->category_exist($segments[0]))
{
//if only category
if(count($segments)==1)
{
return array('category', 'category_browse', $segments[0]);
}
//category pagination
if(count($segments)==2 and is_numeric($segments[1]))
{
return array('category','category_browse', $segments[0], $segments[1]);
}
//category upcoming
if(count($segments)==2 and $segments[1] == 'upcoming')
{
return array('category','upcoming', $segments[0]);
}
//category upcoming pagination
if(count($segments)==3 and $segments[1] == 'upcoming' and is_numeric($segments[3]))
{
return array('category','upcoming', $segments[0], $segments[3]);
}
//category top
if(count($segments)==3 and $segments[1] == 'top')
{
return array('category','top', $segments[0], $segments[2]);
}
//category top pagination
if(count($segments)==4 and $segments[1] == 'top' and is_numeric($segments[3]))
{
return array('category','top', $segments[0], $segments[3]);
}
}
return FALSE;
}
function user_routing($segments)
{
$this->load->model('dx_auth/users', 'user_model');
if($this->user_model->check_username($segments[0]))
{
//only profile
if(count($segments)==1)
{
return array('user','profile',$segments[0]);
}
//all friends
if(count($segments)==2 and $segment[1]=='allfriends')
{
return array('user','allfriends',$segments[0]);
}
//all subscribers
if(count($segments)==2 and $segment[1]=='allsubscribers')
{
return array('user','allsubscribers',$segments[0]);
}
//all subscription
if(count($segments)==2 and $segment[1]=='allsubscriptions')
{
return array('user','allsubscriptions',$segments[0]);
}
}
return FALSE;
}
}
I have tried loading the models by using get_instance function provided by codeigniter but seems like it doesnot work. All i need is load the models in extended system library.
There is no access to the CodeIgniter super-global until CI_Base has been called which is extended by Controller. The Controller class then loads the Loader library:
// In PHP 5 the Loader class is run as a discreet
// class. In PHP 4 it extends the Controller
if (floor(phpversion()) >= 5)
{
$this->load =& load_class('Loader');
$this->load->_ci_autoloader();
}
The Router is loaded very on (have a look in system/codeigniter/CodeIgniter.php to see exactly when, on line 99) so has barely anything available.
You can use load_class('Whatever'); to load classes in a different order, but this can really screw with things if you are not careful, and you still wont have access to the database drivers.
Basically, you can't do it this way. You would need to try and directly work with the database library or use native MySQL bindings to access your data.
Here is what i did and it worked..Thanks phil for suggestion.
class MY_Router extends CI_Router {
function MY_Router()
{
parent::CI_Router();
}
function _validate_request($segments)
{
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if (count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
show_404($this->fetch_directory().$segments[0]);
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
// Let's check if there are category segments
$category_routes = $this->category_routing($segments);
if($category_routes !== FALSE)
{
return $category_routes;
}
$user_routes = $this->user_routing($segments);
if($user_routes !== FALSE)
{
return $user_routes;
}
show_404($segments[0]);
}
function category_routing($segments)
{
if($this->check_category_exist($segments[0]))
{
//if only category
if(count($segments)==1)
{
return array('category', 'category_browse', $segments[0]);
}
//category pagination
if(count($segments)==2 and is_numeric($segments[1]))
{
return array('category','category_browse', $segments[0], $segments[1]);
}
//category upcoming
if(count($segments)==2 and $segments[1] == 'upcoming')
{
return array('category','upcoming', $segments[0]);
}
//category upcoming pagination
if(count($segments)==3 and $segments[1] == 'upcoming' and is_numeric($segments[3]))
{
return array('category','upcoming', $segments[0], $segments[3]);
}
//category top
if(count($segments)==3 and $segments[1] == 'top')
{
return array('category','top', $segments[0], $segments[2]);
}
//category top pagination
if(count($segments)==4 and $segments[1] == 'top' and is_numeric($segments[3]))
{
return array('category','top', $segments[0], $segments[3]);
}
}
return FALSE;
}
function check_category_exist($cat_name)
{
//connect to database and find the category
include(APPPATH.'config/database'.EXT);
$conn = mysql_connect($db['default']['hostname'],$db['default']['username'],$db['default']['password']);
mysql_select_db($db['default']['database'],$conn);
$sql = sprintf("SELECT COUNT(id) as count FROM categories WHERE permalink = '%s'", mysql_real_escape_string($cat_name));
$query = mysql_query($sql);
$row = mysql_fetch_object($query);
mysql_close($conn);
if($row->count)
{
return TRUE;
}
return FALSE;
}
function user_routing($segments)
{
if($this->check_username_exist($segments[0]))
{
//only profile
if(count($segments)==1)
{
return array('user','profile',$segments[0]);
}
//all friends
if(count($segments)==2 and $segments[1]=='allfriends')
{
return array('user','allfriends',$segments[0]);
}
//all subscribers
if(count($segments)==2 and $segments[1]=='allsubscribers')
{
return array('user','allsubscribers',$segments[0]);
}
//all subscription
if(count($segments)==2 and $segments[1]=='allsubscriptions')
{
return array('user','allsubscriptions',$segments[0]);
}
}
return FALSE;
}
function check_username_exist($username)
{
//connect to database and find the category
include(APPPATH.'config/database'.EXT);
$conn = mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']);
mysql_select_db($db['default']['database'],$conn);
$sql = sprintf("SELECT COUNT(id) as count FROM users WHERE username = '%s'", mysql_real_escape_string($username));
$query = mysql_query($sql);
$row = mysql_fetch_object($query);
mysql_close($conn);
if($row->count)
{
return TRUE;
}
return FALSE;
}
}
The following code will solve your problem too and will make your coding lot easier and flexible.
require_once( BASEPATH . 'database/DB' . EXT );
$db = & DB();
$query = $db->query("select ...");
$results = $query->result();
When using the base CodeIgniter class in external Libraries you have to invoke it again like this:
// load it
$CI =& get_instance();
$CI->load->model('model_name');
//use it
$CI->model_name->method()
Hope that helps