How to add new parameters to my URL - Laravel? - html

I need your help. So, I need to add more details on my URL. But what I did doesn't working. I need to add id of news on my link. Now, my link is like that : www.website.com/news/my-news-title, but it should be like that : www.website.com/news/88/my-news-title.
Here is my route:
Route::get('news/{id}/{slug}', 'ModelController#newsSingle');
Here is my view link:
Here is my controller:
public function newsSingle($slug, $id)
{
// return $slug;
$data = $this->data;
$data['news'] = News::with('category_name','news_image','models','creative')->where('slug','=',$slug)->orWhere('id','=',$id)->first();
if(count($data['news']) == 0)
{
abort(404);
}
updatNewsView($data['news']['id']);
// $displayitem = DisplayItem::where('slug','=',url('news'))->first();
// $data['page'] = $displayitem;
$data['title'] = $data['news']->title;
$data['breadcrumb'] = $data['news']->title;
// $data['menu'] = $tag->title;
$data['metadescription'] = $data['news']->metadescription;
$data['metatitle'] = $data['news']->metatitle;
// $data['blogs'] = $tag->blog;
return view('news.single_news',$data);
}
Now, the link is good, but when I'm trying to access it I get 404 error .

Your params are switched around in your controller. You have id/slug in your route but $slug, $id in your controller action.
Changing the following should work:
Controller:
public function newsSingle($id, $slug)
View:
Or use the named routes from mrhn's answer.

Your Url generation seems wrong, usually you would do named routes.
Route::get('news/{id}/{slug}', 'ModelController#newsSingle')->name('news');
Generate your url like this in the blade, by using the route helper that will return the url.

Related

Redirect restfull api codeigniter

I want to ask how to redirect the results from the input code form post like this
how do i redirect resfull api I want after input_post () page will be redirected
public function loginsi_post(){
$username = $this->post('username');
$password = $this->post('password');
$data = [];
$data['username'] = $username;
$data['password'] = $password;
if ($this->model_app->insert('jajal', $data) > 0) {
$this->response([
'message' => 'data berhasil disimpan',
'data' => $data
], REST_Controller::HTTP_CREATED);
}else{
$this->response([
'message' => 'data gagal disimpan'
], REST_Controller::HTTP_CREATED);
}
redirect('main/home'); ---------> is not working
}
Please setup your route like as below.
public function index() {
/*Load the URL helper*/
$this->load->helper('url');
/*Redirect the user to some site*/
redirect('http://www.example.com');
}
Best Regards.
Note: One can not access any controller that is in other folder and script access is not allowed this way. So there must be route set in route.php then you can access the function using route path. It can be defined as below:-
Like for example:- In route.php, the route is defined as:-
$route['your uri']='your uri';
then to access controller :-
$captcha_url = "http://your_api_url/index.php/nlpgen/nlpimg/"
Now you can use CURL to access the external URL.

Why does Laravel redirect to a wrong id after DB::listen?

I would like to store every query I run inside my application. To do that, I've created a "loggers" table, a Logger modal and this function inside my boot AppServiceProvider
DB::listen(function($query) {
$logger = new Logger;
$logger->query = str_replace('"', '', $query->sql);
$logger->bindings = json_encode($query->bindings);
$logger->created_at = Carbon::now();
$logger->save();
});
Well, anytime I run an insert query, Laravel returns the loggers table ID instead of the model last inserted ID.
Why on earth does this happen?
public function store(CycleRequest $request) {
$appointment = new Appointment;
$appointment-> ... same data ...
$appointment->save();
if ( ! $errors ) ){
$msg['redirect'] = route('appointments.edit', $appointment);
// The page redirects to last logger id
}
}
I think you want to do triggers so I recommend use events for this, o maybe you can take the structure of you table "loggers" and do two differents querys each time that you do querys.
After searching a lot, I found a solution creating a Middleware. Hope this may help someone else.
I've created a QueryLogMiddleware and registered in 'web' middleware, but you may put it everywhere you want:
public function handle($request, Closure $next)
{
\DB::enableQueryLog();
return $next($request);
}
public function terminate($request, $response)
{
$queries = \DB::getQueryLog();
foreach ($queries as $query)
{
// Save $query to the database
// $query["query"]
// $query["bindings"]
...
}
\DB::disableQueryLog();
\DB::flushQueryLog();
}

Yii2 Login Only For One Page

