The problem I have is that I do not know how I can use the data of a query in a view if someone can give me a serious idea, the form I use is this but it gives me an error:
My Controller:
public function edit($id){
$datosProfesor = DB::table('profesor')->where('id', $id)->get();
$institucionDB = DB::table('institucion')->get();
$datos = array('datosProfesor' => $datosProfesor, 'institucionDB' => $institucionDB);
return view('profesorView/editarProfesor', $datos);
}
My view:
<div class="form-group">
<h4>Nombre</h4>
<input type="text" name="nombre_profesor" id="nombre_profesor" class="form-control" placeholder= 'Nombre' value="{{$datosProfesor['id']}}">
</div>
The error that appears to me is this:
Undefined index: id (View: /var/www/html/Konecte/resources/views/profesorView/editarProfesor.blade.php)
The get() method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass object. You may access each column's value by accessing the column as a property of the object:
foreach ($datosProfesor as $profesor) {
echo $profesor->id;
}
If you want to get a single result then you can use find() method as:
$datosProfesor = DB::table('profesor')->find($id);
which is a short form of:
$datosProfesor = DB::table('profesor')->where('id', $id)->first();
Just one more tip for you that you can use PHP's compact() method for creating array containing variables and their values. So that you can get rid of line
$datos = array('datosProfesor' => $datosProfesor, 'institucionDB' => $institucionDB);
Your final code will look as:
public function edit($id){
$datosProfesor = DB::table('profesor')->find($id);
$institucionDB = DB::table('institucion')->get();
return view('profesorView/editarProfesor', compact('datosProfesor', 'institucionDB'));
}
Related
I was looking for help creating an object of the type Illuminate\Http\Request. This article helped me understand the mechanism of the class, but I did not get the desired result.
Create a Laravel Request object on the fly
I'm editing the development code passed to me by the customer. The code has a function that gets a request parameter from vue and translates it to JSON:
$json = $request->json()->get('data');
$json['some_key'];
This code returned an empty array of data:
$json = $request->request->add([some data]);
or
$json = $request->request->replace([some data]);
this one returned an error for missing the add parameter
$json = $request->json->replace([some data]);
A variant was found by trying and errors. Maybe, it help someone save time:
public function index() {
$myRequest = new \Illuminate\Http\Request();
$myRequest->json()->replace(['data' => ['some_key' => $some_data]]);
$data = MyClass::getData($myRequest);
}
..
class MyClass extends ...
{
public static function getData(Request $request) {
$json = $request->json()->get('data');
$json['some_key'];
In addition, there are other fields in the class that you can also slip data into so that you can pass everything you want via Request
$myRequest->json()->replace(['data' => ['some_key' => $some_data]]);
..
$myRequest->request->replace(['data' => ['some_key' => $some_data]]);
..
$myRequest->attributes->replace(['data' => ['some_key' => $some_data]]);
..
$myRequest->query->replace(['data' => ['some_key' => $some_data]]);
$myRequest = new \Illuminate\Http\Request();
$myRequest->setMethod('POST');
$myRequest->request->add(['foo' => 'bar']);
dd($request->foo);
This from the link you shared works, give it a try. Thanks for sharing that link!
I'm new to Laravel. I need to retrieve specific data from the database using the JSON decode. I am currently using $casts to my model to handle the JSON encode and decode.
This is my insert query with json encode:
$request->validate([
'subject' => 'required|max:255',
'concern' => 'required'
]);
$issue = new Issue;
$issue->subject = $request->subject;
$issue->url = $request->url;
$issue->details = $request->concern;
$issue->created_by = $request->userid;
$issue->user_data = $request->user_data; //field that use json encode
$issue->status = 2; // 1 means draft
$issue->email = $request->email;
$issue->data = '';
$issue->save();
The user_data contains {"id":37,"first_name":"Brian","middle_name":"","last_name":"Belen","email":"arcega52#gmail.com","username":"BLB-Student1","avatar":"avatars\/20170623133042-49.png"}
This is my output:
{{$issue->user_data}}
What I need to retrieve is only the first_name, middle_name, and last_name. How am I supposed to achieve that? Thank you in ADVANCE!!!!!
As per the above code shown by you it will only insert data into the database.For retrieving data you can make use of Query Builder as i have written below and also you can check the docs
$users = DB::table('name of table')->select('first_name', 'middle_name', 'last_name')->get();
I will recommend using Resources. It really very helpful laravel feature. Check it out. It is a reusable class. You call anywhere and anytime.
php artisan make:resource UserResource
Go to your the newly created class App/Http/Resources/UserResource.php and drfine the column you want to have in your response.
public function toArray($request) {
return [
"first_name" => $this->first_name,
"middle_name" => $this->middle_name,
"last_name" => $this->last_name
]
}
Now is your controller you can use the UserResource like folow:
public function index()
{
return UserResource::collection(User::all());
}
Or after inserting data you can return the newly added data(f_name, l_name...)
$user = new User;
$user->first_name= $request->first_name;
$user->middle_name= $request->middle_name;
$user->last_name= $request->last_name;
$user->save();
$user_data= new UserResource($user);
return $user_data;
I try to program a query in Yii2, which shows me the highest value of the database. Unfortunately, I get error message:
"Call to a member function all() on string"
How to patch this problem?
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Country;
class CountryController extends Controller
{
public function actionIndex()
{
$query = Country::find();
$countries = $query->select('population')->max('population')
->all();
return $this->render('index', [
'countries' => $countries,
]);
}
}
?>
You can use this
$query = Country::find();
$countries = $query->select('population')->max('population');
Also you can use
$query = Country::find();
$countries=$query->select('max(population) as `population`')->one();
It will help you :)
You have put as 'population' or other field name in table to assign value in second query.
According to your code example, you are calling all() on the result of max(), which according to the error message is returning a string.
max() is returning the maximum value, so you probably just need to drop ... ->all().
Try this:
$countries = $query->select('population')->max('population');
I'm trying to use the model create option and this is my array:
$result = array(
'match_id' => $input['id'],
'score' => $input['score'],
'result' => $input['result'],
'headline' => NULL,
'article' => $input['report'],
'tries' => $input['try'],
'try_amount' => $input['tryquant'],
'conversions' => $input['conv'],
'conv_amount' => $input['convquant'],
'penalties' => $input['pens'],
'pen_amount' => $input['penquant'],
'dropgoals' => $input['dgs'],
'dg_amount' => $input['dgquant']
);
Result::create($result);
The contents of some of these are arrays themselves. eg:
$input['penquant'] = [
"4"
]
When I run my code, it saves the data to the DB simply as Array and throws up the following error:
ErrorException in helpers.php line 703: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
Can someone tell me what I'm doing wrong and how to fix it?
Shouldn't have rushed, forgot to use json_encode.
The best is to use mutators and accessors in your model.
example of mutator
// convert pen_amount from snake case to studly case
// The set...attribute (the ... is you field name which is in studly case) helps transform the data before you save it
// into the database
public function setPenAmountAttribute($value)
{
$this->attributes['pen_amount'] = serialize($value);
}
example of an accessor is
// convert pen_amount from snake case to studly case
// the get...Attribute (the ... is you field name which is in studly case) helps you convert the data back to it original state
public function getPenAmountAttribute($value)
{
return unserialize($value);
}
You can use accessors and mutators for all your fields that you want to save as array. This is elegant. No need to manually use json_encode and decode in your controllers.
Let me preface this by saying I'm new to AngularJS & CodeIgniter.
Trying to create a single page app. In the center it displays news stories. On the side is a form to submit new stories. I'm to the point where the stories display fine from the DB. But when I try to create new stories from the form on the side, it enters 0 into the DB. I assume I have an issue with my function in the model. And it's probably as basic as not having the information encoded correctly to pass between MVC.
index.php
<div class="span2" ng-controller="NewStoryCtrl">
<h4>New Story</h4>
<form name="newStory">
<label for="title">Title: </label>
<input type="text" name ="title" ng-model="news.title" required>
<label for="text">Text: </label>
<textarea type="text" name="text" ng-model="news.text"required></textarea>
<button ng-click="createNews()">Submit</button>
</form>
controller.js
function NewStoryCtrl($scope, $http) {
$scope.news = {title:$scope.title, text:$scope.text};
$scope.createNews = function(){
$http.post('/ci/index.php/news/create/',$scope.news);
};}
news.php (controller)
public function create() {
$this->news_model->set_news();
}
news_model.php (model)
public function set_news() {
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'time' => time(),
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
The stuff in the model is leftover from my initial CI news tutorial. That's why I assume the error is here.
What's the best way to pass the information from the controllers.js to the model?
As expected, my issue was with not getting the right type of data. Controller was expecting a variable, but in Angular controller I was passing it as JSON. I hadn't ever gone through decoding.
news.php (controller)
public function create() {
$data = json_decode(file_get_contents('php://input'), TRUE);
$this->news_model->set_news($data);
}
And then in the model, I just needed to pass it as a parameter to set_news(). I ended up changing some variable names, just for personal clarification.
*news_model.php*
public function set_news($data) {
$this->load->helper('url');
$slug = url_title($data['title'], 'dash', TRUE);
$retval = array(
'title' => $data['title'],
'slug' => $slug,
'time' => time(),
'text' => $data['text']
);
return $this->db->insert('news', $retval);
}
I haven't used Angular.js, but your data format is probably correct. For example, Backbone sends a single $_POST variable called model with json encoded data, as I have used it.
It is imperative that you use Firebug, Webdev or other tools to see what is going on when you try to do AJAX work like this; otherwise you will go crazy . Look at the variable being sent to your backend - it is probably described, an encoded single var you will need to collect, json_decode, CLEAN & VALIDATE and then use.