Specific question Laravel Database Homepage - php

I started using Laravel few days before.
I'm actually struggling with a problem, I created a homepage and I want to replace some text of the page with content from my database.
So how do I create a model/controller, and after that I will make an admin panel, so I can edit them.
The only tutorials/docs I see are for making a form/post to create users
Example
In basic php it's easy you just do a pdo connection and then a fetch and you use your date as you want. How do you do it in laravel ?

To fetch data from the DB in Laravel can be done in 1 of two ways, 1. using a Model (the best way) or using a Query Builder, which is much more familiar to those migrating from pure PHP.
Using a Model
Create a model using php artisan make:Model (change Model with a name of your choosing) then open the model once created (found in app/Http/Models) and add the following under use HasFactory;:
protected $table = 'your_table_name';
protected $primaryKey = 'id'; // This is the column you usually set to PRIMARY
public $timestamps = true;
protected $fillable = [
'table_column',
'table_column',
];
To use the Model, import it into your Controller file like so use App\Models\Model; and then use it as so:
$flights = Flight::where('destination', 'Paris')->get();
Learn more about Models in Laravel here.
Using a Query Builder, not best practice
Import the DB facade in the controller like so use DB; then call upon it like so:
$db = DB::table('users')->where('name', 'John')->first();
Learn more about the Query Builder here.
I hope this helps, if not let me know how I can assist further.

Related

Advanced Laravel merged data/models - can it be done at model level?

We have a COMMON database and then tenant databases for each organization that uses our application. We have base values in the COMMON database for some tables e.g.
COMMON.widgets. Then in the tenant databases, IF a table called modified_widgets exists and has values, they are merged with the COMMON.widgets table.
Right now we are doing this in controllers along the lines of:
public function index(Request $request)
{
$widgets = Widget::where('active', '1')->orderBy('name')->get();
if(Schema::connection('tenant')->hasTable('modified_widgets')) {
$modified = ModifiedWidget::where('active', '1')->get();
$merged = $widgets->merge($modified);
$merged = array_values(array_sort($merged, function ($value) {
return $value['name'];
}));
return $merged;
}
return $countries;
}
As you can see, we have model for each table and this works OK. We get the expected results for GET requests like this from controllers, but we'd like to merge at the Laravel MODEL level if possible. That way id's are linked to the correct tables and such when populating forms with these values. The merge means the same id can exist in BOTH tables. We ALWAYS want to act on the merged data if any exists. So it seems like model level is the place for this, but we'll try any suggestions that help meet the need. Hope that all makes sense.
Can anyone help with this or does anyone have any ideas to try? We've played with overriding model constructors and such, but haven't quite been able to figure this out yet. Any thoughts are appreciated and TIA!
If you put this functionality in Widget model you will get 2x times of queries. You need to think about Widget as an instance, what I am trying to say is that current approach does 2 queries minimum and +1 if tenant has modified_widgets table. Now imagine you do this inside a model, each Widget instance will pull in, in a best case scenario its equivalent from different database, so for bunch of Widgets you will do 1 (->all())+n (n = number of ModifiedWidgets) queries - because each Widget instance will pull its own mirror if it exists, no eager load is possible.
You can improve your code with following:
$widgets = Widget::where('active', '1')->orderBy('name')->get();
if(Schema::connection('tenant')->hasTable('modified_widgets')) {
$modified = ModifiedWidget::where('active', '1')->whereIn('id', $widgets->pluck('id'))->get(); // remove whereIn if thats not the case
return $widgets->merge($modified)->unique()->sortBy('name');
}
return $widgets;
OK, here is what we came up with.
We now use a single model and the table names MUST be the same in both databases (setTable does not seem to work even though in exists in the Database/Eloquent/Model base source code - that may be why it's not documented). Anyway = just use a regular model and make sure the tables are identical (or at least the fields you are using are):
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Widget extends Model
{
}
Then we have a generic 'merge controller' where the model and optional sort are passed in the request (we hard coded the 'where' and key here, but they could be made dynamic too). NOTE THIS WILL NOT WORK WITH STATIC METHODS THAT CREATE NEW INSTANCES such as $model::all() so you need to use $model->get() in that case:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class MergeController extends Controller
{
public function index(Request $request)
{
//TODO: add some validations to ensure model is provided
$model = app("App\\Models\\{$request['model']}");
$sort = $request['sort'] ? $request['sort'] : 'id';
$src_collection = $model->where('active', '1')->orderBy('name')->get();
// we setup the tenants connection elsewhere, but use it here
if(Schema::connection('tenant')->hasTable($model->getTable())) {
$model->setConnection('tenant');
$tenant_collection = $model->get()->where('active', '1');
$src_collection = $src_collection->keyBy('id')->merge($tenant_collection->keyBy('id'))->sortBy('name');
}
return $src_collection;
}
}
If you dd($src_collection); before returning it it, you will see the connection is correct for each row (depending on data in the tables). If you update a row:
$test = $src_collection->find(2); // this is a row from the tenant db in our data
$test->name = 'Test';
$test->save();
$test2 = $src_collection->find(1); // this is a row from the tenant db in our data
$test2->name = 'Test2'; // this is a row from the COMMON db in our data
$test2->save();
dd($src_collection);
You will see the correct data is updated no matter which table the row(s) came from.
This results in each tenant being able to optionally override and/or add to base table data without effecting the base table data itself or other tenants while minimizing data duplication thus easing maintenance (obviously the table data and population is managed elsewhere just like any other table). If the tenant has no overrides then the base table data is returned. The merge and custom collection stuff have minimal documentation, so this took some time to figure out. Hope this helps someone else some day!

Jenssegers MongoDB dot notation in fillable

I'm trying to get the dot notation working in Jenssegers MongoDB package for Laravel. According this issue it's already been implemented:
link
But it doesn't seem to work in the latest version.
protected $fillable = ['title', 'some.data'];
Doesn't work. But if I open it all up it works fine.
protected $guarded = [];
So that works, not sure if this feature is still there or I need to pre filter my fields manually for now?
Nested fields are not currently supported in $fillable.
Unfortunately this means you have to do it manually. There are two ways to go:
If you have an embedded Some model, you can set $fillable on that, create/fill it with new data, then attach it to the parent model.
If you don't have/want a whole separate model for your subdocument, you would have to define e.g. $someFillable = ['data']; and use that to filter your new $some data prior to manually setting it on the model. You can basically just copy how Eloquent does it in its fill method.

Questions about Using laravel with several models / MySQL tables

I'm new with laravel + frameworks and i'm having a few issues.I read the laravel documentation and tried asking for support on their forums - no results/
In my current setup - I followed the laravel documentation & code
I have 1 Model : User
I have 1 table in the db : users
Everything works fine for the login / registration parts etc....
However now i need to create several new tables & maybe some more models :
I searched the web and there are no tutorials or anything else to guide me how to do it.
Any help would be greatly appreciated .
Tried :
In Models -
created : profile.php
class Profile extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'profile';
}
It doesn't seem to work , I'm wondering if i have to link the file or something in the laravel framework etc..
P.s : I used artisan and migrations to create the user table
I am now creating the tables directly in the database but i have no idea how to access them such as :
in the user table , i can use :
Auth::user()->username - to get the username
however in the new table (profile) -
I have absolutely no idea how to access it using laravel code.
Have you read over the documentation http://laravel.com/docs/eloquent?
Create a new file inside of ../app/models/
../app/models/Profile.php
** note the file matches the classname
inside the model:
class Profile extends Eloquent {
protected $table = 'profile';
}
Then in your controller or route closure access the model via
$profile = Profile::find(1);
or
$profile = App::make('Profile');
$profile->about = 'About the user';
$profile->save();

