I have a question, how to show 404 error if the page doesn't exist.For example if I have bloc.com and I add at the end of link bloc.com/?id=45 it redirects to the homepage but the page doesn't exists. In CodeIgniter exists a config :
$config['enable_query_strings'] = TRUE;
If I change to FALSE it gives errors at utm tags, how to show 404 if the page is bloc.com/?=45 but work fine at utm tags.Please help me.
function show($id = 0)
{
$date= $this->model->get_date($id);
if($date)
{
....
}
else
{
show_404();
}
}
I edited my question.
Would this not work?
public function show()
{
if (isset($_GET['id']) )
{
if ( $check = $this->model->get_date($_GET['id']) )
{
......
}
else
{
echo 'show_404()';
}
}
else
{
echo 'no ID set';
}
}
Related
All cruds work well both on shared hosting and localhost except create (store).
here is my addtoqueue controller:
public function store(Request $request)
{
$last = antri::whereDate('created_at', Carbon::today())->latest()->first();
if ( $last ) {
$tambah = $last->number + 1;
}
else {
$tambah = 1;
}
$newantri = new antri;
$newantri->user_id = $request->user_id;
$newantri->number = $tambah;
$newantri->called = 0;
$newantri->save();
return $newantri;
}
model:
class antri extends Model
{
use HasFactory;
}
api route :
Route::post('queue', [addtoqueue::class, 'store']);
the trigger:
<v-btn elevation="2" v-on:click="increase" >Ambil Nomor Antrian</v-btn>
the script:
methods: {
increase: function() {
axios.post('/api/queue/', {
user_id: this.user.id
})
. then( response=> {
if( response.status == 200 ) {
this.$emit('itemchanged');
}
})
. catch( error => {
console.log(error);
})
window.location.reload();
}
tested using postman worked well too on both local and share hosting database.
can anyone figure out what seems to be the problem?
I found the problem. I got Status Code 301 moved permanently every time post method is requested. this caused the url structure changed from domain/api/target to domain/public/api/targetand of course it won't hit the store function in the controller.
I edited .htaccess file in public folder from:
RewriteRule ^ %1 [L,R=301]
to
RewriteRule ^ %1 [L,R=307]
which means from permanently moved to temporarily redirected.
and this solved my problem.
I am a beginner in Vue and I am wondering if I can get an insight from experienced developers here about my Vue codes. I just want to ask for help to know if my Vue approach is efficient and proper. (Project is running on Laravel)
The Case:
Let us say I have 2 tables in DB
(1) stores
(2) ad_accounts
Then we have 2 web pages to present these tables' data and execute CRUD functions with it
(1) store.blade.php
(2) adaccount.blade.php
Each page is running a Vue component
(1) Stores.vue
(2) AdAccounts.vue
I am using Vuex for store management.
Within store.js, I would have set of actions for CRUD for each vue component.
Now I realized that I have series of actions that actually does the same thing. For example, I have an action to add stores, and another action to add Ad accounts. Their only difference is that they are calling a different Laravel route.
So it seemed to me that my code was unnecessarily long and a bit expensive. To resolve, I decided to write my actions in a form of template. So this is what I did:
In store.js, I created an action for each CRUD function to be used as template
In Stores.vue and AdAccounts.vue, if I need to execute a CRUD function, I would use a method to call the corresponding action from store.js and provide the Laravel route as part of the action's payload
I have states and corresponding getters for returning these states in Stores.vue and AdAccounts.vue
Each action has a dedicated mutation that alters the approriate state
states and getters are mapped in each Vue component in order to access and use them
Is this approach efficient and proper? I have sample methods and actions below for reference.
Stores.vue
<template>
<div>
<form #submit.prevent="addData('stores/add')">
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</template>
<script>
export default {
methods: {
addData: function(url) {
this.payload.url = url
if(
this.payload.requestData.store_name == "" &&
this.payload.requestData.store_token == ""
) {
this.payload.isErr = true;
this.payload.errMsg = "ERROR: Could not continue due to some invalid or missing data. \nPlease check your entries and try again or contact your administrator.";
this.$store.dispatch('addData', this.payload)
}
else {
this.payload.isErr = false;
this.$store.dispatch('addData', this.payload)
this.readDataAll('stores/all', 'store');
}
this.cleanOnModalDismiss(this.$refs.addModal, this.refreshRequestData)
}
}
}
</script>
AdAccounts.vue
<template>
<div>
<form #submit.prevent="addData('ad_accounts/add')">
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</template>
<script>
export default {
methods: {
addData: function(url) {
this.payload.url = url
if(
this.payload.requestData.ad_id == "" &&
this.payload.requestData.ad_name == ""
) {
this.payload.isErr = true;
this.payload.errMsg = "ERROR: Could not continue due to some invalid or missing data. \nPlease check your entries and try again or contact your administrator.";
this.$store.dispatch('addData', this.payload)
}
else {
this.payload.isErr = false;
this.$store.dispatch('addData', this.payload)
this.readDataAll('ad_accounts/all', 'adaccounts');
}
this.cleanOnModalDismiss(this.$refs.addModal, this.refreshRequestData)
}
}
}
</script>
store.js
export default new Vuex.Store({
actions: {
addData (commit, payload) { // insert a record to DB
try {
if(payload.isErr == true) {
commit('SHOW_ERRORS', {messageType: "alert-danger", errorMessage: payload.errMsg});
} else {
axios.post(payload.url, payload.requestData)
.then(response=>{
if(response.status == 200) {
var err_msg = "";
if(response.data.success !== null) {
response.data.messageType = "alert-info"
response.data.actionMessage = response.data.success
commit('ADD_DATA', response.data);
} else {
response.data.messageType = "alert-danger"
for(var i=0; i<response.data.error.length; i++) {
err_msg += response.data.error[i] + "\n"
}
response.data.actionMessage = err_msg
commit('ADD_DATA', response.data);
}
}
else {
commit('SHOW_ERRORS', {messageType: "alert-danger", errorMessage: "ERROR: Connection status set to '" + response.headers.connection + "' due to error " + response.status + " " + response.statusText + ". \nPlease contact your administrator."});
}
})
}
} catch (error) {
commit('SHOW_ERRORS', {messageType: "alert-danger", errorMessage: error})
}
}
}
}
I'm trying to work with the BarryVdh/DOMPDF code in my Laravel project.
I made a page with a print button, with
Print
This is calling the controller function :
public function printFacturen(Request $request) {
$facturen = Factuur::all();
view()->share('facturen', $facturen);
$pdf = PDF::loadView('pdf.facturen');
return $pdf->download('invoice.pdf');
}
This is successfully downloading the PDF file.
My route is :
Route::get('/print-facturen', 'PrintController#printFacturen')->name('print_overzicht_facturen');
But, I need the content of a radio button to fill my PDF instead.
So I change my a href to
Print
I add a jQuery function :
$(".printbtn").click(function(e)
{
var option = $("input[name='factuur_selectie']:checked").val();
$.ajax({
type: 'POST',
url: 'print-facturen',
data: {"optionID": option}
})
});
And my controller is changed to
public function printFacturen(Request $request) {
$option = $request->get('optionID');
$facturen = Factuur::all();
$searchFacturen = new \Illuminate\Database\Eloquent\Collection();
foreach ($facturen as $factuur) {
if ($option == 1) {
$searchFacturen->add($factuur);
}
else if ($option == 2) {
if ($factuur->voldaan == true) {
$searchFacturen->add($factuur);
}
}
else if ($option == 3) {
if ($factuur->voldaan == false) {
$searchFacturen->add($factuur);
}
}
}
view()->share('facturen', $searchFacturen);
$pdf = PDF::loadView('pdf.facturen');
return $pdf->download('invoice.pdf');
}
I can see my optionID successfully, but the PDF file is NOT being downloaded anymore ... :-(
As I got a POST error, I added this route :
Route::post('/print-facturen', 'PrintController#printFacturen')->name('print_overzicht_facturen');
When inspecting the network, I see this :
SORRY, I'm not allowed yet to post pictures here :-(
(https://user-images.githubusercontent.com/5870500/32404394-3555952c-c14f-11e7-82c3-2d000d1a2661.png)
What am I doing wrong ?
Best regards,
Davy
You need to set proper http response headers:
header('Content-Type: application/octet-stream; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$filename.'"');
Other simple option to do it will be to dynamic modify link on radio click to get link like: example.org/download?radio=1
I am using Laravel for site development purposes. What would be nice is to have a button on the main page that shows the current version of the project. When clicking on the button, one would see all of the changes that have taken place (in the form of git commits) to the system. Is there a way to do this? If so, how?
TIA
On click of the button initiate an ajax call
$("#button").on("click", function () {
url: window.location.origin + '/fetch-git-commits',
type: "get",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
// data contains the git commit informations
$(".container").html(data);
}
});
In the Route.php file add an entry
Route::get('fetch-git-commits', 'YourController#getGitCommits');
In the controller
public function getGitCommits ()
{
exec('git log', $output);
$history = array();
foreach($output as $line) {
if(strpos($line, 'commit') === 0) {
if(!empty($commit)) {
array_push($history, $commit);
unset($commit);
}
$commit['hash'] = substr($line, strlen('commit'));
}
else if(strpos($line, 'Author') === 0) {
$commit['author'] = substr($line, strlen('Author:'));
}
else if(strpos($line, 'Date') === 0) {
$commit['date'] = substr($line, strlen('Date:'));
}
else {
if(isset($commit['message']))
$commit['message'] .= $line;
else
$commit['message'] = $line;
}
}
return $history; // Array of commits, parse it to json if you need
}
References:
Reading a git commit message from php
Parse git log with PHP to an array
There is a little package for that:
https://github.com/tremby/laravel-git-version
i am using ajax for send active form by this function
public function Link()
{
$id=$this->params['id'];
$url=$this->params['url'];
$dviId=$this->params['divId'];
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() { $.ajax({url: '".$url."',type: 'POST',success : function(res){ $('#".$dviId."').html(res);}});});";
$view = $this->getView();
AjaxAsset::register($view);
if ($js2 !== '') {
$view->registerJs($js2);
}
return ;
}
And want to show error if any happened else send form
There is a plugin in jquery to do client side validation if you are using javascript and want to do initial validation of the form.
http://jqueryvalidation.org/
Also you can use "required" attribute in your text tags to do some intial checks. More can be found here:
http://www.w3schools.com/tags/att_input_required.asp
Hope this helps a bit.
You can also set enableAjaxValidation to true in your form.
There is an example in the docs about that (see the controller part).
public function Link()
{
$id=$this->params['id'];
$url=$this->params['url'];
$dviId=$this->params['divId'];
if(isset($this->params['confirm'])) {
$confirm = "if(confirm('".$this->params['confirm']."')){";
$endConfirm = "}";
}
else
{
$confirm = "";
$endConfirm = "";
}
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() {".$confirm."$.ajax({url: '".$url."',type: 'POST',beforeSend: function(){ $('body').addClass('wait');},complete: function(){ $('body').removeClass('wait');},success : function(res){ $('#".$dviId."').html(res);}});".$endConfirm."});";
$view = $this->getView();
AjaxAsset::register($view);
if ($js2 !== '') {
$view->registerJs($js2);
}
return ;
}