Passing dependency parameters to App::make() or App::makeWith() in Laravel - php

I have a class that uses a dependency. I need to be able to dynamically set parameters on the dependency from the controller:
$objDependency = new MyDependency();
$objDependency->setSomething($something);
$objDependency->setSomethingElse($somethingElse);
$objMyClass = new MyClass($objDependency);
How do I achieve this through the Service Container in Laravel? This is what I've tried but this seems wrong to me. In my AppServiceProvider:
$this->app->bind('MyClass', function($app,$parameters){
$objDependency = new MyDependency();
$objDependency->setSomething($parameters['something']);
$objDependency->setSomethingElse($parameters['somethingElse']);
return new MyClass($objDependency);
}
And then in the controller i'd use this like:
$objMyClass = App:make('MyClass', [
'something' => $something,
'somethingElse' => $somethingElse
]);
Is this correct? Is there a better way I can do this?
Thanks

You can see detailed documentation here: https://laravel.com/docs/5.6/container#the-make-method
It's done like this:
$api = $this->app->makeWith('HelpSpot\API', ['id' => 1]);
Or use the app() helper
$api = app()->makeWith(HelpSpot\API::class, ['id' => 1]);
It is essential to set the array key as the argument variable name, otherwise it will be ignored. So if your code is expecting a variable called $modelData, the array key needs to be 'modelData'.
$api = app()->makeWith(HelpSpot\API::class, ['modelData' => $modelData]);
Note: if you're using it for mocking, makeWith does not return Mockery instance.

You can also do it this way:
$this->app->make(SomeClass::class, ["foo" => 'bar']);

Related

Laravel convert collect() to object dynamically

I need to create a collection from an array in Laravel and use -> to access my domain key, I've tried:
all()
first()
get()
What am I missing?
$domain = collect([
'domain' => 'test'
])->first();
I need to be able to use this syntax: $domain->domain which would then give me "test".
$domains = collect([(object)['domain' => 'test']]);
$domain = $domains->first();
// OR $domain = collect([(object)['domain' => 'test']])->first();
$domain->domain; // 'test'`
The (object)[...] syntax is called casting, and allows you to set certain variables as an explicit type, if possible. This code will create a Collection of a single Object, with a single property domain: 'Test', which you can access via -> syntax.
Note, if you're working with Models, you can use either -> or [] syntax:
$domains = Domain::get();
$domain = $domains->first();
$domain->domain; // 'test'
$domain['domain']; // 'test'

How to get insert id after save to database in CodeIgniter 4

I'm using Codeigniter 4.
And inserting new data like this,
$data = [
'username' => 'darth',
'email' => 'd.vader#theempire.com'
];
$userModel->save($data);
Which is mentioned here: CodeIgniter’s Model reference
It's doing the insertion.
But I haven't found any reference about to get the inserted id after insertion.
Please help! Thanks in advance.
This also works.
$user= new UserModel();
$data = [
'username' => 'darth',
'email' => 'd.vader#theempire.com'
];
$user->insert($data);
$user_id = $user->getInsertID();
I got a simple solution after researching on the core of the CI 4 framework.
$db = db_connect('default');
$builder = $db->table('myTable');
$data = [
'username' => 'darth',
'email' => 'd.vader#theempire.com'
];
$builder->insert($data);
echo $db->insertID();
Hope they'll add a clear description on the docs soon.
There are three way to get the ID in ci4:
$db = \Config\Database::connect();
$workModel = model('App\Models\WorkModel', true, $db);
$id = $workModel->insert($data);
echo $id;
echo '<br/>';
echo $workModel->insertID();
echo '<br/>';
echo $db->insertID();
In fact, what you did is correct.
You did it in the best and easiest way and following the Codeigniter 4 Model usage guide.
You just missed: $id = $userModel->insertID;
Complete code using your example:
$data = [
'username' => 'darth',
'email' => 'd.vader#theempire.com'
];
$userModel->save($data);
$id = $userModel->insertID;
That's it. You don't need all this code from the examples above nor calling database service or db builder if you're using codeigniter's models.
Tested on CodeIgniter 4.1.1 on 3/19/2021
To overcome this, I modified system/Model.php in the save() method---
$response = $this->insert($data, false);
// add after the insert() call
$this->primaryKey = $this->db->insertID();
Now, in your models, you can just reference "$this->primaryKey" and it will give you the needed info, while maintaining the data modeling functionality.
I'm going to submit this over to the CI developers, hopefully it will be added in.
For CI4
$settings = new SettingsModel();
$settingsData = $settings->find(1);
<?php namespace App\Models;
use App\Models\BaseModel;
class SettingsModel extends BaseModel
{
protected $table = 'users';
protected $primaryKey = 'id';
}
$settings->find(1); will return a single row. it will find the value provided as the $primaryKey.
hi guys in my case i use ci model to save data and my code is :
$x=new X();
$is_insert= $x->save(['name'=>'test','type'=>'ss']);
if($is_insert)
$inserted_id=$x->getInsertID()
I'm using mysql for my database then I ran this inside my seeder
$university = $this->db->table('universities')->insert([
'name' => 'Harvard University'
]);
$faculty = $this->db->table('faculties')->insert([
'name' => 'Arts & Sciences',
'university' => $university->resultID
]);
Look at code line 6
$university->resultID
variable $university here is type object of CodeIgniter\Database\MySQLi\Result class
Corect me if I'm wrong or any room for improvements
I had the same problem but, unfortunately, the CI4 documentation doesn't help much. The solution using a builder woks, but it's a workaround the data modeling. I believe you want a pure model solution, otherwise you wouldn't be asking.
$data = [
'username' => 'darth',
'email' => 'd.vader#theempire.com'
];
$id = $userModel->save($data);
Trying everything I could think of I decided to store the result of the save method to see if returned a boolean value to indicate if the saving was sucessful. Inspecting the variable I realized it returns exactly what I wanted: the lost insertID.
I believe CodeIgniter 4 is quite an easy and capable framework that does a decent job in shared hosts where other frameworks can be a little demanding if you're learning but lacks the same fantastic documentation and examples of CI3. Hopefully, that's only temporary.
By the way, you code works only if you are using the $userModel outside the model itself, for example, from a Controller. You need to create a model object like:
$userModel = New WhateverNameModel();
$data = [any data];
$userModel->save($data);
Alternatively, if you are programming a method inside the model itself (my favorite way), you should write
$this->save($data);

UpdateOrCreate Model Object

I am using Laravel 5.5 and I am declaring my model object the following:
$product = new product();
$product->name = $coinArr[$key];
$product->symbol = $symbolArr[$key];
$product->current_price = $priceArr[$key];
///save image to public folder
$fileName = basename($imgArr[$key]);
Image::make($imgArr[$key])->save(public_path('images/' . $fileName));
$product->asset_logo = $fileName;
//$product->updateOrCreate();
App/Product::updateOrCreate($product);
If the product does not exist in the database I would like to create it else just update it.
I tried the following two ways to use the updateOrCreate method. However, I receive the following error for App/Product::updateOrCreate($product);:
Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::updateOrCreate(), 0 passed in C:\Users\admin\Desktop\Coding Projects\laravel_proj\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 1455 and at least 1 expected
And the following error for $product->updateOrCreate();:
Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::updateOrCreate()
Any suggestions how to use updateOrCreate with my model object?
I appreciate your replies!
When you use updateOrCreate, you need to choose which attributes are used to determine if the product exists already. The function takes 2 arrays:
product::updateOrCreate([
'name' => $coinArr[$key] //Laravel will check if this model exists by name
],[
'symbol' => $symbolArr[$key] //if exists, will update symbol. if doesnt exist, will create new with this name and symbol
]);
That's not how the updateOrCreate() method works. In the first parameter you put an array with search conditions. If you want to search existing route by name for example, the correct syntax will be:
Product::updateOrCreate(
[
'name' => $coinArr[$key]
],
[
'symbol' => $symbolArr[$key],
'current_price' => $symbolArr[$key],
'asset_logo' => $fileName
]
);
The second parameter is array for creating a new object.
https://laravel.com/docs/5.5/eloquent#other-creation-methods

Return object base on request uri

so I have this modular web application that has doctrine2 intergrated with zend framework 1.12.
So I want to return one object base on the request uri, for example: url/api/people/1, which return the person one base on their id.
*side note, I can return all objects of people, I just want to select one object once the user enter's a number.
What I have tried, was to grab the parameter from the url and just pass it through the find function, but doctrine doesn't understand these numbers passed through the uri, and believes they're actions.
if($this->getRequest()->isGet())
{
$request = $this->getRequest();
$id = $request->getParam('peopleId');
$em = $this->getEntityManager();
$peopleRepo = $em->getRepository('API\Entity\People');
$people = $peopleRepo->find(3); //$id goes into find function
$resultArray[] =
[
'id' => $people->getId(),
'firstname' => $people->getFirstName(),
'lastname' => $people->getLastName(),
"food" => $people->getFavoriteFood()
];
echo json_encode($resultArray, JSON_PRETTY_PRINT);
var_dump($people);
*****EDIT*****
So I have added code that I can manually find one person, but I want to do that through the url, how can I achieve this?
Try:
$peopleRepo = $em->getRepository('API\Entity\People')->findBy(array('id' => $id));
Or
$peopleRepo = $em->getRepository('API\Entity\People')->findById($id);
See Doctrine docs:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#by-simple-conditions

laravel controller compact doesn't work

In my Routes I have:
Route::get('/about','PagesController#about');
In PagesController:
public function about()
{
$people=['Taylor','Matt','Jeffrey'];
return view('pages.about',compact($people));
}
if I use
return view('pages.about',['people'=> $people]);
It runs ok.
The controller isn't passing the array to view, why ?
Use
compact('people')
If you're a beginner checkout the laracasts video series to get a good understanding of the Laravel framework.
Remove $ sign inside compact function like compact('people'). This will solve your issue.
compact() is not a Laravel function. It is a PHP function. It creates an array containing variables and their values.
For an example, assume you have following variables.
$name = 'Jon Snow';
$dad = 'Rhaegar Targaryen';
$mom = 'Lyanna Stark';
If you put those in a compact() as follows,
$thePrinceThatWasPromised = compact(['name', 'dad', 'mom']);
You'll get following array assigned to $thePrinceThatWasPromised.
[
'name' => 'Jon Snow',
'dad' => 'Rhaegar Targaryen',
'mom' => 'Lyanna Stark'
]
For more information go to php manual

Categories