raheelkhan's avatar

Model Approach like ASP.NET MVC in Laravel

I am trying to achieve something similar to the Dot Net framework in Laravel. As we declare all of our table columns in the Model and in the controller we can simply call them using model object.

  1. WHAT I WANT (Something Similar)
public function functionaName(){
	$object = ModelName::class
         $items = Item::select($object->name1, $object->name2)->get()
	return view('welcome', compact('items');
}

And want to achieve the same in Blade's view as well.

  1. Currently, what I am doing is;

That I have created constant fields in my Model

	public const ItemName = "ItemName";
	public const ItemQuantity = "Quantity";

and In my Controller, I used them like

	$items = Item::select(Item::ItemName, Item::ItemQuantity)->get();

is this the right approach? if not, then what is the best approach?

Thank you

0 likes
11 replies
martinbean's avatar

@raheelkhan What, exactly, are you trying to accomplish? Why are you just creating constants with exactly the same name as your column names, instead of just referencing your column names directly?

1 like
jlrdw's avatar

Just test data:

I've seen like:

        public Pet GetPetData(int? id)
        {
            Dbcon ob = new Dbcon();
            Pet pet = new Pet();
            using (var context = ob.OpBuilder())
            {

                var data = (from p in context.Pet
                            where p.PetID == id
                            select p).SingleOrDefault();

                pet = data;
                return pet;

            }

And of course regular sql server:

        public IEnumerable<Pet> GetAllPets(int pageno, string petname)
        {
            var thispage = pageno;
            var thisoffset = (thispage - 1) * 5;

            string name = petname;
            using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=petdate;Integrated Security=False;Persist Security Info=False;User ID=zzz;Password=zzzzzzzzzz"))
            {
                List<Pet> lstpet = new List<Pet>();
                SqlCommand cmd = new SqlCommand("SELECT * FROM pets WHERE petname LIKE @lastname ORDER BY petname OFFSET " + thisoffset + " ROWS FETCH NEXT 5 ROWS ONLY", conn);

                cmd.Parameters.AddWithValue("@lastname", name + "%");

                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();

                //var reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    Pet pet = new Pet();
                    pet.PetId = Convert.ToInt32(reader["petid"]);
                    pet.PetName = reader["petname"].ToString();
                    pet.DogPic = reader["dogpic"].ToString();
                    
                    if (!reader.IsDBNull(reader.GetOrdinal("odate")))
                    {
                        pet.Odate = reader.GetDateTime(reader.GetOrdinal("odate"));
                    }
                    
                    pet.Ocheck = Convert.ToBoolean(reader["ocheck"]);
                    lstpet.Add(pet);
                }
                conn.Close();
                return lstpet;
            }

            

        }

Can you give a reference to asp.net on that technique you mentioned.

In laravel I just do field names just like other languages do.

If you view the from scratch free video series, do just like @jeffreyway does in the videos, and you will be fine.

1 like
raheelkhan's avatar

@martinbean @jlrdw Let me explain, In ASP.NET we can reference the Column name in Razor Views and Controllers by calling Model.Column name.

I just want to achieve that approach in my Laravel project.

If I go this way

$items = select("Id", "Name", "Quantity", "Quality", "Price", "GST")->get();

and in the future, I change the column name for GST to GovernmentServiceTax Then I will need to manually update the column name everywhere in my project.

That's all I want if we can declare them in one place and call it everywhere we need. changes in one place automatically change everywhere.

that's why I declared them in Model as constant to let it call anywhere in my controller.

jlrdw's avatar

In asp.net I have never seen that feature where it changes everywhere, can you give a reference to the feature in their Documentation.

I use a grep tool, fast and easy.

I know you have to have a model like

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace pcore31.Models
{
    [Table("pets")]
    public class Pet
    {
        [Key]
        public int PetID { get; set; }
        [Required(ErrorMessage = "Enter Name")]
        public string PetName { get; set; }

        public string Dogpic { get; set; }
               
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime? Odate { get; set; }
        public bool Ocheck { get; set; }


    }
}


But if I change Odate to Mydate, it doesn't change everywhere.

You would have to re-scaffold views, etc.

MichalOravec's avatar

Usually you want to get a full object.

$items = Item::all();

// or 

$items = Item::where('something', 'is_something')->get():

And maybe just a few times you use select(), so I think it doesn't matter.

By the way how often you change the column name? Think about it and then don't change it. That's it.

jlrdw's avatar

@michaloravec but still in the view you would need new field name when displaying data, if you changed a field name.

Otherwise use alias for field name.

That's why I suggested grep tool.

Many IDE's have grep built in.

martinbean's avatar

@raheelkhan Eloquent is an ORM. It’s meant to map objects to rows in your database.

If I tried to use an Eloquent ORM and the properties had different names to the columns in the database, I’d hunt that developer down…

raheelkhan's avatar

@michaloravec @martinbean @jlrdw I feel like I did not correctly ask the question in a proper way.

I will explain it with examples.

IN ASP.NET MVC we can directly call the column names in view. like this;

@model NZMIS.Models.Area


<span>  @Model.AreaCode </span>

This way. I can see each column name in my Model and I don't need to check DB or table to check column names or anything else.

I want such an approach in Laravel.

jlrdw's avatar

IN ASP.NET MVC we can directly call the column names in view. like this;

That is a visual studio helper, it has nothing to do with the language itself.

Netbeans does the same with Java code.

Please or to participate in this conversation.