Cannot insert to my new table

I have created a migration for ratings, and the table also working when i am entering phpmyadmin.
The problem is, i cannot figure out, how to write to the table?
I am running the code from "story" controller
I am using this:
$z = new Rating();
$z->story_id = 10;
$z->save();
print_r($z);
My "ratings.php" model:
<?php
class Rating extends Eloquent {
protected $table = 'ratings';
}
?>
Is there some place where i should notify laravel that new Rating() means my table "ratings"?
It doesn't seem like i have done the migration correctly, but i am completely new still, so hope someone can figure it out for me.
well instead of using the save() function for laravel you can use the insert() function
Rating->insert_get_id(array('story_id' => '10'));
or
$insert_id = Rating->insert_get_id(array('story_id' => '10'));
for insertion into table.This is much easy to use and I have used this in my whole project and so far I haven't face any problems.
Also if you have not created the model for rating table then go to the models folder under application folder and create a file name rating.php and inside the file write this:
class Rating extends Eloquent
{
public static $timestamps = false;
}
Also please note that table which you created in the phpmyadmin should have name of the form "ratings".
I hope this can be of some help.
I don't really understand what you're doing. Are you trying to write into the table from php? Is Rating a sort of database connection class? You need to create a mysqli object to connect to the database, write a query, and get a result. For best security use a prepared statement. Mysqli Documentation Sorry if I'm off-base about your question, I'm just not positive about what it is.

Kohana 3.2 reuse model to insert data

I'm currently working on a project that uses Kohana 3.2.
I haven't used the framework so I'm kind of a "beginner" though I've been using Symfony2 for quite some time.
Let's say I have a "task". This "task" can be assigned to multiple "users" at the same time.
This is achieved by entering the same "task" with different user_id. So I thought it shouldn't be a problem to reuse the model by simply to change the column's data and then calling $task->create().
For some reason this isn't working right and the code returns:
Kohana_Exception [ 0 ]: Cannot create task model because it is already loaded.
My current code is:
Model:
class Model_Task extends ORM{
protected $_table_name = 'task';
protected $_primary_key = 'task_id';
}
Code:
$task = ORM::factory('task');
$task->task = "some random task you need to finish.";
foreach($users as $user){
$task->user_id=$user;
$task->create();
}
Am I doing something wrong or you simply can't reuse models in Kohana?
You are using the same task object for all users, thus after first iteration task will be loaded after calling create method. Change your code to:
foreach($users as $user)
{
$task = ORM::factory('task');
$task->user_id = $user;
$task->create();
}

Categories