Laravel | Call variable in view - php

I need help figuring out what I'm doing wrong. I'm building a chat where on the right side I have the users and when clicking on the user opens the respective chat.
In the users on the right I put the following HREF:
<a href="{{route('chat.index', ['id'=>$item->id])}}">
Which then shows the following link on the page:
/Chat?id=10
I put in the view if there is id shows the chat.
#if ($id)
But don't come here. I can't get the IF to be true.
In the controller I have the following code, but I don't think it's wrong.
$outroUser = null;
if($id){
$outroUser = utilizador::findOrFail($id);
}
$tabela = utilizador::orderBy('id', 'desc')->get();
return view('painel-admin.chat.index', ['itens' => $tabela, $outroUser]);

To get id param you can try following in your controller
if ($request->has('id')) {
$outroUser = utilizador::findOrFail($request->query('id'));
}
Do not forget to add Request object into your controller function params
use Illuminate\Http\Request;
public function yourController(Request $request) {
//Code
}

Related

Replacing object ID by object name on URL on Laravel route

I am trying to make my URL more SEO friendly on my Laravel application by replacing the ID number of a certain object by the name on the URL when going to that specific register show page. Anyone knows how?
This is what I got so far and it displays, as normal, the id as the last parameter of the URL:
web.php
Route::get('/job/show/{id}', ['as'=>'website.job.show','uses'=>'HomeController#show']);
Controller method
public function show($id){
$job = Job::findOrFail($id);
return view('website.job')->with(compact('job'));
}
Blade page where there is the link to that page
{{$job->name}}
You can overwrite the key name of your Job model:
public function getRouteKeyName()
{
return 'name';
}
Then in your route simply use {job}:
Route::get('/job/show/{job}', ...);
And to call your route:
route('website.job.show', $job);
So your a tag would look like this:
{{ $job->name }}
Inside your controller, you can change the method's signature to receive the Job automatically:
public function show(Job $job)
{
return view('website.job')
->with(compact('job'));
}
For more information, look at customizing the key name under implicit binding: https://laravel.com/docs/5.8/routing#implicit-binding
You need simply to replace the id by the name :
Route::get('/job/show/{name}', ['as'=>'website.job.show','uses'=>'HomeController#show']);
In the controller action:
public function show($name){
//Make sure to replace the 'name' string with the column name in your DB
$job = Job::where('name', $name)->first();
return view('website.job')->with(compact('job'));
}
Finally in the blade page :
{{$job->name}}
2 options:
1) one is like #zakaria-acharki wrote in his comment, by the name of the job and search by the name for fetching the data
2) the second is to do it like here in stackoverflow
to build the url with the id/name
in this way you will make sure to fetch and show the relevant job object by the unique ID
the route:
Route::get('/job/show/{id}/{name}', ['as'=>'website.job.show','uses'=>'HomeController#show']);
in the controller, update the check if the name is equal to the job name (in case it was changed) to prevent duplicate pages url's
public function show($id, $name){
$job = Job::findOrFail($id);
// check here if( $job->name != $name ) {
// redirect 301 to url with the new name
// }
return view('website.job')->with(compact('job'));
}
in the blade.php :
{{$job->name}}

how to get the current id of show function in laravel

