Laravels Artisan::call('migrate:status') as json response - json

I want to get the migration status of my laravel app in a controller as json response and I try
$migratiorns = \Artisan::call('migrate:status');
return response()->json($migratiorns);
but \Artisan::call returns an integer 0.
What should I use for my case to get the desired response?

The value of $migration will be the output you see on the command line, which is sort of a table, its basically a string value which cannot be converted to json.

An easy way is the following
\Artisan::call('migrate:status');
dd(Artisan::output());

The question is quite old but I got the same problem and didn't find any solution so I made a little helper function to get pending migrations on the fly, maybe it will help someone else:
function getPendingMigration($migrationsFolderPath = false, $toJson = false)
{
$migrationsFolderPath = $migrationsFolderPath ?: database_path('/migrations');
$migrations = app('migrator')->getMigrationFiles($migrationsFolderPath);
$pendingMigrations = [];
foreach ($migrations as $migration => $fullpath){
if(!\Illuminate\Support\Facades\DB::table('migrations')->where('migration', $migration)->exists())
array_push($pendingMigrations, $migration);
}
return $toJson ? json_encode($pendingMigrations) : $pendingMigrations;
}

Here ini my console code
protected $signature = 'command:name {json?}';
ini handle function
public function handle()
{
$json = $this->argument('json');
if($json){
$a = ['foo'=>
['bar', $json]
];
$a = collect($a);
$this->info($a->toJson());
} else {
$this->info('Display this on the screen');
}
}
just run
php artisan command:name -json
will get json output

Related

Retrieve specific data using JSON decode Laravel

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;

How to fetch data from database with 3 parameters Laravel

I'm still new to this laravel, for now I'm facing a trouble for fetching data from the database. What i want to get is when there are only one data available, the second parameters won't be executed, but if there are some data available on the second parameters, then all the data from first parameter and the second parameter will be called.
$detail = Barang_Keluar_Detail::findOrFail($id); //15
$cariid = $detail->pluck('barang_keluar_id');
$instansiquery = Barang_Keluar::where('id',$cariid)->first(); //21
$instansiid = $instansiquery->pluck('instansi_id');
$tanggal = $instansiquery->pluck('tanggal')->first();//2019-12-31
and the parameter are here
$cariinstasama = Barang_Keluar::where('id', $cariid)
->orWhere(function ($query) use($instansiid, $tanggal) {
$query->where('tanggal', "'$tanggal'")
->where('instansi_id', $instansiid);
});
Please any help will be appreciated, thank you.
Laravel query builder provides elegant way to put conditional clause using when() . You can put conditional clause on your query like this:
$cariinstasama = Barang_Keluar::where('id', $cariid)
->when($instansiid, function ($query, $instansiid) {
return $query->where('instansi_id', $instansiid);
})
->when($tanggal, function ($query, $tanggal) {
return $query->where('tanggal', $tanggal);
})->get();
For more info see https://laravel.com/docs/5.8/queries#conditional-clauses
You can try this as well.
$cariinstasama = Barang_Keluar::where('id', $cariid);
if($instansiid !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
if($tanggal !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
$result = $cariinstasama->get();
Its not clear what exactly you want.
Are you applying more than one parameter on the query if the first parameter result gives you more than one row in the database? If yes check out my approach :
$query = new Model(); // the model you want to query
if($query->where('col1', $param1)->count() > 1) // checks if the query from the 1st parameter produces more than one row in the database
$query = $query->where( // if yes apply more parameters to the query
[
['col1', $param1],
['col2', $param2]
]
);
else
$query = $query->where('col1', $param1);
$results = $query->get();
Hope it helps....

How can I call a member function on an Array with two parameters?

in my Controller:
$relationEntity = $this->getDoctrine()->getRepository(Data::class)->findPosition($dataId,$documentId);
$relationEntity->setContent("hello");
in my Repository:
public function findPosition($dataId,$documentId) {
return $this->createQueryBuilder('data')
->leftJoin('data.documents', 'dd')
->andWhere('dd.uuid = :documentId')
->andWhere('data.document_id = :dataId')
->setParameter('documentId', $documentId)
->setParameter('dataId', $dataId)
->getQuery()
->execute();
}
I get the error message:
Call to a member function setContent() on array
I know that it would work with findOnebybut then I cannot find the entry I want to edit by two parameters. So I am not sure what to do now.
I found the solution:
foreach ($relationEntity as $r) {
$r->setContent("hello");
}
If you use custom repository you should return getResult() istead of execute, try this:
$datas = $this->createQueryBuilder('data')
->leftJoin('data.documents', 'dd')
->andWhere('dd.uuid = :documentId')
->andWhere('data.document_id = :dataId')
->setParameter('documentId', $documentId)
->setParameter('dataId', $dataId)
->getQuery()
->getResult();
return $datas[0];
If you are sure of query return only one row, you can return first result.

HTML response when passing an Object in Zend Controller using end_Json_Encoder::encode

I Have two problem in this Case :
I want to pass a JSON object that i created in Zend Controller
public function exampleAction() {
$answers = array();
for($i = 0 ; $i < 3 ; $i++)
{
$answer = new Answer();
$answer->answer_id = 5 ; // for example
$answer->thanked = 'true';// for example
$answers[] = $answer;
}
echo Zend_Json_Encoder::encode($answers);
}
the Jquery Post function is :
$.post(
"/memberactions/getthanks/",
{values:values},
function(res){
alert(123);
}
, 'json')
First Question :
why the return response is HTML ? the response must be in JSON ?
Second Question
the HTML response is like this
[{"__className":"Answer","thanked":"true","answer_id":"5"}]
How can I make the response like this :
- answer
thanked : true
answer_id : 5
as a JSON Object without the __className:"Answer" (does it hurt to have the class name in the response) ?
Have you disabled layout, viewRenderer etc.? Also, you should send appropriate headers. You can do all this at once using the JSON action helper:
$this->_helper->json($answers);
You could provide a toArray() method in Answer, which would return an array of relevant properties and then use it in your action:
$answers[] = $answer->toArray();

Functional test: how to set JSON data in a POST method?

I want to create a functional test for an action that receives a POST method with data in JSON format.
This is what I have:
info('set car')->
post('/user/'.$user->getId().'/set-car/'.$car->getId()'->
with('request')->ifFormat('json')->begin()->
isParameter('module', 'myModule')->
isParameter('action', 'myAction')->
end()->
But..where should I set the receiving json data?
sf 1.4
Regards
Javi
Did you checked out the page from Jobeet tutorial?
The first example is
$browser = new sfBrowser();
$browser->
get('/')->
click('Design')->
get('/category/programming?page=2')->
get('/category/programming', array('page' => 2))->
post('search', array('keywords' => 'php'))
;
It may be that I didn't understand you question at all.
Correct me if I'm wrong.
More of a workaround...
If you get the content in your action like this:
protected function getContent() {
$content = $this->request->getParameter('content');
if(!$content) $content = $this->request->getContent();
return $content;
}
public function executeIndex(sfWebRequest $request) {
$content = $this->getContent();
//do something with your content :D
}
that should allow you to test what you want by passing
post('search', array('content' => 'whatever my content is'));