I have been attempting to implement an OpenID log-in with Yii2 today, and for the most part it has worked. Below is code from my controller, with the action 'Register' running through, and outputting the user->identity->username, but when I, say, redirect this action back to any page on the site, the logged in user is essentially forgotten. I can return to my Register action and have the user logged in.
Help would be appreciated. Thank you.
public function actionRegister()
{
require ('../views/site/steamauth/userInfo.php');
$localId = $_SESSION['steam_steamid'];
$foundUser = User::findOne(['steamid' => $localId]);
if(isset($foundUser))
{
Yii::$app->user->login($foundUser);
var_dump($foundUser);
echo Yii::$app->user->identity->username;
} elseif(!isset($foundUser)) {
$db = new User();
$db->steamid = $_SESSION['steam_steamid'];
$db->username = $_SESSION['steam_personaname'];
$db->visstate = $_SESSION['steam_communityvisibilitystate'];
$db->profile = $_SESSION['steam_profileurl'];
$db->avs = $_SESSION['steam_avatar'];
$db->avm = $_SESSION['steam_avatarmedium'];
$db->avf = $_SESSION['steam_avatarfull'];
$db->persstate = $_SESSION['steam_personastate'];
$db->save();
$foundUser = User::findOne(['steamid' => $localId]);
Yii::$app->user->login($foundUser);
return $this->goHome();
}
}
/**
Ah. After scouring Stackoverflow I found it.
The standard model function findIdentity
return isset(self::$usrs[$id]) ? new static(self::$usrs[$id]) : null;
must be change to reflect the new table of
return User::findOne($id);

How to display data to view from db after insertion? [L5.2]

what I am trying to do here is after the insertion I want to display the data in the same page without refreshing the page
ROUTES
Route::post('viewBook/{bookId}', 'CommentsController#insertcomment');
//there's {bookId} cause of this http://localhost:8000/viewBook/1
CONTROLLER
public function insertcomment(Request $request)
{
$commenter = Auth::user()->id;
$comments = new Comments;
$comments->comment = $request->input('mycomment');
$comments->commenter = $commenter;
$comments->save(); //insert success
//getting the data
$data=DB::table('comments')
->select('comment')
->get();
return response()->json($data,true);
}
You don't need to get the data from DB again, just return inserted Comment object:
$commenter = Auth::user()->id;
$comment = new Comments;
$comment->comment = $request->input('mycomment');
$comment->commenter = $commenter;
$comment->save(); //insert success
return response()->json($comment, true);
In your situation.
In http://localhost:8000/viewBook/1. You should send a AJAX request to Route::post('viewBook/{bookId}', 'CommentsController#insertcomment');
Then get response from server for append to current comments HTML section. The response like #Alexey Mezenin answer

How to avoid the instruction "return" inside a function in Symfony2?

I would like to know how to avoid the instruction "return" inside a function in Symfony2. In other words how can I make a void function which doesn't return anything. In fact I have tried that for a long time but every time I run the code I did I see this error message: "The controller must return a response" ... By the way, this is the code that I have:
public function AddeventsgroupeAction(Request $request) {
$eventg = new eventsgroupe();
$form = $this->createForm(new eventsgroupeType(), $eventg);
$em = $this->getDoctrine()->getManager();
$securityContext = $this->get('security.context');
$token = $securityContext->getToken();
$user = $token->getUser();
$id = $user->getId();
$groupe=$this->getRequest('groupe');
$idg = intval($groupe->attributes->get('id'));
$qb = $em->createQueryBuilder();
$qb->select('l')
->from('IkprojGroupeBundle:Groupe', 'l')
->from('IkprojGroupeBundle:eventsgroupe', 'e')
->where(' l.id = :g and e.idGroupe = l.idAdmin and l.id = e.idEventGroupe');
$qb->setParameter("g", $idg);
$query = $qb->getQuery();
$res = $query->getResult();
$rows = array();
foreach ($res as $obj) {
$rows[] = array(
'id' => $obj->getId());
}
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isValid()) {
$eventg-> setIdGroupe($id);
$eventg-> setIdEventGroupe($idg);
$em->persist($eventg);
$em->flush();
return $moslem="yes";
}
} else {
return $this->render('IkprojGroupeBundle:GroupeEvents:Addeventgroupe.html.twig', array(
'groupe' => $rows,
'event' => $eventg,
'form' => $form->createView(),
));
}
}
How can I replace the instruction : return $moslem="yes"; in order to not return anything??...Is that possible??
To answer your basic question, a simple return will return a void from your function.
The "controller must return a response" message actually comes from the request handler. You need to tell the request handler what you want it to do. There is no default page so a void return will trigger the error.
In most cases, after successfully processing a posted form you will want to return a redirect response.
Something like:
$form->handleRequest($request);
if ($form->isValid()) {
...
$em->flush();
return $this->redirect($this->generateUrl('task_success'));
I should point out that your form code seems to be from S2.1 or older. It's unnecessarily complicated. You should be using at least 2.3. Make sure you are looking at the correct version of the documentation. Hint: the isValid() takes care of the POST check.
http://symfony.com/doc/current/book/forms.html#handling-form-submissions
It's also worth while to understand the request/response workflow.
http://symfony.com/doc/current/book/http_fundamentals.html
Digging into the code can also help in understanding where the error message is coming from:
Symfony\Component\HttpKernel\HttpKernel#handleRaw($request)
Simple, delete the else statement and if $request->isMethod('POST') or $form->isValid() returns false the code inside will not be executed then the script return the default view.
EDIT: you can also make a redirect with a flash message where needed like this:
$this->get('session')->getFlashBag()->add('success', 'your success message');
return $this->redirect($this->generateUrl('your_route'));
Remember to add support for flash message in your view looking at the Symfony2 docs