in my controller in my show function in laravel i want the get the id that shows in browser show when i browse it it shows like this
http://localhost:8000/admin/invoices/1
i want to get that "1" and use it in show controller like below
public function show(Invoice $invoice)
{
$clients = Invoice::with('user','products')->get();
$invoice_id = 1;
$invoices = Invoice::with('products')->where('id', '=', $invoice_id)->firstOrFail();
return view('admin.invoices.show', compact('invoice','invoices'),compact('clients'));
}
and put it instead of $invoice_id so when every my client visit this page only sees the related invoice products . thanks you for help
If you're actually getting an instance of Invoice passed to your show method then it likely means you have Route-Model Binding set up for your project. Laravel is looking at the defined route and working out that the ID part (1) should map to an instance of Invoice and is doing the work to grab the record from the database for you.
The Invoice object passed through should refer to an item in your database with the ID of 1, so to get the ID that was mapped in the route you can simply just do:
public function show(Invoice $invoice)
{
echo $invoice->id; // This should be 1
Laravel supports route model binding out of the box these days, but in earlier versions you had to set it up in app/Providers/RouteServiceProvider.php. If you don't want it, try replacing your show method signature with this:
public function show($id)
{
echo $id; // Should be 1
By removing the type-hint you're simply expecting the value that was given in the route parameter and Laravel won't try to resolve it out of the database for you.
Simple way you may try this.
//Define query string in route
Route::get('admin/invoice/{id}','ControllerName#show')
//Get `id` in show function
public function show(Invoice $invoice,$id)
{
$invoice_id = $id;
}
Try using $invoiceId
public function show(Invoice $invoice, $invoiceId)
{
$clients = Invoice::with('user','products')->get();
$invoices = Invoice::with('products')->findOrFail($invoiceId);
return view('admin.invoices.show', compact('invoice','invoices'),compact('clients'));
}
do this if you want to get the url segment in controller.
$invoice_id = request()->segment(3);
if you want this in view
{{ Request::segment(3) }}
Goodluck!
Usually happens when giving a route name different from the controller name
Example:
Route::resource('xyzs', 'AbcController');
Expected:
Route::resource('abcs', 'AbcController');

Copy one row from one table to another

I need a little help and I can’t find an answer. I would like to replicate a row from one data table to another. My code is:
public function getClone($id) {
$item = Post::find($id);
$clone = $item->replicate();
unset($clone['name'],$clone['price']);
$data = json_decode($clone, true);
Order::create($data);
$orders = Order::orderBy('price', 'asc')->paginate(5);
return redirect ('/orders')->with('success', 'Success');
}
and i got an error :
"Missing argument 1 for
App\Http\Controllers\OrdersController::getClone()"
.
I have two models: Post and Order. After trying to walk around and write something like this:
public function getClone(Post $id) {
...
}
I got another error
Method replicate does not exist.
Where‘s my mistake? What wrong have i done? Maybe i should use another function? Do i need any additional file or code snippet used for json_decode ?
First of all, make sure your controller gets the $id parameter - you can read more about how routing works in Laravel here: https://laravel.com/docs/5.4/routing
Route::get('getClone/{id}','YourController#getClone');
Then, call the URL that contains the ID, e.g.:
localhost:8000/getClone/5
If you want to create an Order object based on a Post object, the following code will do the trick:
public function getClone($id) {
// find post with given ID
$post = Post::findOrFail($id);
// get all Post attributes
$data = $post->attributesToArray();
// remove name and price attributes
$data = array_except($data, ['name', 'price']);
// create new Order based on Post's data
$order = Order::create($data);
return redirect ('/orders')->with('success', 'Success');
}
By writing
public function getClone(Post $id)
you are telling the script that this function needs a variable $id from class Post, so you can rewrite this code like this :
public function getClone(){
$id = new Post;
}
However, in your case this does not make any sence, because you need and integer, from which you can find the required model.
To make things correct, you should look at your routes, because the url that executes this function is not correct, for example, if you have defined a route like this :
Route::get('getClone/{id}','YourController#getClone');
then the Url you are looking for is something like this :
localhost:8000/getClone/5
So that "5" is the actual ID of the post, and if its correct, then Post::find($id) will return the post and you will be able to replicate it, if not, it will return null and you will not be able to do so.
$item = Post::find($id);
if(!$item){
abort(404)
}
Using this will make a 404 page not found error, meaning that the ID is incorrect.

Generate multiple result in codeigniter

Currently I am working on one Web-based software which creates results automatically in codeigniter. I create modules like add student, add marks & generate mark sheet. here in generate marksheet i created individual marksheet but now I want to generate code for generate marksheet on one button click.
For that i use file_get_content(), curl(), fopen() but this all showing blank page if file_get_content("http://127.0.0.1/exam/admission/forms/showResult/41/2/1")
shows individual students result i want to show it in page
Here is My controller code
class forms extends CI_Controller {
function __construct() {
parent::__construct();
$this->admin_layout->setLayout('template/layout_admission');
$session = $this->session->userdata('admin_session');
if (empty($session) || $session->type != 'admission') {
$this->session->set_flashdata('error', 'Login First');
redirect(base_url() . 'login', 'refresh');
}
function printDoc(){
$siteaddressAPI = "http://127.0.0.1/exam/admission/forms/showResult/41/2/1";
$data = file_get_contents($siteaddressAPI);
echo $data;
}
}
Your Question does not explain exactly what you need.!!! Better you can give your sample code with expected result.
Still I have a solution which might help you in some way.
You can use view template to generate mark-sheet code. For Example:
$mark_sheets = array();
foreach($all_students_data as $student_data){
$mark_sheets[] = $this -> load -> view('marksheet_template', $student_data, TRUE);
}
Here $this -> load -> view() with third parameter TRUE will return generated html code and then store it in mark_sheets array.
By this way, you can access all your mark-sheets from $mark_sheets array.

Codeigniter tutorial delete Post doesn't work

After completing the tutorial from the codeigniter user guide I ran into a problem I was forcing for the last two hours. I am trying to add functionality to delete a post, selected by ID, I am new to PHP and couldn't find any solution for my problem:
The Controller
public function delete($id){
$id = $this->uri->segment(3);
$data['title'] = 'Delete an item';
if($this->news_model->delete_news($id)){
$this->load->view('templates/header', $data);
$this->load->view('news/success');
$this->load->view('templates/footer');
}else{
}
}
The Model
public function delete_news($id){
$this->db->where('id',$id)->delete('news');
return $this->db->affected_rows();
}
The Routing
$route['news/delete/(:num)'] = 'news/delete/$1';
I'm calling the function out of the index-page where all posts are shown with an anchor:
<p>Delete article</p>
and it calls the correct URL (http://localhost/webapp/index.php/news/delete/2) which should correctly execute and delete the post with the ID 2 from my news table.
I really can't understand where the mistake ism but by executing this, I get a 404.
What am I doing wrong?
In your function delete I don't see that you loaded the news_model. That could be the issue if it isn't auto-loading. Perhaps, start by verifying that the controller is talking to the model by inserting:
echo 'Hello Model';
in the delete_news function of your news_model.
EDIT:
Instead of
if($this->news_model->delete_news($id)){
//conditions
}
And
Have your model send a T/F based on it's execution. This will tell us if the error is in the SQL. By returning TRUE no matter what, we'll see if that model function even runs:
return TRUE;
Try to add the step (for error checking)
$del = $this->news_model->delete_news($id);
echo 'del';
if($del == TRUE){
//conditions
}
With the 404 - I'm also suspicious it's a routing issue. I'll take a look at that as well.

Categories